@seams/wallet 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/THIRD_PARTY_NOTICES.md +1 -127
- package/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/SeamsWeb/SeamsWeb.js +2 -0
- package/dist/esm/SeamsWeb/walletIframe/client/inboundMessages.js +9 -0
- package/dist/esm/SeamsWeb/walletIframe/client/router.js +30 -0
- package/dist/esm/SeamsWeb/walletIframe/coordinator.js +18 -0
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +88 -47
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.js +67 -0
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.js +13 -0
- package/dist/esm/SeamsWeb/walletIframe/host/walletMutationGuard.js +1 -0
- package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +20 -6
- package/dist/esm/SeamsWeb/walletIframe/shared/walletAlternatives.js +109 -0
- package/dist/esm/core/config/configBuilder.js +1 -1
- package/dist/esm/core/config/defaultConfigs.js +9 -2
- package/dist/esm/core/ui/messages.js +3 -1
- package/dist/esm/core/ui/walletIcon.js +10 -0
- package/dist/esm/externalEvm/boundary.js +4 -2
- package/dist/esm/react/components/HostedSeamsAuthMenu/shell.js +26 -6
- package/dist/esm/react/components/HostedSeamsAuthMenu/walletAlternatives.js +178 -0
- package/dist/esm/react/index.js +1 -2
- package/dist/esm/react/styles/styles.css +0 -183
- package/dist/esm/react/styles.css +0 -1
- package/dist/esm/sdk/{ConfirmationDrawer-BRnd5SEf.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
- package/dist/{public/sdk/NonceCoordinator-CNXYrOoy.js → esm/sdk/NonceCoordinator-C1lw03Ce.js} +1 -1
- package/dist/esm/sdk/{activeWalletSession-BJ4B-nJo.js → activeWalletSession-HAOgRKzn.js} +1 -1
- package/dist/esm/sdk/{adapters-B2k8y0MB.js → adapters-BY1wGpm5.js} +1 -1
- package/dist/esm/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
- package/dist/esm/sdk/{authorization-gVWwKwav.js → authorization-D_NueqAv.js} +1 -1
- package/dist/esm/sdk/{clientSessionPersistenceState-BxpITYM_.js → clientSessionPersistenceState-B3gU3515.js} +1 -1
- package/dist/esm/sdk/{commitQueue-C1wkey4q.js → commitQueue-CbyuhEW9.js} +1 -1
- package/dist/{public/sdk/confirm-ui-Dx6c4-Rk.js → esm/sdk/confirm-ui-DWFcGTsT.js} +1 -1
- package/dist/{public/sdk/device-linking-_o3_fgiG.js → esm/sdk/device-linking-BL2aDEUF.js} +1 -1
- package/dist/esm/sdk/{deviceLinkApproval-CObsEWBa.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
- package/dist/esm/sdk/{digestEncoding-34kXJoJr.js → digestEncoding-Rx8Vjy4J.js} +1 -1
- package/dist/esm/sdk/{display-CUWg48tD.js → display-8NGPOhQT.js} +1 -1
- package/dist/{public/sdk/ecdsaCapabilityManifest--1Ztngfx.js → esm/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
- package/dist/{public/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js → esm/sdk/ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
- package/dist/{public/sdk/ecdsaDerivationExport-BUUUGc6o.js → esm/sdk/ecdsaDerivationExport-jm2VBMz_.js} +1 -1
- package/dist/esm/sdk/{emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
- package/dist/esm/sdk/{export-viewer-host-O0OV1Oou.js → export-viewer-host-TzgdJQuZ.js} +1 -1
- package/dist/{public/sdk/exportKeypairOperation-DkqY9Bpf.js → esm/sdk/exportKeypairOperation-B9_ulzNz.js} +1 -1
- package/dist/esm/sdk/host-DltV2Oan.js +1 -0
- package/dist/esm/sdk/{indexedDB-CA4tGqkr.js → indexedDB-BqsYXybq.js} +1 -1
- package/dist/esm/sdk/{lanes-vBKm6yBJ.js → lanes-0WT2w1Xz.js} +1 -1
- package/dist/esm/sdk/{localOnly-U_MucUAe.js → localOnly-DFrtrfdO.js} +1 -1
- package/dist/esm/sdk/{mountExportPrivateKeySurface-C2-fnvP6.js → mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
- package/dist/{public/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js → esm/sdk/mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
- package/dist/esm/sdk/{nearEd25519YaoSigningPreparation-CnbgQfZc.js → nearEd25519YaoSigningPreparation-Cz2Gb95g.js} +1 -1
- package/dist/esm/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
- package/dist/esm/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
- package/dist/esm/sdk/{pendingWalletRecoveryCodeBackup-DXFrQmO5.js → pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
- package/dist/{public/sdk/presignaturePool-Dq4RhzXn.js → esm/sdk/presignaturePool-CaI45td2.js} +1 -1
- package/dist/esm/sdk/{presignatures-CkhuZ0YQ.js → presignatures-B9KnQyfE.js} +1 -1
- package/dist/esm/sdk/{recovery-entrypoint-s9OoKBcl.js → recovery-entrypoint-DA2FGLG6.js} +1 -1
- package/dist/esm/sdk/registration-Coh0_Nva.js +1 -0
- package/dist/esm/sdk/{registration-D3p7muCc.js → registration-XNyt1YRK.js} +1 -1
- package/dist/esm/sdk/{registrationIntent-C1-Kyx_-.js → registrationIntent-Cb3tggIM.js} +1 -1
- package/dist/{public/sdk/requireStepUpAuth-iVo6h_U-.js → esm/sdk/requireStepUpAuth-ByMTPBu4.js} +1 -1
- package/dist/esm/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
- package/dist/esm/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
- package/dist/esm/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/esm/sdk/runtime-auth-CP6P681o.js +1 -0
- package/dist/esm/sdk/{runtime-device-link-qmYvGep9.js → runtime-device-link-CGDZQK-D.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-Zh95TuLV.js → esm/sdk/runtime-ecdsa-tempo-BiJYKWK4.js} +1 -1
- package/dist/esm/sdk/{runtime-email-otp-CnLuW4H1.js → runtime-email-otp-B0XCNDRb.js} +1 -1
- package/dist/esm/sdk/{runtime-export-m8lvrXtw.js → runtime-export-CXxv6KIx.js} +1 -1
- package/dist/esm/sdk/{runtime-near-BiXzXXhH.js → runtime-near-CuyS57wu.js} +1 -1
- package/dist/esm/sdk/runtime-preferences-B2WBUZO7.js +1 -0
- package/dist/esm/sdk/runtime-recovery-KwVdSe94.js +1 -0
- package/dist/esm/sdk/{runtime-recovery-codes-B033ake_.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
- package/dist/esm/sdk/{runtimeContext-RNS2E5wy.js → runtimeContext-Iy1vecX0.js} +3 -3
- package/dist/esm/sdk/{secp256k1-DPeaOjM0.js → secp256k1-sDDAa4Ga.js} +1 -1
- package/dist/{public/sdk/signEvmFamily-Cksw3RpU.js → esm/sdk/signEvmFamily-CMrXkVsZ.js} +1 -1
- package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
- package/dist/esm/sdk/{signEvmWithUiConfirm-B14zYdwE.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
- package/dist/esm/sdk/{signNear-D0rFEYP1.js → signNear-DyFk--I3.js} +1 -1
- package/dist/{public/sdk/signingFlow-Bd1X0e-1.js → esm/sdk/signingFlow-DTP4D19E.js} +1 -1
- package/dist/{public/sdk/signingQueue-DoUBeaCv.js → esm/sdk/signingQueue-Dy5mYMus.js} +1 -1
- package/dist/esm/sdk/{thresholdEcdsa-BxfOZmiR.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
- package/dist/esm/sdk/{trace-BnhLKxcu.js → trace-BA8jya7O.js} +1 -1
- package/dist/{public/sdk/transactionState-G_FPe-U8.js → esm/sdk/transactionState-BCbaT2hO.js} +1 -1
- package/dist/esm/sdk/tx-confirm-ui.js +3 -1
- package/dist/esm/sdk/{types-A-w1cYlJ.js → types-D2Zk1W7I.js} +1 -1
- package/dist/{public/sdk/unlockedEd25519ExportRootCapability-5F1egCSv.js → esm/sdk/unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
- package/dist/esm/sdk/voiceid-host.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/esm/sdk/{wallet-recovery-DXdm68_Q.js → wallet-recovery-Bfm-oUoP.js} +1 -1
- package/dist/esm/sdk/wallet-ui.css +1 -1
- package/dist/{public/sdk/walletAuthMethodRecord-BW-XV4fv.js → esm/sdk/walletAuthMethodRecord--fvGr8r1.js} +1 -1
- package/dist/{public/sdk/walletAuthority-DbGaSw7D.js → esm/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
- package/dist/esm/sdk/{walletCustodyEcdsaContinuity-BnyL1Ryu.js → walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
- package/dist/esm/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
- package/dist/esm/sdk/{walletOwnerOperation-CScYv2K6.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
- package/dist/esm/sdk/{walletOwnershipGeneration-BZc6UKqX.js → walletOwnershipGeneration-B3uE9GRG.js} +1 -1
- package/dist/{public/sdk/walletRecoveryAdminProof-DdwikrW3.js → esm/sdk/walletRecoveryAdminProof-BmZaP0Q8.js} +1 -1
- package/dist/{public/sdk/walletRecoveryCommit-DbAoiJp5.js → esm/sdk/walletRecoveryCommit-CSYNbYNd.js} +1 -1
- package/dist/esm/sdk/{walletSessionAuthorizationStatus-GhcGvDCX.js → walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
- package/dist/{public/sdk/walletSessionAuthorizationStore-BivTUoKY.js → esm/sdk/walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
- package/dist/esm/shared-ts/src/utils/index.js +1 -1
- package/dist/esm/wasm/near_signer/pkg/wasm_signer_worker_bg.wasm +0 -0
- package/dist/esm/wasm/router_ab_ecdsa_client/pkg/router_ab_ecdsa_client_bg.wasm +0 -0
- package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.d.ts +212 -233
- package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.js +675 -694
- package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{ConfirmationDrawer-BRnd5SEf.js → ConfirmationDrawer-fyl4IDRl.js} +1 -1
- package/dist/{esm/sdk/NonceCoordinator-CNXYrOoy.js → public/sdk/NonceCoordinator-C1lw03Ce.js} +1 -1
- package/dist/public/sdk/{activeWalletSession-BJ4B-nJo.js → activeWalletSession-HAOgRKzn.js} +1 -1
- package/dist/public/sdk/{adapters-B2k8y0MB.js → adapters-BY1wGpm5.js} +1 -1
- package/dist/public/sdk/appearance-token-vars-CzlRDVQ7.js +1 -0
- package/dist/public/sdk/{authorization-gVWwKwav.js → authorization-D_NueqAv.js} +1 -1
- package/dist/public/sdk/{clientSessionPersistenceState-BxpITYM_.js → clientSessionPersistenceState-B3gU3515.js} +1 -1
- package/dist/public/sdk/{commitQueue-C1wkey4q.js → commitQueue-CbyuhEW9.js} +1 -1
- package/dist/{esm/sdk/confirm-ui-Dx6c4-Rk.js → public/sdk/confirm-ui-DWFcGTsT.js} +1 -1
- package/dist/{esm/sdk/device-linking-_o3_fgiG.js → public/sdk/device-linking-BL2aDEUF.js} +1 -1
- package/dist/public/sdk/{deviceLinkApproval-CObsEWBa.js → deviceLinkApproval-C4T8XAmi.js} +1 -1
- package/dist/public/sdk/{digestEncoding-34kXJoJr.js → digestEncoding-Rx8Vjy4J.js} +1 -1
- package/dist/public/sdk/{display-CUWg48tD.js → display-8NGPOhQT.js} +1 -1
- package/dist/{esm/sdk/ecdsaCapabilityManifest--1Ztngfx.js → public/sdk/ecdsaCapabilityManifest-BbPXL-qh.js} +1 -1
- package/dist/{esm/sdk/ecdsaDerivationClientWasm-DJh2uN-q.js → public/sdk/ecdsaDerivationClientWasm-GCt9yVsd.js} +1 -1
- package/dist/{esm/sdk/ecdsaDerivationExport-BUUUGc6o.js → public/sdk/ecdsaDerivationExport-jm2VBMz_.js} +1 -1
- package/dist/public/sdk/{emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js → emailOtpEcdsaDerivationIdentity-DJmMyqL-.js} +1 -1
- package/dist/public/sdk/{export-viewer-host-O0OV1Oou.js → export-viewer-host-TzgdJQuZ.js} +1 -1
- package/dist/{esm/sdk/exportKeypairOperation-DkqY9Bpf.js → public/sdk/exportKeypairOperation-B9_ulzNz.js} +1 -1
- package/dist/public/sdk/host-DltV2Oan.js +1 -0
- package/dist/public/sdk/{indexedDB-CA4tGqkr.js → indexedDB-BqsYXybq.js} +1 -1
- package/dist/public/sdk/{lanes-vBKm6yBJ.js → lanes-0WT2w1Xz.js} +1 -1
- package/dist/public/sdk/{localOnly-U_MucUAe.js → localOnly-DFrtrfdO.js} +1 -1
- package/dist/public/sdk/{mountExportPrivateKeySurface-C2-fnvP6.js → mountExportPrivateKeySurface-D8juRQJM.js} +1 -1
- package/dist/{esm/sdk/mountRecoveryCodeBackupSurface-C_tJNPJX.js → public/sdk/mountRecoveryCodeBackupSurface-CMtByh-L.js} +1 -1
- package/dist/public/sdk/{nearEd25519YaoSigningPreparation-CnbgQfZc.js → nearEd25519YaoSigningPreparation-Cz2Gb95g.js} +1 -1
- package/dist/public/sdk/{operationFingerprint-Bas59T7L.js → operationFingerprint-GKEY-X5I.js} +1 -1
- package/dist/public/sdk/ownerNearOperation-DCxxHcwX.js +1 -0
- package/dist/public/sdk/{pendingWalletRecoveryCodeBackup-DXFrQmO5.js → pendingWalletRecoveryCodeBackup-8iMhQU-E.js} +1 -1
- package/dist/{esm/sdk/presignaturePool-Dq4RhzXn.js → public/sdk/presignaturePool-CaI45td2.js} +1 -1
- package/dist/public/sdk/{presignatures-CkhuZ0YQ.js → presignatures-B9KnQyfE.js} +1 -1
- package/dist/public/sdk/{recovery-entrypoint-s9OoKBcl.js → recovery-entrypoint-DA2FGLG6.js} +1 -1
- package/dist/public/sdk/registration-Coh0_Nva.js +1 -0
- package/dist/public/sdk/{registration-D3p7muCc.js → registration-XNyt1YRK.js} +1 -1
- package/dist/public/sdk/{registrationIntent-C1-Kyx_-.js → registrationIntent-Cb3tggIM.js} +1 -1
- package/dist/{esm/sdk/requireStepUpAuth-iVo6h_U-.js → public/sdk/requireStepUpAuth-ByMTPBu4.js} +1 -1
- package/dist/public/sdk/resealedEnvelopeResult-DKY5fVNY.js +1 -0
- package/dist/public/sdk/routerAbNormalSigning-CPLDkttX.js +1 -0
- package/dist/public/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/sdk/runtime-auth-CP6P681o.js +1 -0
- package/dist/public/sdk/{runtime-device-link-qmYvGep9.js → runtime-device-link-CGDZQK-D.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-Zh95TuLV.js → public/sdk/runtime-ecdsa-tempo-BiJYKWK4.js} +1 -1
- package/dist/public/sdk/{runtime-email-otp-CnLuW4H1.js → runtime-email-otp-B0XCNDRb.js} +1 -1
- package/dist/public/sdk/{runtime-export-m8lvrXtw.js → runtime-export-CXxv6KIx.js} +1 -1
- package/dist/public/sdk/{runtime-near-BiXzXXhH.js → runtime-near-CuyS57wu.js} +1 -1
- package/dist/public/sdk/runtime-preferences-B2WBUZO7.js +1 -0
- package/dist/public/sdk/runtime-recovery-KwVdSe94.js +1 -0
- package/dist/public/sdk/{runtime-recovery-codes-B033ake_.js → runtime-recovery-codes-CFOWDVd9.js} +1 -1
- package/dist/public/sdk/{runtimeContext-RNS2E5wy.js → runtimeContext-Iy1vecX0.js} +3 -3
- package/dist/public/sdk/{secp256k1-DPeaOjM0.js → secp256k1-sDDAa4Ga.js} +1 -1
- package/dist/{esm/sdk/signEvmFamily-Cksw3RpU.js → public/sdk/signEvmFamily-CMrXkVsZ.js} +1 -1
- package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-B7p9UVix.js → signEvmFamilyWithUiConfirmForTempo-CnRoo0e8.js} +1 -1
- package/dist/public/sdk/{signEvmWithUiConfirm-B14zYdwE.js → signEvmWithUiConfirm-yITc3ZvP.js} +1 -1
- package/dist/public/sdk/{signNear-D0rFEYP1.js → signNear-DyFk--I3.js} +1 -1
- package/dist/{esm/sdk/signingFlow-Bd1X0e-1.js → public/sdk/signingFlow-DTP4D19E.js} +1 -1
- package/dist/{esm/sdk/signingQueue-DoUBeaCv.js → public/sdk/signingQueue-Dy5mYMus.js} +1 -1
- package/dist/public/sdk/{thresholdEcdsa-BxfOZmiR.js → thresholdEcdsa-CRfx6RP1.js} +1 -1
- package/dist/public/sdk/{trace-BnhLKxcu.js → trace-BA8jya7O.js} +1 -1
- package/dist/{esm/sdk/transactionState-G_FPe-U8.js → public/sdk/transactionState-BCbaT2hO.js} +1 -1
- package/dist/public/sdk/tx-confirm-ui.js +3 -1
- package/dist/public/sdk/{types-A-w1cYlJ.js → types-D2Zk1W7I.js} +1 -1
- package/dist/{esm/sdk/unlockedEd25519ExportRootCapability-5F1egCSv.js → public/sdk/unlockedEd25519ExportRootCapability-BbGMlikr.js} +1 -1
- package/dist/public/sdk/voiceid-host.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/public/sdk/{wallet-recovery-DXdm68_Q.js → wallet-recovery-Bfm-oUoP.js} +1 -1
- package/dist/public/sdk/wallet-ui.css +1 -1
- package/dist/{esm/sdk/walletAuthMethodRecord-BW-XV4fv.js → public/sdk/walletAuthMethodRecord--fvGr8r1.js} +1 -1
- package/dist/{esm/sdk/walletAuthority-DbGaSw7D.js → public/sdk/walletAuthority-CU9nO0Ze.js} +1 -1
- package/dist/public/sdk/{walletCustodyEcdsaContinuity-BnyL1Ryu.js → walletCustodyEcdsaContinuity-BUdDyRl_.js} +1 -1
- package/dist/public/sdk/{walletDbName-Ca0rCq5r.js → walletDbName-B6-CV_Rq.js} +1 -1
- package/dist/public/sdk/{walletOwnerOperation-CScYv2K6.js → walletOwnerOperation-BJPxzo-k.js} +1 -1
- package/dist/public/sdk/{walletOwnershipGeneration-BZc6UKqX.js → walletOwnershipGeneration-B3uE9GRG.js} +1 -1
- package/dist/{esm/sdk/walletRecoveryAdminProof-DdwikrW3.js → public/sdk/walletRecoveryAdminProof-BmZaP0Q8.js} +1 -1
- package/dist/{esm/sdk/walletRecoveryCommit-DbAoiJp5.js → public/sdk/walletRecoveryCommit-CSYNbYNd.js} +1 -1
- package/dist/public/sdk/{walletSessionAuthorizationStatus-GhcGvDCX.js → walletSessionAuthorizationStatus-CQ3qA9tI.js} +1 -1
- package/dist/{esm/sdk/walletSessionAuthorizationStore-BivTUoKY.js → public/sdk/walletSessionAuthorizationStore-CGt-s5fX.js} +1 -1
- package/dist/public/sdk/workers/device-linking-key.worker.js +454 -947
- package/dist/public/sdk/workers/email-otp.worker.js +588 -820
- package/dist/public/sdk/workers/email_otp_runtime_bg.wasm +0 -0
- package/dist/public/sdk/workers/evm_crypto_bg.wasm +0 -0
- package/dist/public/sdk/workers/passkey-mpc-export.worker.js +572 -804
- package/dist/public/sdk/workers/router_ab_ecdsa_client_bg.wasm +0 -0
- package/dist/public/sdk/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/sdk/workers/shamir3pass_runtime_bg.wasm +0 -0
- package/dist/public/sdk/workers/tempo_signer_bg.wasm +0 -0
- package/dist/public/sdk/workers/wallet-custody-ceremony.worker.js +524 -971
- package/dist/public/sdk/workers/wallet_custody_ceremony_bg.wasm +0 -0
- package/dist/public/sdk/workers/wasm_signer_worker_bg.wasm +0 -0
- package/dist/public/wallet-assets.manifest.json +153 -153
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/SeamsWeb/index.d.ts +1 -0
- package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +3 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/client/inboundMessages.d.ts +5 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +3 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/coordinator.d.ts +6 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/controller.d.ts +2 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/domain.d.ts +3 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/session.d.ts +4 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/requestRouter.d.ts +1 -1
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +5 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/WalletAlternativesSection.d.ts +13 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.d.ts +3 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +11 -4
- package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/walletAlternatives.d.ts +52 -0
- package/dist/types/wallet/src/core/types/seams.d.ts +2 -2
- package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
- package/dist/types/wallet/src/core/ui/walletIcon.d.ts +3 -0
- package/dist/types/wallet/src/index.d.ts +1 -0
- package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/public.d.ts +1 -0
- package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/types.d.ts +4 -0
- package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/walletAlternatives.d.ts +48 -0
- package/dist/types/wallet/src/react/index.d.ts +1 -2
- package/dist/workers/device-linking-key.worker.js +454 -947
- package/dist/workers/email-otp.worker.js +588 -820
- package/dist/workers/email_otp_runtime_bg.wasm +0 -0
- package/dist/workers/evm_crypto_bg.wasm +0 -0
- package/dist/workers/passkey-mpc-export.worker.js +572 -804
- package/dist/workers/router_ab_ecdsa_client_bg.wasm +0 -0
- package/dist/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/workers/shamir3pass_runtime_bg.wasm +0 -0
- package/dist/workers/tempo_signer_bg.wasm +0 -0
- package/dist/workers/wallet-custody-ceremony.worker.js +524 -971
- package/dist/workers/wallet_custody_ceremony_bg.wasm +0 -0
- package/dist/workers/wasm_signer_worker_bg.wasm +0 -0
- package/package.json +17 -17
- package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.css +0 -182
- package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.js +0 -315
- package/dist/esm/sdk/appearance-token-vars-DkF3EBbF.js +0 -1
- package/dist/esm/sdk/host-BeE2dIU4.js +0 -1
- package/dist/esm/sdk/ownerNearOperation-DjNDxW3_.js +0 -1
- package/dist/esm/sdk/registration-CTtTocyo.js +0 -1
- package/dist/esm/sdk/resealedEnvelopeResult-DXDo-72P.js +0 -1
- package/dist/esm/sdk/routerAbNormalSigning-DVFFkNhJ.js +0 -1
- package/dist/esm/sdk/runtime-auth-Dsmw_dUA.js +0 -1
- package/dist/esm/sdk/runtime-preferences-DlKHDIjb.js +0 -1
- package/dist/esm/sdk/runtime-recovery-C6lS71Jp.js +0 -1
- package/dist/public/sdk/appearance-token-vars-DkF3EBbF.js +0 -1
- package/dist/public/sdk/host-BeE2dIU4.js +0 -1
- package/dist/public/sdk/ownerNearOperation-DjNDxW3_.js +0 -1
- package/dist/public/sdk/registration-CTtTocyo.js +0 -1
- package/dist/public/sdk/resealedEnvelopeResult-DXDo-72P.js +0 -1
- package/dist/public/sdk/routerAbNormalSigning-DVFFkNhJ.js +0 -1
- package/dist/public/sdk/runtime-auth-Dsmw_dUA.js +0 -1
- package/dist/public/sdk/runtime-preferences-DlKHDIjb.js +0 -1
- package/dist/public/sdk/runtime-recovery-C6lS71Jp.js +0 -1
- package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.d.ts +0 -31
- /package/dist/esm/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
- /package/dist/esm/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
- /package/dist/esm/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
- /package/dist/public/sdk/{canonicalPrimitives-Jd3i_Ngz.js → canonicalPrimitives-DKeS3M40.js} +0 -0
- /package/dist/public/sdk/{capabilityKinds-DVlGMspk.js → capabilityKinds-Cafn86Y1.js} +0 -0
- /package/dist/public/sdk/{walletIframeIdentity-CpgyEnKg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
package/dist/esm/sdk/{walletOwnershipGeneration-BZc6UKqX.js → walletOwnershipGeneration-B3uE9GRG.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,a as t,b as n,i as r}from"./domainIds-t1lp25yU.js";import{S as i,n as a,t as o,y as s}from"./digests-BIaE0DMd.js";import{i as c,r as l}from"./base64-BmKR3UqU.js";import{X as u}from"./activeWalletSession-BJ4B-nJo.js";import{i as d,n as f,r as p}from"./canonicalPrimitives-Jd3i_Ngz.js";import{a as m,i as h,n as g}from"./presignatures-CkhuZ0YQ.js";import{a as _}from"./ecdsaChainTarget-BoRVQtjQ.js";import{A as ee,At as te,Et as ne,F as re,G as ie,Pt as ae,St as oe,Tt as se,W as ce,_t as v,b as le,bt as ue,ct as y,dt as de,gt as b,ht as x,mt as S,pt as C,q as fe,xt as w,yt as T,z as pe}from"./digestEncoding-34kXJoJr.js";import{A as E,B as me,C as he,I as ge,M as _e,P as ve,_ as ye,a as be,b as D,c as xe,d as Se,f as Ce,g as we,h as Te,i as Ee,j as O,l as De,m as k,n as Oe,o as ke,p as A,r as Ae,s as je,t as Me,u as Ne,v as Pe,z as Fe}from"./ecdsaCapabilityManifest--1Ztngfx.js";import{C as Ie,p as Le,w as Re}from"./emailOtpEcdsaDerivationIdentity-Qd4pBwHv.js";const j=`seams/router-ab-ecdsa-presign/fixed-2of2/v1`;function M(e,t){if(typeof e!=`string`||!e)throw Error(`${t} is required`);if(e.trim()!==e)throw Error(`${t} must be canonical`);return e}function N(e){if(typeof e!=`object`||!e)throw Error(`poolIdentity is required`);let t=e;if(!Number.isSafeInteger(t.ownershipGeneration)||Number(t.ownershipGeneration)<1)throw Error(`poolIdentity.ownershipGeneration must be a positive safe integer`);if(t.pairRole!==`client`)throw Error(`poolIdentity.pairRole must be client`);if(t.protocolId!==`seams/router-ab-ecdsa-presign/fixed-2of2/v1`)throw Error(`poolIdentity.protocolId is unsupported`);let n=M(t.relayerUrl,`poolIdentity.relayerUrl`);if(n.replace(/\/+$/g,``)!==n)throw Error(`poolIdentity.relayerUrl must be canonical`);return{ownershipGeneration:Number(t.ownershipGeneration),relayerUrl:n,materialActivationB64u:M(t.materialActivationB64u,`poolIdentity.materialActivationB64u`),materialActivationId:M(t.materialActivationId,`poolIdentity.materialActivationId`),capability:M(t.capability,`poolIdentity.capability`),keyBinding:M(t.keyBinding,`poolIdentity.keyBinding`),walletId:M(t.walletId,`poolIdentity.walletId`),signingScopeB64u:M(t.signingScopeB64u,`poolIdentity.signingScopeB64u`),pairRole:`client`,keyEpoch:M(t.keyEpoch,`poolIdentity.keyEpoch`),activationEpoch:ze(t.activationEpoch),protocolId:j}}function ze(e){let t=n(e);if(!t.ok)throw Error(`poolIdentity.activationEpoch is invalid`);return t.value}function Be(e,t){return e.ownershipGeneration===t.ownershipGeneration&&e.relayerUrl===t.relayerUrl&&e.materialActivationB64u===t.materialActivationB64u&&e.materialActivationId===t.materialActivationId&&e.capability===t.capability&&e.keyBinding===t.keyBinding&&e.walletId===t.walletId&&e.signingScopeB64u===t.signingScopeB64u&&e.pairRole===t.pairRole&&e.keyEpoch===t.keyEpoch&&e.activationEpoch===t.activationEpoch&&e.protocolId===t.protocolId}function P(e){return[e.protocolId,e.relayerUrl,e.signingScopeB64u,e.materialActivationB64u,e.ownershipGeneration].join(`|`)}function Ve(e){let t=le(e.scope),n=e.materialActivation,r=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);return{ownershipGeneration:e.ownershipGeneration,relayerUrl:r,materialActivationB64u:c(te(n)),materialActivationId:n.activation_id,capability:n.capability,keyBinding:n.key_binding,walletId:t.wallet_id,signingScopeB64u:c(pe(t)),pairRole:`client`,keyEpoch:t.signing_worker.key_epoch,activationEpoch:t.activation_epoch,protocolId:j}}const He=`ecdsa_capability_manifest_v3`,F=`ecdsa_current_capability_manifest_v2`,Ue=`ecdsa_role_local_material_v2`,We=`ecdsa_activation_commit_journal_v1`,Ge=`ecdsa_material_sealing_key_v1`,Ke=m.ecdsaCapabilityManifests,qe=m.ecdsaCurrentCapabilityManifests,Je=m.ecdsaRoleLocalMaterial,Ye=m.ecdsaActivationCommitJournals,Xe=m.ecdsaMaterialSealingKeys,I=m.ecdsaClientPresignatures;function L(e,t,n){let r=Object.keys(e).sort(),i=[...n].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`${t} has unexpected fields`)}function Ze(e){let n=y(e.authority);if(!n)throw Error(`ECDSA capability selector authority is invalid`);return{capability:D(t(e.capability)),authority:n}}function R(e){return{capability:e.capability,authority:e.authority}}function z(e){return R(e.candidate.activationBinding.signer)}function B(e){return R(e.signer)}function V(e){return[String(e.capability),String(e.authority.walletId),String(e.authority.authorityDigest)]}function H(e){return{capability_ref:e.capability,wallet_id:e.authority.walletId,authority_digest:e.authority.authorityDigest,wallet_auth_method_id:e.authority.walletAuthMethodId}}function Qe(e){return y({kind:`wallet_auth_authority_ref`,walletId:e.wallet_id,authorityDigest:e.authority_digest,walletAuthMethodId:e.wallet_auth_method_id})}function $e(e,t){return e.kind===t.kind&&e.walletId===t.walletId&&e.authorityDigest===t.authorityDigest&&e.walletAuthMethodId===t.walletAuthMethodId}function et(e,t){let n=V(e),r=V(t);return n[0]===r[0]&&n[1]===r[1]&&n[2]===r[2]}function U(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function tt(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}function W(e,t){if(e.kind!==t.kind)return!1;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 Y(e)}}function nt(e,t){return e.kind===t.kind&&e.targetMemberships.length===t.targetMemberships.length&&e.targetMemberships.every((e,n)=>W(e,t.targetMemberships[n]))}function G(e,t){return e.kind===t.kind&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.clientVerifyingPublicKey33B64u===t.clientVerifyingPublicKey33B64u&&U(e.participantIds,t.participantIds)&&e.relayerKeyId===t.relayerKeyId}function rt(e,t){return e.walletId===t.walletId&&W(e.chainTarget,t.chainTarget)&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion&&e.applicationBindingDigestB64u===t.applicationBindingDigestB64u&&e.clientParticipantId===t.clientParticipantId&&e.relayerParticipantId===t.relayerParticipantId&&U(e.participantIds,t.participantIds)&&e.contextBinding32B64u===t.contextBinding32B64u&&e.derivationClientSharePublicKey33B64u===t.derivationClientSharePublicKey33B64u&&e.relayerPublicKey33B64u===t.relayerPublicKey33B64u&&e.groupPublicKey33B64u===t.groupPublicKey33B64u&&e.ethereumAddress===t.ethereumAddress&&ie(e.publicCapability,t.publicCapability)}function it(e,t){return e.kind===t.kind&&e.keyHandle===t.keyHandle&&e.publicKeyB64u===t.publicKeyB64u&&U(e.participantIds,t.participantIds)&&e.thresholdOwnerAddress===t.thresholdOwnerAddress}function at(e,t){return e.manifestId===t.manifestId&&e.manifestRevision===t.manifestRevision}function ot(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`no_current_manifest`:return!0;case`exact_manifest`:return t.kind===`exact_manifest`&&e.manifestId===t.manifestId&&e.manifestRevision===t.manifestRevision;default:return Y(e)}}function st(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`no_current_generation`:return!0;case`exact_generation`:return t.kind===`exact_generation`&&e.serverGeneration===t.serverGeneration;default:return Y(e)}}function ct(e,t){return e.kind===t.kind&&e.capability===t.capability&&e.signerId===t.signerId&&e.walletId===t.walletId&&$e(e.authority,t.authority)&&nt(e.scope,t.scope)&&e.materialOwner===t.materialOwner&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion}function lt(e,t){return ct(e,t)&&it(e.registeredPublicFacts,t.registeredPublicFacts)}function ut(e,t){return e.kind===t.kind&&e.sealingKeyId===t.sealingKeyId&&e.iv12B64u===t.iv12B64u&&e.ciphertextB64u===t.ciphertextB64u&&e.ciphertextDigest===t.ciphertextDigest}function dt(e,t){return e.kind===t.kind&&at(e.targetManifest,t.targetManifest)&&ct(e.signer,t.signer)&&G(e.roleLocalBinding,t.roleLocalBinding)&&e.bindingDigest===t.bindingDigest&&e.durableMaterialRef===t.durableMaterialRef}function K(e,t){return e.kind===t.kind&&e.correlationId===t.correlationId&&e.activationRequestDigest===t.activationRequestDigest&&e.serverGeneration===t.serverGeneration&&ft(e.serverActivationReceipt,t.serverActivationReceipt)}function ft(e,t){return e.kind===t.kind&&e.lifecycleId===t.lifecycleId&&e.activationDigest===t.activationDigest&&e.activatedAt===t.activatedAt&&fe(e.protocolReceipt,t.protocolReceipt)}function pt(e,t){return e.kind===t.kind&&e.correlationId===t.correlationId&&st(e.expectedGeneration,t.expectedGeneration)&&e.requestDigest===t.requestDigest&&e.canonicalRequest===t.canonicalRequest}function mt(e,t){return e.kind===t.kind&&dt(e.activationBinding,t.activationBinding)&&ut(e.encryptedPending,t.encryptedPending)}function ht(e,t){if(e.kind!==t.kind||!(e.journalId===t.journalId&&ot(e.expectedManifest,t.expectedManifest)&&pt(e.activationCommand,t.activationCommand)&&mt(e.candidate,t.candidate)&&e.createdAt===t.createdAt))return!1;switch(e.kind){case`activation_prepared`:return!0;case`server_activation_committed`:return t.kind===`server_activation_committed`&&K(e.serverActivation,t.serverActivation);default:return Y(e)}}function gt(e,t){return e.kind===t.kind&&r(e.materialActivation,t.materialActivation)&&ce(e.routerAbEcdsaDerivationNormalSigning,t.routerAbEcdsaDerivationNormalSigning)&&rt(e.roleLocalPublicFacts,t.roleLocalPublicFacts)&&G(e.roleLocalBinding,t.roleLocalBinding)&&e.durableMaterialRef===t.durableMaterialRef&&e.bindingDigest===t.bindingDigest&&e.lifecycleId===t.lifecycleId&&e.ciphertextDigest===t.ciphertextDigest&&e.activationDigest===t.activationDigest&&e.activatedAt===t.activatedAt&&tt(e.runtimePolicyScope,t.runtimePolicyScope)}function _t(e,t){return e.kind===t.kind&&r(e.materialActivation,t.materialActivation)&&K(e.serverActivation,t.serverActivation)&&e.retention===t.retention}function vt(e,t){return e.kind===t.kind&&at(e.identity,t.identity)&<(e.signer,t.signer)&&_t(e.activation,t.activation)&>(e.durableMaterial,t.durableMaterial)&&e.committedAt===t.committedAt}function yt(e,t){try{let n=i(t.serverActivationReceipt,`ECDSA server activation receipt`);return t.kind===e.kind&&f(t.correlationId)===e.correlationId&&p(t.activationRequestDigest)===e.activationRequestDigest&&w(t.serverGeneration)===e.serverGeneration&&n.kind===e.serverActivationReceipt.kind&&n.lifecycleId===String(e.serverActivationReceipt.lifecycleId)&&n.activationDigest===String(e.serverActivationReceipt.activationDigest)&&d(n.activatedAt)===e.serverActivationReceipt.activatedAt&&fe(ee(n.protocolReceipt),e.serverActivationReceipt.protocolReceipt)}catch{return!1}}function bt(e){let t=A({activationBinding:e.preparation.activationBinding,encryptedPending:e.encryptedPending});return xt({...e.preparation,candidate:t})}function xt(e){let t={journalId:e.journalId,candidate:e.candidate,requestDigest:e.requestDigest,canonicalRequest:e.canonicalRequest,createdAt:e.createdAt};switch(e.expectedManifest.kind){case`no_current_manifest`:if(e.expectedGeneration.kind!==`no_current_generation`)throw Error(`Initial ECDSA activation cannot expect a server generation`);return k({...t,expectedManifest:e.expectedManifest,expectedGeneration:e.expectedGeneration});case`exact_manifest`:if(e.expectedGeneration.kind!==`exact_generation`)throw Error(`Replacement ECDSA activation requires an exact server generation`);return k({...t,expectedManifest:e.expectedManifest,expectedGeneration:e.expectedGeneration});default:return Y(e.expectedManifest)}}function St(e,t){if(typeof e!=`string`||e.length===0||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be non-empty unpadded base64url`);let n=l(e);if(n.length===0||c(n)!==e)throw n.fill(0),Error(`${t} must be canonical base64url`);return n}function q(e){return new TextEncoder().encode(o(e))}async function Ct(){return await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function wt(e){let t=St(e.stateBlobB64u,`ECDSA state blob`),n=crypto.getRandomValues(new Uint8Array(12)),r=q(e.aadProjection);try{let i=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,additionalData:r},e.key,t));try{return{iv12B64u:v(c(n)),ciphertextB64u:x(c(i)),digestB64u:c(await a(i))}}finally{i.fill(0)}}finally{t.fill(0),r.fill(0)}}async function Tt(e){let t=l(e);try{return c(await a(t))}finally{t.fill(0)}}async function Et(e){let t=l(e.iv12B64u),n=l(e.ciphertextB64u),r=q(e.aadProjection),i=null;try{if(i=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:t,additionalData:r},e.key,n)),i.length===0)throw Error(`decrypted ECDSA state blob must not be empty`);return c(i)}finally{t.fill(0),n.fill(0),r.fill(0),i?.fill(0)}}function Dt(e){let t=i(e,`ECDSA manifest identity`);return L(t,`ECDSA manifest identity`,[`manifestId`,`manifestRevision`]),be({manifestId:C(t.manifestId),manifestRevision:S(t.manifestRevision)})}function Ot(e){let t=i(e,`ECDSA manifest expectation`);switch(t.kind){case`no_current_manifest`:return L(t,`ECDSA no-current manifest expectation`,[`kind`]),Se();case`exact_manifest`:return L(t,`ECDSA exact manifest expectation`,[`kind`,`manifestId`,`manifestRevision`]),De(be({manifestId:C(t.manifestId),manifestRevision:S(t.manifestRevision)}));default:throw Error(`ECDSA manifest expectation kind is invalid`)}}function kt(e){let t=i(e,`ECDSA capability target`);switch(t.kind){case`evm`:return L(t,`ECDSA EVM capability target`,[`kind`,`namespace`,`chainId`,`networkSlug`]),_({kind:t.kind,namespace:t.namespace,chainId:t.chainId,networkSlug:t.networkSlug});case`tempo`:return L(t,`ECDSA Tempo capability target`,[`kind`,`chainId`,`networkSlug`]),_({kind:t.kind,chainId:t.chainId,networkSlug:t.networkSlug});default:throw Error(`ECDSA capability target kind is invalid`)}}function At(e){let t=i(e,`ECDSA capability scope`);if(L(t,`ECDSA capability scope`,[`kind`,`targetMemberships`]),t.kind!==`evm_family`)throw Error(`ECDSA capability scope kind is invalid`);let n=s(t.targetMemberships,`ECDSA capability target memberships`),r=[];for(let e of n)r.push(kt(e));let[a,...o]=r;if(!a)throw Error(`ECDSA capability scope requires at least one target`);return Ee({targetMemberships:[a,...o]})}function jt(e){let t=i(e,`ECDSA role-local material binding`);if(L(t,`ECDSA role-local material binding`,[`kind`,`keyHandle`,`ecdsaThresholdKeyId`,`clientVerifyingPublicKey33B64u`,`participantIds`,`relayerKeyId`]),t.kind!==`ecdsa_role_local_material_binding`)throw Error(`ECDSA role-local material binding kind is invalid`);let n=s(t.participantIds,`ECDSA role-local participant ids`),r=[];for(let e of n)r.push(Re(e));let[a,...o]=r;if(!a)throw Error(`ECDSA role-local material requires at least one participant`);return ke({keyHandle:Fe(t.keyHandle),ecdsaThresholdKeyId:ge(t.ecdsaThresholdKeyId),clientVerifyingPublicKey33B64u:E(t.clientVerifyingPublicKey33B64u),participantIds:[a,...o],relayerKeyId:me(t.relayerKeyId)})}function Mt(n){let r=i(n,`prepared ECDSA signer`);if(L(r,`prepared ECDSA signer`,[`kind`,`capability`,`signerId`,`walletId`,`authority`,`scope`,`materialOwner`,`signingRootId`,`signingRootVersion`]),r.kind!==`prepared_evm_family_signer`)throw Error(`prepared ECDSA signer kind is invalid`);let a=y(r.authority);if(!a)throw Error(`prepared ECDSA signer authority is invalid`);if(String(r.walletId)!==String(a.walletId))throw Error(`prepared ECDSA signer wallet does not match its authority`);return Te({capability:D(t(r.capability)),signerId:oe(r.signerId),authority:a,scope:At(r.scope),materialOwner:D(e(r.materialOwner)),signingRootId:se(r.signingRootId),signingRootVersion:ne(r.signingRootVersion)})}function Nt(e){let t=i(e,`encrypted ECDSA pending candidate`);if(L(t,`encrypted ECDSA pending candidate`,[`kind`,`sealingKeyId`,`iv12B64u`,`ciphertextB64u`,`ciphertextDigest`]),t.kind!==`encrypted_ecdsa_pending_candidate`)throw Error(`encrypted ECDSA pending candidate kind is invalid`);return xe({sealingKeyId:T(t.sealingKeyId),iv12B64u:v(t.iv12B64u),ciphertextB64u:x(t.ciphertextB64u),ciphertextDigest:ue(t.ciphertextDigest)})}function Pt(e){let t=i(e,`ECDSA activation binding`);if(L(t,`ECDSA activation binding`,[`kind`,`targetManifest`,`signer`,`roleLocalBinding`,`bindingDigest`,`durableMaterialRef`]),t.kind!==`ecdsa_activation_binding`)throw Error(`ECDSA activation binding kind is invalid`);return Ae({targetManifest:Dt(t.targetManifest),signer:Mt(t.signer),roleLocalBinding:jt(t.roleLocalBinding),bindingDigest:O(t.bindingDigest),durableMaterialRef:_e(t.durableMaterialRef)})}function Ft(e){let t=i(e,`prepared ECDSA activation candidate`);if(L(t,`prepared ECDSA activation candidate`,[`kind`,`activationBinding`,`encryptedPending`]),t.kind!==`prepared_ecdsa_activation_candidate`)throw Error(`prepared ECDSA activation candidate kind is invalid`);return A({activationBinding:Pt(t.activationBinding),encryptedPending:Nt(t.encryptedPending)})}function It(e){let t=i(e,`ECDSA server generation expectation`);switch(t.kind){case`no_current_generation`:return L(t,`ECDSA no-current server generation expectation`,[`kind`]),Ce();case`exact_generation`:return L(t,`ECDSA exact server generation expectation`,[`kind`,`serverGeneration`]),Ne(w(t.serverGeneration));default:throw Error(`ECDSA server generation expectation kind is invalid`)}}function Lt(e){let t=i(e,`prepared ECDSA activation journal`);if(L(t,`prepared ECDSA activation journal`,[`kind`,`journalId`,`expectedManifest`,`activationCommand`,`candidate`,`createdAt`]),t.kind!==`activation_prepared`)throw Error(`prepared ECDSA activation journal kind is invalid`);let n=i(t.activationCommand,`ECDSA activation command`);if(L(n,`ECDSA activation command`,[`kind`,`correlationId`,`expectedGeneration`,`requestDigest`,`canonicalRequest`]),n.kind!==`ecdsa_server_activation_command`)throw Error(`ECDSA activation command kind is invalid`);let r=f(t.journalId);if(f(n.correlationId)!==r)throw Error(`ECDSA activation command correlation does not match its journal`);let a=Ot(t.expectedManifest),o=It(n.expectedGeneration),s={journalId:r,candidate:Ft(t.candidate),requestDigest:p(n.requestDigest),canonicalRequest:de(n.canonicalRequest),createdAt:d(t.createdAt)};switch(a.kind){case`no_current_manifest`:if(o.kind!==`no_current_generation`)throw Error(`initial ECDSA journal has an exact server generation`);return k({...s,expectedManifest:a,expectedGeneration:o});case`exact_manifest`:if(o.kind!==`exact_generation`)throw Error(`replacement ECDSA journal is missing its exact server generation`);return k({...s,expectedManifest:a,expectedGeneration:o})}return Y(a)}function Rt(e){return{kind:`activation_prepared`,journalId:e.journalId,expectedManifest:e.expectedManifest,activationCommand:e.activationCommand,candidate:e.candidate,createdAt:e.createdAt}}function zt(e){return e.kind===`activation_prepared`?e:xt({journalId:e.journalId,expectedManifest:e.expectedManifest,expectedGeneration:e.activationCommand.expectedGeneration,candidate:e.candidate,requestDigest:e.activationCommand.requestDigest,canonicalRequest:e.activationCommand.canonicalRequest,createdAt:e.createdAt})}function Bt(e){let t=i(e,`server-committed ECDSA activation journal`);if(L(t,`server-committed ECDSA activation journal`,[`kind`,`journalId`,`expectedManifest`,`activationCommand`,`candidate`,`createdAt`,`serverActivation`]),t.kind!==`server_activation_committed`)throw Error(`server-committed ECDSA activation journal kind is invalid`);let n=Lt(Rt(t)),r=Vt(t.serverActivation),a=ye({preparedJournal:n,serverCommit:r.serverCommit});if(!yt(a.serverActivation,r.record))throw Error(`ECDSA server activation commit fields are inconsistent`);return a}function Vt(e){let t=i(e,`ECDSA server activation commit`);if(L(t,`ECDSA server activation commit`,[`kind`,`correlationId`,`activationRequestDigest`,`serverGeneration`,`serverActivationReceipt`]),t.kind!==`ecdsa_server_activation_commit`)throw Error(`ECDSA server activation commit kind is invalid`);let n=i(t.serverActivationReceipt,`ECDSA server activation receipt`);if(L(n,`ECDSA server activation receipt`,[`kind`,`lifecycleId`,`activationDigest`,`activatedAt`,`protocolReceipt`]),n.kind!==`ecdsa_server_activation_receipt`)throw Error(`ECDSA server activation receipt kind is invalid`);return{record:t,serverCommit:{correlationId:f(t.correlationId),activationRequestDigest:p(t.activationRequestDigest),serverGeneration:w(t.serverGeneration),protocolReceipt:n.protocolReceipt}}}function Ht(e){let t=i(e,`ECDSA activation journal`);switch(t.kind){case`activation_prepared`:return Lt(t);case`server_activation_committed`:return Bt(t);default:throw Error(`ECDSA activation journal kind is invalid`)}}function Ut(e){let t=i(e,`registered ECDSA public facts`);if(L(t,`registered ECDSA public facts`,[`kind`,`keyHandle`,`publicKeyB64u`,`participantIds`,`thresholdOwnerAddress`]),t.kind!==`verified_ecdsa_public_facts`)throw Error(`registered ECDSA public facts kind is invalid`);return Le({keyHandle:Ie(t.keyHandle),publicKeyB64u:t.publicKeyB64u,participantIds:s(t.participantIds,`registered ECDSA participant ids`),thresholdOwnerAddress:t.thresholdOwnerAddress})}function J(e){let t=i(e,`active ECDSA manifest proof`);L(t,`active ECDSA manifest proof`,[`activation_binding`,`server_activation`,`registered_public_facts`,`role_local_public_facts`,`router_ab_ecdsa_derivation_normal_signing`,`runtime_policy_scope`,`ciphertext_digest`,`committed_at`]);let n=Pt(t.activation_binding),r=Vt(t.server_activation),a=je({activationBinding:n,serverCommit:r.serverCommit});if(!yt(a,r.record))throw Error(`ECDSA server activation commit fields are inconsistent`);let o=Oe({activationBinding:n,serverActivation:a,routerAbEcdsaDerivationNormalSigning:re(t.router_ab_ecdsa_derivation_normal_signing),roleLocalPublicFacts:he(t.role_local_public_facts),ciphertextDigest:b(t.ciphertext_digest),runtimePolicyScope:u(t.runtime_policy_scope)}),s=d(t.committed_at);return{activationBinding:n,serverActivation:a,durableMaterial:o,activeManifest:Me({activationBinding:n,serverActivation:a,registeredPublicFacts:Ut(t.registered_public_facts),durableMaterial:o,committedAt:s}),committedAt:s}}function Wt(e){let t=i(e,`ECDSA capability manifest row`),n=[`record_version`,`manifest_id`,`manifest_revision`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`manifest_state`,`active_proof`];switch(t.manifest_state){case`active`:{L(t,`active ECDSA capability manifest row`,n);let e=J(t.active_proof),r=B(e.activeManifest);return Gt(t,e.activeManifest,r),{state:`active`,selector:r,manifest:e.activeManifest,activeProof:e}}case`replaced`:{L(t,`replaced ECDSA capability manifest row`,[...n,`replacement_proof`]);let e=J(t.active_proof),r=J(t.replacement_proof),i=we({activeManifest:e.activeManifest,replacementManifest:r.activeManifest}),a=B(e.activeManifest);return Gt(t,e.activeManifest,a),{state:`replaced`,selector:a,manifest:i,activeProof:e,replacementProof:r}}default:throw Error(`ECDSA capability manifest row state is invalid`)}}function Gt(e,t,n){if(e.record_version!==`ecdsa_capability_manifest_v3`||C(e.manifest_id)!==t.identity.manifestId||S(e.manifest_revision)!==t.identity.manifestRevision||String(e.capability_ref)!==String(n.capability)||String(e.wallet_id)!==String(n.authority.walletId)||String(e.authority_digest)!==String(n.authority.authorityDigest))throw Error(`ECDSA capability manifest row identity is inconsistent`)}function Kt(e){return{record_version:F,...H(B(e)),manifest_id:e.identity.manifestId,manifest_revision:e.identity.manifestRevision}}function qt(e){let n=i(e,`current ECDSA capability pointer`);if(L(n,`current ECDSA capability pointer`,[`record_version`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`manifest_id`,`manifest_revision`]),n.record_version!==F)throw Error(`current ECDSA capability pointer version is invalid`);let r=Qe(n);if(!r)throw Error(`current ECDSA capability pointer authority is invalid`);return{selector:{capability:D(t(n.capability_ref)),authority:r},manifestId:C(n.manifest_id),manifestRevision:S(n.manifest_revision)}}function Jt(e,t){return{record_version:Ue,durable_material_ref:e.binding.durableMaterialRef,binding_digest:e.binding.bindingDigest,...H(B(t)),sealing_key_id:e.sealingKeyId,iv:e.iv12B64u,ciphertext:e.ciphertextB64u}}function Yt(e){let n=i(e,`ECDSA role-local material row`);if(L(n,`ECDSA role-local material row`,[`record_version`,`durable_material_ref`,`binding_digest`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`sealing_key_id`,`iv`,`ciphertext`]),n.record_version!==Ue)throw Error(`ECDSA role-local material row version is invalid`);let r=Qe(n);if(!r)throw Error(`ECDSA role-local material authority is invalid`);return{durableMaterialRef:_e(n.durable_material_ref),bindingDigest:O(n.binding_digest),selector:{capability:D(t(n.capability_ref)),authority:r}}}function Xt(e,t){let n=i(e,`ECDSA role-local material row`),r=Yt(n),a=Pe({binding:t.durableMaterial,sealingKeyId:T(n.sealing_key_id),iv12B64u:v(n.iv),ciphertextB64u:x(n.ciphertext)});if(r.durableMaterialRef!==a.binding.durableMaterialRef||r.bindingDigest!==a.binding.bindingDigest||!et(r.selector,B(t.activeManifest)))throw Error(`ECDSA role-local material row binding is inconsistent`);return a}function Zt(e,t){return e.binding.durableMaterialRef===t.durableMaterial.durableMaterialRef&&e.binding.bindingDigest===t.durableMaterial.bindingDigest&&e.binding.lifecycleId===t.durableMaterial.lifecycleId&&e.binding.ciphertextDigest===t.durableMaterial.ciphertextDigest&&e.binding.activationDigest===t.durableMaterial.activationDigest&&e.binding.activatedAt===t.durableMaterial.activatedAt&&r(e.binding.materialActivation,t.durableMaterial.materialActivation)&&G(e.binding.roleLocalBinding,t.durableMaterial.roleLocalBinding)}function Qt(e){return{record_version:We,journal_id:e.journalId,...H(z(e)),journal:e}}function $t(e){let t=i(e,`ECDSA activation commit journal row`);if(L(t,`ECDSA activation commit journal row`,[`record_version`,`journal_id`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`journal`]),t.record_version!==We)throw Error(`ECDSA activation commit journal row version is invalid`);let n=Ht(t.journal),r=z(n);if(f(t.journal_id)!==n.journalId||String(t.capability_ref)!==String(r.capability)||String(t.wallet_id)!==String(r.authority.walletId)||String(t.authority_digest)!==String(r.authority.authorityDigest))throw Error(`ECDSA activation commit journal row identity is inconsistent`);return{journal:n,selector:r}}function en(e){return typeof CryptoKey>`u`||!(e instanceof CryptoKey)||e.type!==`secret`||e.extractable||e.algorithm.name!==`AES-GCM`?!1:e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function tn(e,t){return{record_version:Ge,key_id:e,key:t}}function nn(e){let t=i(e,`ECDSA material sealing key row`);if(L(t,`ECDSA material sealing key row`,[`record_version`,`key_id`,`key`]),t.record_version!==Ge)throw Error(`ECDSA material sealing key row version is invalid`);if(!en(t.key))throw Error(`ECDSA material sealing key must be a non-extractable AES-GCM key`);return{keyId:T(t.key_id),key:t.key}}function Y(e){throw Error(`Unexpected ECDSA persistence branch: ${String(e)}`)}const rn=5*6e4;function an(e,t,n){let i=e.binding.routerAbEcdsaDerivationNormalSigning.scope,a=ae(e.binding.materialActivation);return i.wallet_id===t.walletId&&c(pe(i))===t.signingScopeB64u&&c(te(a))===t.materialActivationB64u&&i.signing_worker.key_epoch===t.keyEpoch&&i.activation_epoch===t.activationEpoch&&a.activation_id===t.materialActivationId&&a.capability===t.capability&&a.key_binding===t.keyBinding&&a.material_owner===t.walletId&&e.binding.durableMaterialRef===n.durableMaterialRef&&e.binding.bindingDigest===n.bindingDigest&&r(e.binding.materialActivation,n.materialActivation)}function on(e,t){return e.materialActivation.activationId===t.materialActivationId&&e.materialActivation.capability===t.capability&&e.materialActivation.keyBinding===t.keyBinding&&e.materialActivation.materialOwner===t.walletId}function sn(e){if(typeof e!=`string`||!/^ecdsa-client-presignature-[A-Za-z0-9_-]+$/.test(e))throw Error(`ECDSA durable presignature record id is invalid`);return e}function X(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} is invalid`);return e}function Z(e){if(!e||typeof e!=`object`||!(`record_id`in e))return null;let t=e.record_id;return typeof t==`string`?t:null}function cn(){return typeof IDBTransaction<`u`&&`durability`in IDBTransaction.prototype}async function ln(e,t=1/0){let n=0;for(;e&&n<t;)await e.delete(),n+=1,e=await e.continue();return n}async function un(e,t,n){return await ln(await e.store(I).index(h.walletExpiresAt).openCursor(IDBKeyRange.bound([t,0],[t,n])),32)}async function dn(e,t,n){await un(e,t.walletId,n);let r=e.store(I),i=await r.index(h.poolIdentityKey).getAll(P(t));t.ownershipGeneration===1&&i.push(...await r.index(h.poolIdentityKey).getAll(pn(t)));let a=[];for(let e of i)try{let t=Q(e);t.expires_at_ms<=n?await r.delete(t.record_id):(e.pool_identity_key!==t.pool_identity_key&&await r.put(t),a.push(t))}catch{let t=Z(e);t&&await r.delete(t)}return a}function fn(e){let{ownershipGeneration:t,...n}=e.poolIdentity;return{domain:`seams/ecdsa-client-presignature/v1`,version:1,pool_identity:t===1?n:e.poolIdentity,durable_material_ref:e.durableMaterialRef,presignature_id:e.presignatureId,group_public_key33_b64u:e.groupPublicKey33B64u,big_r33_b64u:e.bigR33B64u,created_at_ms:e.createdAtMs,expires_at_ms:e.expiresAtMs,sealing_key_id:e.sealingKeyId}}function pn(e){return[e.protocolId,e.relayerUrl,e.signingScopeB64u,e.materialActivationB64u].join(`|`)}function Q(e){let t=i(e,`ECDSA durable presignature row`);if(L(t,`ECDSA durable presignature row`,[`kind`,`record_id`,`pool_identity`,`pool_identity_key`,`wallet_id`,`material_activation_id`,`durable_material_ref`,`presignature_id`,`group_public_key33_b64u`,`big_r33_b64u`,`created_at_ms`,`expires_at_ms`,`sealed`]),t.kind!==`sealed_available_client_presignature_v1`)throw Error(`ECDSA durable presignature row kind is invalid`);let n=i(t.pool_identity,`ECDSA durable presignature pool identity`),r=!Object.hasOwn(n,`ownershipGeneration`);L(n,`ECDSA durable presignature pool identity`,[...r?[]:[`ownershipGeneration`],`activationEpoch`,`capability`,`keyBinding`,`keyEpoch`,`materialActivationB64u`,`materialActivationId`,`pairRole`,`protocolId`,`relayerUrl`,`signingScopeB64u`,`walletId`]);let a=N(r?{...n,ownershipGeneration:1}:n),o=sn(t.record_id),s=String(t.pool_identity_key??``);if(s!==P(a)&&!(r&&s===pn(a)))throw Error(`ECDSA durable presignature pool identity index is inconsistent`);let c=String(t.wallet_id??``).trim(),l=String(t.material_activation_id??``).trim();if(!c||c!==a.walletId)throw Error(`ECDSA durable presignature wallet binding is inconsistent`);if(!l||l!==a.materialActivationId)throw Error(`ECDSA durable presignature activation binding is inconsistent`);let u=ve(t.durable_material_ref);if(!on(u,a))throw Error(`ECDSA durable presignature material binding is inconsistent`);let d=String(t.presignature_id??``).trim();if(!d)throw Error(`ECDSA durable presignature id is invalid`);let f=E(t.group_public_key33_b64u),p=E(t.big_r33_b64u),m=X(t.created_at_ms,`created_at_ms`),h=X(t.expires_at_ms,`expires_at_ms`);if(m>Date.now()+3e5)throw Error(`ECDSA durable presignature creation timestamp is in the future`);if(h<=m)throw Error(`ECDSA durable presignature expiry must follow creation`);if(h-m>7776e6)throw Error(`ECDSA durable presignature lifetime exceeds the maximum`);let g=i(t.sealed,`ECDSA durable presignature sealed payload`);if(L(g,`ECDSA durable presignature sealed payload`,[`kind`,`sealing_key_id`,`iv12_b64u`,`ciphertext_b64u`,`ciphertext_digest_b64u`]),g.kind!==`ecdsa_activation_aes_gcm_v1`)throw Error(`ECDSA durable presignature sealing kind is invalid`);return{kind:`sealed_available_client_presignature_v1`,record_id:o,pool_identity:a,pool_identity_key:P(a),wallet_id:c,material_activation_id:l,durable_material_ref:u,presignature_id:d,group_public_key33_b64u:f,big_r33_b64u:p,created_at_ms:m,expires_at_ms:h,sealed:{kind:`ecdsa_activation_aes_gcm_v1`,sealing_key_id:T(g.sealing_key_id),iv12_b64u:v(g.iv12_b64u),ciphertext_b64u:x(g.ciphertext_b64u),ciphertext_digest_b64u:b(g.ciphertext_digest_b64u)}}}function mn(e){return{kind:`sealed_available_client_presignature_v1`,recordId:e.record_id,poolIdentity:e.pool_identity,durableMaterialRef:e.durable_material_ref,presignatureId:e.presignature_id,groupPublicKey33B64u:e.group_public_key33_b64u,bigR33B64u:e.big_r33_b64u,createdAtMs:e.created_at_ms,expiresAtMs:e.expires_at_ms,sealingKeyId:e.sealed.sealing_key_id}}async function hn(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=q(fn(e.metadata));try{let r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:t,additionalData:n},e.key,e.plaintext97));try{let e=c(r);return{iv12B64u:v(c(t)),ciphertextB64u:x(e),ciphertextDigestB64u:b(c(await a(r)))}}finally{r.fill(0)}}finally{t.fill(0),n.fill(0),e.plaintext97.fill(0)}}async function gn(e){let t=l(e.sealed.iv12_b64u),n=l(e.sealed.ciphertext_b64u),r=q(fn(e.metadata)),i=null;try{if(c(await a(n))!==e.sealed.ciphertext_digest_b64u)throw Error(`ECDSA durable presignature ciphertext digest mismatch`);if(i=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:t,additionalData:r},e.key,n)),i.length!==97)throw Error(`ECDSA durable presignature plaintext length is invalid`);return i.slice()}finally{t.fill(0),n.fill(0),r.fill(0),i?.fill(0)}}async function _n(e,t,n){let r=e.store(I),i=await r.index(h.walletMaterialActivationId).getAll([t,n]);for(let e of i){let t=Z(e);t&&await r.delete(t)}}async function $(e,t){let n=await e.store(m.appState).get(`wallet_ownership_generation:${t}`);if(n===void 0)return 1;let r=i(n,`Wallet ownership generation`).value;if(typeof r!=`number`||!Number.isSafeInteger(r)||r<1)throw Error(`Stored wallet ownership generation is invalid`);return r}async function vn(e,t,n){if(await $(e,t)!==n)throw Error(`Wallet ownership generation requires fresh authentication`)}async function yn(e,t,n){let r=await $(e,t);if(n<r)throw Error(`Wallet session belongs to an obsolete ownership generation`);if(n===r)return;await e.store(m.appState).put({key:`wallet_ownership_generation:${t}`,value:n});let i=await e.store(m.ecdsaClientPresignatures).index(h.walletId).openCursor(t);for(;i;){let e=!0;try{e=Q(i.value).pool_identity.ownershipGeneration<n}catch{}e&&await i.delete(),i=await i.continue()}}async function bn(e,t){await g.runTransaction([m.appState],`readonly`,xn.bind(null,e,t))}function xn(e,t,n){return vn(n,e,t)}async function Sn(e,t){await g.runTransaction([m.appState,m.ecdsaClientPresignatures],`readwrite`,Cn.bind(null,e,t))}async function Cn(e,t,n){t<=await $(n,e)||await yn(n,e,t)}export{B as $,vt as A,Ze as B,I as C,Tt as D,bt as E,rt as F,Yt as G,Bt as H,K as I,nn as J,Xt as K,wt as L,gt as M,it as N,Et as O,G as P,z as Q,Ct as R,qe as S,Y as T,$t as U,J as V,Wt as W,tt as X,zt as Y,H as Z,cn as _,rn as a,Kt as at,Ke as b,hn as c,P as ct,sn as d,N as dt,R as et,X as f,_n as g,dn as h,Sn as i,Jt as it,nt as j,ht as k,on as l,Be as lt,Z as m,bn as n,et as nt,an as o,tn as ot,Q as p,qt as q,vn as r,Qt as rt,gn as s,$e as st,yn as t,V as tt,mn as u,Ve as ut,Ye as v,Xe as w,Je as x,He as y,Zt as z};
|
|
1
|
+
import{_ as e,a as t,b as n,i as r}from"./domainIds-t1lp25yU.js";import{S as i,n as a,t as o,y as s}from"./digests-BIaE0DMd.js";import{i as c,r as l}from"./base64-BmKR3UqU.js";import{X as u}from"./activeWalletSession-HAOgRKzn.js";import{i as d,n as f,r as p}from"./canonicalPrimitives-DKeS3M40.js";import{a as m,i as h,n as g}from"./presignatures-B9KnQyfE.js";import{a as _}from"./ecdsaChainTarget-BoRVQtjQ.js";import{A as ee,At as te,Et as ne,F as re,G as ie,Pt as ae,St as oe,Tt as se,W as ce,_t as v,b as le,bt as ue,ct as y,dt as de,gt as b,ht as x,mt as S,pt as C,q as fe,xt as w,yt as T,z as pe}from"./digestEncoding-Rx8Vjy4J.js";import{A as E,B as me,C as he,I as ge,M as _e,P as ve,_ as ye,a as be,b as D,c as xe,d as Se,f as Ce,g as we,h as Te,i as Ee,j as O,l as De,m as k,n as Oe,o as ke,p as A,r as Ae,s as je,t as Me,u as Ne,v as Pe,z as Fe}from"./ecdsaCapabilityManifest-BbPXL-qh.js";import{C as Ie,p as Le,w as Re}from"./emailOtpEcdsaDerivationIdentity-DJmMyqL-.js";const j=`seams/router-ab-ecdsa-presign/fixed-2of2/v1`;function M(e,t){if(typeof e!=`string`||!e)throw Error(`${t} is required`);if(e.trim()!==e)throw Error(`${t} must be canonical`);return e}function N(e){if(typeof e!=`object`||!e)throw Error(`poolIdentity is required`);let t=e;if(!Number.isSafeInteger(t.ownershipGeneration)||Number(t.ownershipGeneration)<1)throw Error(`poolIdentity.ownershipGeneration must be a positive safe integer`);if(t.pairRole!==`client`)throw Error(`poolIdentity.pairRole must be client`);if(t.protocolId!==`seams/router-ab-ecdsa-presign/fixed-2of2/v1`)throw Error(`poolIdentity.protocolId is unsupported`);let n=M(t.relayerUrl,`poolIdentity.relayerUrl`);if(n.replace(/\/+$/g,``)!==n)throw Error(`poolIdentity.relayerUrl must be canonical`);return{ownershipGeneration:Number(t.ownershipGeneration),relayerUrl:n,materialActivationB64u:M(t.materialActivationB64u,`poolIdentity.materialActivationB64u`),materialActivationId:M(t.materialActivationId,`poolIdentity.materialActivationId`),capability:M(t.capability,`poolIdentity.capability`),keyBinding:M(t.keyBinding,`poolIdentity.keyBinding`),walletId:M(t.walletId,`poolIdentity.walletId`),signingScopeB64u:M(t.signingScopeB64u,`poolIdentity.signingScopeB64u`),pairRole:`client`,keyEpoch:M(t.keyEpoch,`poolIdentity.keyEpoch`),activationEpoch:ze(t.activationEpoch),protocolId:j}}function ze(e){let t=n(e);if(!t.ok)throw Error(`poolIdentity.activationEpoch is invalid`);return t.value}function Be(e,t){return e.ownershipGeneration===t.ownershipGeneration&&e.relayerUrl===t.relayerUrl&&e.materialActivationB64u===t.materialActivationB64u&&e.materialActivationId===t.materialActivationId&&e.capability===t.capability&&e.keyBinding===t.keyBinding&&e.walletId===t.walletId&&e.signingScopeB64u===t.signingScopeB64u&&e.pairRole===t.pairRole&&e.keyEpoch===t.keyEpoch&&e.activationEpoch===t.activationEpoch&&e.protocolId===t.protocolId}function P(e){return[e.protocolId,e.relayerUrl,e.signingScopeB64u,e.materialActivationB64u,e.ownershipGeneration].join(`|`)}function Ve(e){let t=le(e.scope),n=e.materialActivation,r=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);return{ownershipGeneration:e.ownershipGeneration,relayerUrl:r,materialActivationB64u:c(te(n)),materialActivationId:n.activation_id,capability:n.capability,keyBinding:n.key_binding,walletId:t.wallet_id,signingScopeB64u:c(pe(t)),pairRole:`client`,keyEpoch:t.signing_worker.key_epoch,activationEpoch:t.activation_epoch,protocolId:j}}const He=`ecdsa_capability_manifest_v3`,F=`ecdsa_current_capability_manifest_v2`,Ue=`ecdsa_role_local_material_v2`,We=`ecdsa_activation_commit_journal_v1`,Ge=`ecdsa_material_sealing_key_v1`,Ke=m.ecdsaCapabilityManifests,qe=m.ecdsaCurrentCapabilityManifests,Je=m.ecdsaRoleLocalMaterial,Ye=m.ecdsaActivationCommitJournals,Xe=m.ecdsaMaterialSealingKeys,I=m.ecdsaClientPresignatures;function L(e,t,n){let r=Object.keys(e).sort(),i=[...n].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`${t} has unexpected fields`)}function Ze(e){let n=y(e.authority);if(!n)throw Error(`ECDSA capability selector authority is invalid`);return{capability:D(t(e.capability)),authority:n}}function R(e){return{capability:e.capability,authority:e.authority}}function z(e){return R(e.candidate.activationBinding.signer)}function B(e){return R(e.signer)}function V(e){return[String(e.capability),String(e.authority.walletId),String(e.authority.authorityDigest)]}function H(e){return{capability_ref:e.capability,wallet_id:e.authority.walletId,authority_digest:e.authority.authorityDigest,wallet_auth_method_id:e.authority.walletAuthMethodId}}function Qe(e){return y({kind:`wallet_auth_authority_ref`,walletId:e.wallet_id,authorityDigest:e.authority_digest,walletAuthMethodId:e.wallet_auth_method_id})}function $e(e,t){return e.kind===t.kind&&e.walletId===t.walletId&&e.authorityDigest===t.authorityDigest&&e.walletAuthMethodId===t.walletAuthMethodId}function et(e,t){let n=V(e),r=V(t);return n[0]===r[0]&&n[1]===r[1]&&n[2]===r[2]}function U(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function tt(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}function W(e,t){if(e.kind!==t.kind)return!1;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 Y(e)}}function nt(e,t){return e.kind===t.kind&&e.targetMemberships.length===t.targetMemberships.length&&e.targetMemberships.every((e,n)=>W(e,t.targetMemberships[n]))}function G(e,t){return e.kind===t.kind&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.clientVerifyingPublicKey33B64u===t.clientVerifyingPublicKey33B64u&&U(e.participantIds,t.participantIds)&&e.relayerKeyId===t.relayerKeyId}function rt(e,t){return e.walletId===t.walletId&&W(e.chainTarget,t.chainTarget)&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion&&e.applicationBindingDigestB64u===t.applicationBindingDigestB64u&&e.clientParticipantId===t.clientParticipantId&&e.relayerParticipantId===t.relayerParticipantId&&U(e.participantIds,t.participantIds)&&e.contextBinding32B64u===t.contextBinding32B64u&&e.derivationClientSharePublicKey33B64u===t.derivationClientSharePublicKey33B64u&&e.relayerPublicKey33B64u===t.relayerPublicKey33B64u&&e.groupPublicKey33B64u===t.groupPublicKey33B64u&&e.ethereumAddress===t.ethereumAddress&&ie(e.publicCapability,t.publicCapability)}function it(e,t){return e.kind===t.kind&&e.keyHandle===t.keyHandle&&e.publicKeyB64u===t.publicKeyB64u&&U(e.participantIds,t.participantIds)&&e.thresholdOwnerAddress===t.thresholdOwnerAddress}function at(e,t){return e.manifestId===t.manifestId&&e.manifestRevision===t.manifestRevision}function ot(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`no_current_manifest`:return!0;case`exact_manifest`:return t.kind===`exact_manifest`&&e.manifestId===t.manifestId&&e.manifestRevision===t.manifestRevision;default:return Y(e)}}function st(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`no_current_generation`:return!0;case`exact_generation`:return t.kind===`exact_generation`&&e.serverGeneration===t.serverGeneration;default:return Y(e)}}function ct(e,t){return e.kind===t.kind&&e.capability===t.capability&&e.signerId===t.signerId&&e.walletId===t.walletId&&$e(e.authority,t.authority)&&nt(e.scope,t.scope)&&e.materialOwner===t.materialOwner&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion}function lt(e,t){return ct(e,t)&&it(e.registeredPublicFacts,t.registeredPublicFacts)}function ut(e,t){return e.kind===t.kind&&e.sealingKeyId===t.sealingKeyId&&e.iv12B64u===t.iv12B64u&&e.ciphertextB64u===t.ciphertextB64u&&e.ciphertextDigest===t.ciphertextDigest}function dt(e,t){return e.kind===t.kind&&at(e.targetManifest,t.targetManifest)&&ct(e.signer,t.signer)&&G(e.roleLocalBinding,t.roleLocalBinding)&&e.bindingDigest===t.bindingDigest&&e.durableMaterialRef===t.durableMaterialRef}function K(e,t){return e.kind===t.kind&&e.correlationId===t.correlationId&&e.activationRequestDigest===t.activationRequestDigest&&e.serverGeneration===t.serverGeneration&&ft(e.serverActivationReceipt,t.serverActivationReceipt)}function ft(e,t){return e.kind===t.kind&&e.lifecycleId===t.lifecycleId&&e.activationDigest===t.activationDigest&&e.activatedAt===t.activatedAt&&fe(e.protocolReceipt,t.protocolReceipt)}function pt(e,t){return e.kind===t.kind&&e.correlationId===t.correlationId&&st(e.expectedGeneration,t.expectedGeneration)&&e.requestDigest===t.requestDigest&&e.canonicalRequest===t.canonicalRequest}function mt(e,t){return e.kind===t.kind&&dt(e.activationBinding,t.activationBinding)&&ut(e.encryptedPending,t.encryptedPending)}function ht(e,t){if(e.kind!==t.kind||!(e.journalId===t.journalId&&ot(e.expectedManifest,t.expectedManifest)&&pt(e.activationCommand,t.activationCommand)&&mt(e.candidate,t.candidate)&&e.createdAt===t.createdAt))return!1;switch(e.kind){case`activation_prepared`:return!0;case`server_activation_committed`:return t.kind===`server_activation_committed`&&K(e.serverActivation,t.serverActivation);default:return Y(e)}}function gt(e,t){return e.kind===t.kind&&r(e.materialActivation,t.materialActivation)&&ce(e.routerAbEcdsaDerivationNormalSigning,t.routerAbEcdsaDerivationNormalSigning)&&rt(e.roleLocalPublicFacts,t.roleLocalPublicFacts)&&G(e.roleLocalBinding,t.roleLocalBinding)&&e.durableMaterialRef===t.durableMaterialRef&&e.bindingDigest===t.bindingDigest&&e.lifecycleId===t.lifecycleId&&e.ciphertextDigest===t.ciphertextDigest&&e.activationDigest===t.activationDigest&&e.activatedAt===t.activatedAt&&tt(e.runtimePolicyScope,t.runtimePolicyScope)}function _t(e,t){return e.kind===t.kind&&r(e.materialActivation,t.materialActivation)&&K(e.serverActivation,t.serverActivation)&&e.retention===t.retention}function vt(e,t){return e.kind===t.kind&&at(e.identity,t.identity)&<(e.signer,t.signer)&&_t(e.activation,t.activation)&>(e.durableMaterial,t.durableMaterial)&&e.committedAt===t.committedAt}function yt(e,t){try{let n=i(t.serverActivationReceipt,`ECDSA server activation receipt`);return t.kind===e.kind&&f(t.correlationId)===e.correlationId&&p(t.activationRequestDigest)===e.activationRequestDigest&&w(t.serverGeneration)===e.serverGeneration&&n.kind===e.serverActivationReceipt.kind&&n.lifecycleId===String(e.serverActivationReceipt.lifecycleId)&&n.activationDigest===String(e.serverActivationReceipt.activationDigest)&&d(n.activatedAt)===e.serverActivationReceipt.activatedAt&&fe(ee(n.protocolReceipt),e.serverActivationReceipt.protocolReceipt)}catch{return!1}}function bt(e){let t=A({activationBinding:e.preparation.activationBinding,encryptedPending:e.encryptedPending});return xt({...e.preparation,candidate:t})}function xt(e){let t={journalId:e.journalId,candidate:e.candidate,requestDigest:e.requestDigest,canonicalRequest:e.canonicalRequest,createdAt:e.createdAt};switch(e.expectedManifest.kind){case`no_current_manifest`:if(e.expectedGeneration.kind!==`no_current_generation`)throw Error(`Initial ECDSA activation cannot expect a server generation`);return k({...t,expectedManifest:e.expectedManifest,expectedGeneration:e.expectedGeneration});case`exact_manifest`:if(e.expectedGeneration.kind!==`exact_generation`)throw Error(`Replacement ECDSA activation requires an exact server generation`);return k({...t,expectedManifest:e.expectedManifest,expectedGeneration:e.expectedGeneration});default:return Y(e.expectedManifest)}}function St(e,t){if(typeof e!=`string`||e.length===0||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be non-empty unpadded base64url`);let n=l(e);if(n.length===0||c(n)!==e)throw n.fill(0),Error(`${t} must be canonical base64url`);return n}function q(e){return new TextEncoder().encode(o(e))}async function Ct(){return await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function wt(e){let t=St(e.stateBlobB64u,`ECDSA state blob`),n=crypto.getRandomValues(new Uint8Array(12)),r=q(e.aadProjection);try{let i=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,additionalData:r},e.key,t));try{return{iv12B64u:v(c(n)),ciphertextB64u:x(c(i)),digestB64u:c(await a(i))}}finally{i.fill(0)}}finally{t.fill(0),r.fill(0)}}async function Tt(e){let t=l(e);try{return c(await a(t))}finally{t.fill(0)}}async function Et(e){let t=l(e.iv12B64u),n=l(e.ciphertextB64u),r=q(e.aadProjection),i=null;try{if(i=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:t,additionalData:r},e.key,n)),i.length===0)throw Error(`decrypted ECDSA state blob must not be empty`);return c(i)}finally{t.fill(0),n.fill(0),r.fill(0),i?.fill(0)}}function Dt(e){let t=i(e,`ECDSA manifest identity`);return L(t,`ECDSA manifest identity`,[`manifestId`,`manifestRevision`]),be({manifestId:C(t.manifestId),manifestRevision:S(t.manifestRevision)})}function Ot(e){let t=i(e,`ECDSA manifest expectation`);switch(t.kind){case`no_current_manifest`:return L(t,`ECDSA no-current manifest expectation`,[`kind`]),Se();case`exact_manifest`:return L(t,`ECDSA exact manifest expectation`,[`kind`,`manifestId`,`manifestRevision`]),De(be({manifestId:C(t.manifestId),manifestRevision:S(t.manifestRevision)}));default:throw Error(`ECDSA manifest expectation kind is invalid`)}}function kt(e){let t=i(e,`ECDSA capability target`);switch(t.kind){case`evm`:return L(t,`ECDSA EVM capability target`,[`kind`,`namespace`,`chainId`,`networkSlug`]),_({kind:t.kind,namespace:t.namespace,chainId:t.chainId,networkSlug:t.networkSlug});case`tempo`:return L(t,`ECDSA Tempo capability target`,[`kind`,`chainId`,`networkSlug`]),_({kind:t.kind,chainId:t.chainId,networkSlug:t.networkSlug});default:throw Error(`ECDSA capability target kind is invalid`)}}function At(e){let t=i(e,`ECDSA capability scope`);if(L(t,`ECDSA capability scope`,[`kind`,`targetMemberships`]),t.kind!==`evm_family`)throw Error(`ECDSA capability scope kind is invalid`);let n=s(t.targetMemberships,`ECDSA capability target memberships`),r=[];for(let e of n)r.push(kt(e));let[a,...o]=r;if(!a)throw Error(`ECDSA capability scope requires at least one target`);return Ee({targetMemberships:[a,...o]})}function jt(e){let t=i(e,`ECDSA role-local material binding`);if(L(t,`ECDSA role-local material binding`,[`kind`,`keyHandle`,`ecdsaThresholdKeyId`,`clientVerifyingPublicKey33B64u`,`participantIds`,`relayerKeyId`]),t.kind!==`ecdsa_role_local_material_binding`)throw Error(`ECDSA role-local material binding kind is invalid`);let n=s(t.participantIds,`ECDSA role-local participant ids`),r=[];for(let e of n)r.push(Re(e));let[a,...o]=r;if(!a)throw Error(`ECDSA role-local material requires at least one participant`);return ke({keyHandle:Fe(t.keyHandle),ecdsaThresholdKeyId:ge(t.ecdsaThresholdKeyId),clientVerifyingPublicKey33B64u:E(t.clientVerifyingPublicKey33B64u),participantIds:[a,...o],relayerKeyId:me(t.relayerKeyId)})}function Mt(n){let r=i(n,`prepared ECDSA signer`);if(L(r,`prepared ECDSA signer`,[`kind`,`capability`,`signerId`,`walletId`,`authority`,`scope`,`materialOwner`,`signingRootId`,`signingRootVersion`]),r.kind!==`prepared_evm_family_signer`)throw Error(`prepared ECDSA signer kind is invalid`);let a=y(r.authority);if(!a)throw Error(`prepared ECDSA signer authority is invalid`);if(String(r.walletId)!==String(a.walletId))throw Error(`prepared ECDSA signer wallet does not match its authority`);return Te({capability:D(t(r.capability)),signerId:oe(r.signerId),authority:a,scope:At(r.scope),materialOwner:D(e(r.materialOwner)),signingRootId:se(r.signingRootId),signingRootVersion:ne(r.signingRootVersion)})}function Nt(e){let t=i(e,`encrypted ECDSA pending candidate`);if(L(t,`encrypted ECDSA pending candidate`,[`kind`,`sealingKeyId`,`iv12B64u`,`ciphertextB64u`,`ciphertextDigest`]),t.kind!==`encrypted_ecdsa_pending_candidate`)throw Error(`encrypted ECDSA pending candidate kind is invalid`);return xe({sealingKeyId:T(t.sealingKeyId),iv12B64u:v(t.iv12B64u),ciphertextB64u:x(t.ciphertextB64u),ciphertextDigest:ue(t.ciphertextDigest)})}function Pt(e){let t=i(e,`ECDSA activation binding`);if(L(t,`ECDSA activation binding`,[`kind`,`targetManifest`,`signer`,`roleLocalBinding`,`bindingDigest`,`durableMaterialRef`]),t.kind!==`ecdsa_activation_binding`)throw Error(`ECDSA activation binding kind is invalid`);return Ae({targetManifest:Dt(t.targetManifest),signer:Mt(t.signer),roleLocalBinding:jt(t.roleLocalBinding),bindingDigest:O(t.bindingDigest),durableMaterialRef:_e(t.durableMaterialRef)})}function Ft(e){let t=i(e,`prepared ECDSA activation candidate`);if(L(t,`prepared ECDSA activation candidate`,[`kind`,`activationBinding`,`encryptedPending`]),t.kind!==`prepared_ecdsa_activation_candidate`)throw Error(`prepared ECDSA activation candidate kind is invalid`);return A({activationBinding:Pt(t.activationBinding),encryptedPending:Nt(t.encryptedPending)})}function It(e){let t=i(e,`ECDSA server generation expectation`);switch(t.kind){case`no_current_generation`:return L(t,`ECDSA no-current server generation expectation`,[`kind`]),Ce();case`exact_generation`:return L(t,`ECDSA exact server generation expectation`,[`kind`,`serverGeneration`]),Ne(w(t.serverGeneration));default:throw Error(`ECDSA server generation expectation kind is invalid`)}}function Lt(e){let t=i(e,`prepared ECDSA activation journal`);if(L(t,`prepared ECDSA activation journal`,[`kind`,`journalId`,`expectedManifest`,`activationCommand`,`candidate`,`createdAt`]),t.kind!==`activation_prepared`)throw Error(`prepared ECDSA activation journal kind is invalid`);let n=i(t.activationCommand,`ECDSA activation command`);if(L(n,`ECDSA activation command`,[`kind`,`correlationId`,`expectedGeneration`,`requestDigest`,`canonicalRequest`]),n.kind!==`ecdsa_server_activation_command`)throw Error(`ECDSA activation command kind is invalid`);let r=f(t.journalId);if(f(n.correlationId)!==r)throw Error(`ECDSA activation command correlation does not match its journal`);let a=Ot(t.expectedManifest),o=It(n.expectedGeneration),s={journalId:r,candidate:Ft(t.candidate),requestDigest:p(n.requestDigest),canonicalRequest:de(n.canonicalRequest),createdAt:d(t.createdAt)};switch(a.kind){case`no_current_manifest`:if(o.kind!==`no_current_generation`)throw Error(`initial ECDSA journal has an exact server generation`);return k({...s,expectedManifest:a,expectedGeneration:o});case`exact_manifest`:if(o.kind!==`exact_generation`)throw Error(`replacement ECDSA journal is missing its exact server generation`);return k({...s,expectedManifest:a,expectedGeneration:o})}return Y(a)}function Rt(e){return{kind:`activation_prepared`,journalId:e.journalId,expectedManifest:e.expectedManifest,activationCommand:e.activationCommand,candidate:e.candidate,createdAt:e.createdAt}}function zt(e){return e.kind===`activation_prepared`?e:xt({journalId:e.journalId,expectedManifest:e.expectedManifest,expectedGeneration:e.activationCommand.expectedGeneration,candidate:e.candidate,requestDigest:e.activationCommand.requestDigest,canonicalRequest:e.activationCommand.canonicalRequest,createdAt:e.createdAt})}function Bt(e){let t=i(e,`server-committed ECDSA activation journal`);if(L(t,`server-committed ECDSA activation journal`,[`kind`,`journalId`,`expectedManifest`,`activationCommand`,`candidate`,`createdAt`,`serverActivation`]),t.kind!==`server_activation_committed`)throw Error(`server-committed ECDSA activation journal kind is invalid`);let n=Lt(Rt(t)),r=Vt(t.serverActivation),a=ye({preparedJournal:n,serverCommit:r.serverCommit});if(!yt(a.serverActivation,r.record))throw Error(`ECDSA server activation commit fields are inconsistent`);return a}function Vt(e){let t=i(e,`ECDSA server activation commit`);if(L(t,`ECDSA server activation commit`,[`kind`,`correlationId`,`activationRequestDigest`,`serverGeneration`,`serverActivationReceipt`]),t.kind!==`ecdsa_server_activation_commit`)throw Error(`ECDSA server activation commit kind is invalid`);let n=i(t.serverActivationReceipt,`ECDSA server activation receipt`);if(L(n,`ECDSA server activation receipt`,[`kind`,`lifecycleId`,`activationDigest`,`activatedAt`,`protocolReceipt`]),n.kind!==`ecdsa_server_activation_receipt`)throw Error(`ECDSA server activation receipt kind is invalid`);return{record:t,serverCommit:{correlationId:f(t.correlationId),activationRequestDigest:p(t.activationRequestDigest),serverGeneration:w(t.serverGeneration),protocolReceipt:n.protocolReceipt}}}function Ht(e){let t=i(e,`ECDSA activation journal`);switch(t.kind){case`activation_prepared`:return Lt(t);case`server_activation_committed`:return Bt(t);default:throw Error(`ECDSA activation journal kind is invalid`)}}function Ut(e){let t=i(e,`registered ECDSA public facts`);if(L(t,`registered ECDSA public facts`,[`kind`,`keyHandle`,`publicKeyB64u`,`participantIds`,`thresholdOwnerAddress`]),t.kind!==`verified_ecdsa_public_facts`)throw Error(`registered ECDSA public facts kind is invalid`);return Le({keyHandle:Ie(t.keyHandle),publicKeyB64u:t.publicKeyB64u,participantIds:s(t.participantIds,`registered ECDSA participant ids`),thresholdOwnerAddress:t.thresholdOwnerAddress})}function J(e){let t=i(e,`active ECDSA manifest proof`);L(t,`active ECDSA manifest proof`,[`activation_binding`,`server_activation`,`registered_public_facts`,`role_local_public_facts`,`router_ab_ecdsa_derivation_normal_signing`,`runtime_policy_scope`,`ciphertext_digest`,`committed_at`]);let n=Pt(t.activation_binding),r=Vt(t.server_activation),a=je({activationBinding:n,serverCommit:r.serverCommit});if(!yt(a,r.record))throw Error(`ECDSA server activation commit fields are inconsistent`);let o=Oe({activationBinding:n,serverActivation:a,routerAbEcdsaDerivationNormalSigning:re(t.router_ab_ecdsa_derivation_normal_signing),roleLocalPublicFacts:he(t.role_local_public_facts),ciphertextDigest:b(t.ciphertext_digest),runtimePolicyScope:u(t.runtime_policy_scope)}),s=d(t.committed_at);return{activationBinding:n,serverActivation:a,durableMaterial:o,activeManifest:Me({activationBinding:n,serverActivation:a,registeredPublicFacts:Ut(t.registered_public_facts),durableMaterial:o,committedAt:s}),committedAt:s}}function Wt(e){let t=i(e,`ECDSA capability manifest row`),n=[`record_version`,`manifest_id`,`manifest_revision`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`manifest_state`,`active_proof`];switch(t.manifest_state){case`active`:{L(t,`active ECDSA capability manifest row`,n);let e=J(t.active_proof),r=B(e.activeManifest);return Gt(t,e.activeManifest,r),{state:`active`,selector:r,manifest:e.activeManifest,activeProof:e}}case`replaced`:{L(t,`replaced ECDSA capability manifest row`,[...n,`replacement_proof`]);let e=J(t.active_proof),r=J(t.replacement_proof),i=we({activeManifest:e.activeManifest,replacementManifest:r.activeManifest}),a=B(e.activeManifest);return Gt(t,e.activeManifest,a),{state:`replaced`,selector:a,manifest:i,activeProof:e,replacementProof:r}}default:throw Error(`ECDSA capability manifest row state is invalid`)}}function Gt(e,t,n){if(e.record_version!==`ecdsa_capability_manifest_v3`||C(e.manifest_id)!==t.identity.manifestId||S(e.manifest_revision)!==t.identity.manifestRevision||String(e.capability_ref)!==String(n.capability)||String(e.wallet_id)!==String(n.authority.walletId)||String(e.authority_digest)!==String(n.authority.authorityDigest))throw Error(`ECDSA capability manifest row identity is inconsistent`)}function Kt(e){return{record_version:F,...H(B(e)),manifest_id:e.identity.manifestId,manifest_revision:e.identity.manifestRevision}}function qt(e){let n=i(e,`current ECDSA capability pointer`);if(L(n,`current ECDSA capability pointer`,[`record_version`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`manifest_id`,`manifest_revision`]),n.record_version!==F)throw Error(`current ECDSA capability pointer version is invalid`);let r=Qe(n);if(!r)throw Error(`current ECDSA capability pointer authority is invalid`);return{selector:{capability:D(t(n.capability_ref)),authority:r},manifestId:C(n.manifest_id),manifestRevision:S(n.manifest_revision)}}function Jt(e,t){return{record_version:Ue,durable_material_ref:e.binding.durableMaterialRef,binding_digest:e.binding.bindingDigest,...H(B(t)),sealing_key_id:e.sealingKeyId,iv:e.iv12B64u,ciphertext:e.ciphertextB64u}}function Yt(e){let n=i(e,`ECDSA role-local material row`);if(L(n,`ECDSA role-local material row`,[`record_version`,`durable_material_ref`,`binding_digest`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`sealing_key_id`,`iv`,`ciphertext`]),n.record_version!==Ue)throw Error(`ECDSA role-local material row version is invalid`);let r=Qe(n);if(!r)throw Error(`ECDSA role-local material authority is invalid`);return{durableMaterialRef:_e(n.durable_material_ref),bindingDigest:O(n.binding_digest),selector:{capability:D(t(n.capability_ref)),authority:r}}}function Xt(e,t){let n=i(e,`ECDSA role-local material row`),r=Yt(n),a=Pe({binding:t.durableMaterial,sealingKeyId:T(n.sealing_key_id),iv12B64u:v(n.iv),ciphertextB64u:x(n.ciphertext)});if(r.durableMaterialRef!==a.binding.durableMaterialRef||r.bindingDigest!==a.binding.bindingDigest||!et(r.selector,B(t.activeManifest)))throw Error(`ECDSA role-local material row binding is inconsistent`);return a}function Zt(e,t){return e.binding.durableMaterialRef===t.durableMaterial.durableMaterialRef&&e.binding.bindingDigest===t.durableMaterial.bindingDigest&&e.binding.lifecycleId===t.durableMaterial.lifecycleId&&e.binding.ciphertextDigest===t.durableMaterial.ciphertextDigest&&e.binding.activationDigest===t.durableMaterial.activationDigest&&e.binding.activatedAt===t.durableMaterial.activatedAt&&r(e.binding.materialActivation,t.durableMaterial.materialActivation)&&G(e.binding.roleLocalBinding,t.durableMaterial.roleLocalBinding)}function Qt(e){return{record_version:We,journal_id:e.journalId,...H(z(e)),journal:e}}function $t(e){let t=i(e,`ECDSA activation commit journal row`);if(L(t,`ECDSA activation commit journal row`,[`record_version`,`journal_id`,`capability_ref`,`wallet_id`,`authority_digest`,`wallet_auth_method_id`,`journal`]),t.record_version!==We)throw Error(`ECDSA activation commit journal row version is invalid`);let n=Ht(t.journal),r=z(n);if(f(t.journal_id)!==n.journalId||String(t.capability_ref)!==String(r.capability)||String(t.wallet_id)!==String(r.authority.walletId)||String(t.authority_digest)!==String(r.authority.authorityDigest))throw Error(`ECDSA activation commit journal row identity is inconsistent`);return{journal:n,selector:r}}function en(e){return typeof CryptoKey>`u`||!(e instanceof CryptoKey)||e.type!==`secret`||e.extractable||e.algorithm.name!==`AES-GCM`?!1:e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function tn(e,t){return{record_version:Ge,key_id:e,key:t}}function nn(e){let t=i(e,`ECDSA material sealing key row`);if(L(t,`ECDSA material sealing key row`,[`record_version`,`key_id`,`key`]),t.record_version!==Ge)throw Error(`ECDSA material sealing key row version is invalid`);if(!en(t.key))throw Error(`ECDSA material sealing key must be a non-extractable AES-GCM key`);return{keyId:T(t.key_id),key:t.key}}function Y(e){throw Error(`Unexpected ECDSA persistence branch: ${String(e)}`)}const rn=5*6e4;function an(e,t,n){let i=e.binding.routerAbEcdsaDerivationNormalSigning.scope,a=ae(e.binding.materialActivation);return i.wallet_id===t.walletId&&c(pe(i))===t.signingScopeB64u&&c(te(a))===t.materialActivationB64u&&i.signing_worker.key_epoch===t.keyEpoch&&i.activation_epoch===t.activationEpoch&&a.activation_id===t.materialActivationId&&a.capability===t.capability&&a.key_binding===t.keyBinding&&a.material_owner===t.walletId&&e.binding.durableMaterialRef===n.durableMaterialRef&&e.binding.bindingDigest===n.bindingDigest&&r(e.binding.materialActivation,n.materialActivation)}function on(e,t){return e.materialActivation.activationId===t.materialActivationId&&e.materialActivation.capability===t.capability&&e.materialActivation.keyBinding===t.keyBinding&&e.materialActivation.materialOwner===t.walletId}function sn(e){if(typeof e!=`string`||!/^ecdsa-client-presignature-[A-Za-z0-9_-]+$/.test(e))throw Error(`ECDSA durable presignature record id is invalid`);return e}function X(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} is invalid`);return e}function Z(e){if(!e||typeof e!=`object`||!(`record_id`in e))return null;let t=e.record_id;return typeof t==`string`?t:null}function cn(){return typeof IDBTransaction<`u`&&`durability`in IDBTransaction.prototype}async function ln(e,t=1/0){let n=0;for(;e&&n<t;)await e.delete(),n+=1,e=await e.continue();return n}async function un(e,t,n){return await ln(await e.store(I).index(h.walletExpiresAt).openCursor(IDBKeyRange.bound([t,0],[t,n])),32)}async function dn(e,t,n){await un(e,t.walletId,n);let r=e.store(I),i=await r.index(h.poolIdentityKey).getAll(P(t));t.ownershipGeneration===1&&i.push(...await r.index(h.poolIdentityKey).getAll(pn(t)));let a=[];for(let e of i)try{let t=Q(e);t.expires_at_ms<=n?await r.delete(t.record_id):(e.pool_identity_key!==t.pool_identity_key&&await r.put(t),a.push(t))}catch{let t=Z(e);t&&await r.delete(t)}return a}function fn(e){let{ownershipGeneration:t,...n}=e.poolIdentity;return{domain:`seams/ecdsa-client-presignature/v1`,version:1,pool_identity:t===1?n:e.poolIdentity,durable_material_ref:e.durableMaterialRef,presignature_id:e.presignatureId,group_public_key33_b64u:e.groupPublicKey33B64u,big_r33_b64u:e.bigR33B64u,created_at_ms:e.createdAtMs,expires_at_ms:e.expiresAtMs,sealing_key_id:e.sealingKeyId}}function pn(e){return[e.protocolId,e.relayerUrl,e.signingScopeB64u,e.materialActivationB64u].join(`|`)}function Q(e){let t=i(e,`ECDSA durable presignature row`);if(L(t,`ECDSA durable presignature row`,[`kind`,`record_id`,`pool_identity`,`pool_identity_key`,`wallet_id`,`material_activation_id`,`durable_material_ref`,`presignature_id`,`group_public_key33_b64u`,`big_r33_b64u`,`created_at_ms`,`expires_at_ms`,`sealed`]),t.kind!==`sealed_available_client_presignature_v1`)throw Error(`ECDSA durable presignature row kind is invalid`);let n=i(t.pool_identity,`ECDSA durable presignature pool identity`),r=!Object.hasOwn(n,`ownershipGeneration`);L(n,`ECDSA durable presignature pool identity`,[...r?[]:[`ownershipGeneration`],`activationEpoch`,`capability`,`keyBinding`,`keyEpoch`,`materialActivationB64u`,`materialActivationId`,`pairRole`,`protocolId`,`relayerUrl`,`signingScopeB64u`,`walletId`]);let a=N(r?{...n,ownershipGeneration:1}:n),o=sn(t.record_id),s=String(t.pool_identity_key??``);if(s!==P(a)&&!(r&&s===pn(a)))throw Error(`ECDSA durable presignature pool identity index is inconsistent`);let c=String(t.wallet_id??``).trim(),l=String(t.material_activation_id??``).trim();if(!c||c!==a.walletId)throw Error(`ECDSA durable presignature wallet binding is inconsistent`);if(!l||l!==a.materialActivationId)throw Error(`ECDSA durable presignature activation binding is inconsistent`);let u=ve(t.durable_material_ref);if(!on(u,a))throw Error(`ECDSA durable presignature material binding is inconsistent`);let d=String(t.presignature_id??``).trim();if(!d)throw Error(`ECDSA durable presignature id is invalid`);let f=E(t.group_public_key33_b64u),p=E(t.big_r33_b64u),m=X(t.created_at_ms,`created_at_ms`),h=X(t.expires_at_ms,`expires_at_ms`);if(m>Date.now()+3e5)throw Error(`ECDSA durable presignature creation timestamp is in the future`);if(h<=m)throw Error(`ECDSA durable presignature expiry must follow creation`);if(h-m>7776e6)throw Error(`ECDSA durable presignature lifetime exceeds the maximum`);let g=i(t.sealed,`ECDSA durable presignature sealed payload`);if(L(g,`ECDSA durable presignature sealed payload`,[`kind`,`sealing_key_id`,`iv12_b64u`,`ciphertext_b64u`,`ciphertext_digest_b64u`]),g.kind!==`ecdsa_activation_aes_gcm_v1`)throw Error(`ECDSA durable presignature sealing kind is invalid`);return{kind:`sealed_available_client_presignature_v1`,record_id:o,pool_identity:a,pool_identity_key:P(a),wallet_id:c,material_activation_id:l,durable_material_ref:u,presignature_id:d,group_public_key33_b64u:f,big_r33_b64u:p,created_at_ms:m,expires_at_ms:h,sealed:{kind:`ecdsa_activation_aes_gcm_v1`,sealing_key_id:T(g.sealing_key_id),iv12_b64u:v(g.iv12_b64u),ciphertext_b64u:x(g.ciphertext_b64u),ciphertext_digest_b64u:b(g.ciphertext_digest_b64u)}}}function mn(e){return{kind:`sealed_available_client_presignature_v1`,recordId:e.record_id,poolIdentity:e.pool_identity,durableMaterialRef:e.durable_material_ref,presignatureId:e.presignature_id,groupPublicKey33B64u:e.group_public_key33_b64u,bigR33B64u:e.big_r33_b64u,createdAtMs:e.created_at_ms,expiresAtMs:e.expires_at_ms,sealingKeyId:e.sealed.sealing_key_id}}async function hn(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=q(fn(e.metadata));try{let r=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:t,additionalData:n},e.key,e.plaintext97));try{let e=c(r);return{iv12B64u:v(c(t)),ciphertextB64u:x(e),ciphertextDigestB64u:b(c(await a(r)))}}finally{r.fill(0)}}finally{t.fill(0),n.fill(0),e.plaintext97.fill(0)}}async function gn(e){let t=l(e.sealed.iv12_b64u),n=l(e.sealed.ciphertext_b64u),r=q(fn(e.metadata)),i=null;try{if(c(await a(n))!==e.sealed.ciphertext_digest_b64u)throw Error(`ECDSA durable presignature ciphertext digest mismatch`);if(i=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:t,additionalData:r},e.key,n)),i.length!==97)throw Error(`ECDSA durable presignature plaintext length is invalid`);return i.slice()}finally{t.fill(0),n.fill(0),r.fill(0),i?.fill(0)}}async function _n(e,t,n){let r=e.store(I),i=await r.index(h.walletMaterialActivationId).getAll([t,n]);for(let e of i){let t=Z(e);t&&await r.delete(t)}}async function $(e,t){let n=await e.store(m.appState).get(`wallet_ownership_generation:${t}`);if(n===void 0)return 1;let r=i(n,`Wallet ownership generation`).value;if(typeof r!=`number`||!Number.isSafeInteger(r)||r<1)throw Error(`Stored wallet ownership generation is invalid`);return r}async function vn(e,t,n){if(await $(e,t)!==n)throw Error(`Wallet ownership generation requires fresh authentication`)}async function yn(e,t,n){let r=await $(e,t);if(n<r)throw Error(`Wallet session belongs to an obsolete ownership generation`);if(n===r)return;await e.store(m.appState).put({key:`wallet_ownership_generation:${t}`,value:n});let i=await e.store(m.ecdsaClientPresignatures).index(h.walletId).openCursor(t);for(;i;){let e=!0;try{e=Q(i.value).pool_identity.ownershipGeneration<n}catch{}e&&await i.delete(),i=await i.continue()}}async function bn(e,t){await g.runTransaction([m.appState],`readonly`,xn.bind(null,e,t))}function xn(e,t,n){return vn(n,e,t)}async function Sn(e,t){await g.runTransaction([m.appState,m.ecdsaClientPresignatures],`readwrite`,Cn.bind(null,e,t))}async function Cn(e,t,n){t<=await $(n,e)||await yn(n,e,t)}export{B as $,vt as A,Ze as B,I as C,Tt as D,bt as E,rt as F,Yt as G,Bt as H,K as I,nn as J,Xt as K,wt as L,gt as M,it as N,Et as O,G as P,z as Q,Ct as R,qe as S,Y as T,$t as U,J as V,Wt as W,tt as X,zt as Y,H as Z,cn as _,rn as a,Kt as at,Ke as b,hn as c,P as ct,sn as d,N as dt,R as et,X as f,_n as g,dn as h,Sn as i,Jt as it,nt as j,ht as k,on as l,Be as lt,Z as m,bn as n,et as nt,an as o,tn as ot,Q as p,qt as q,vn as r,Qt as rt,gn as s,$e as st,yn as t,V as tt,mn as u,Ve as ut,Ye as v,Xe as w,Je as x,He as y,Zt as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e,u as t}from"./participants-BXdREC5k.js";import{r as n}from"./base64-BmKR3UqU.js";import{r,t as i}from"./secureRandomId-8LSc91aN.js";import{o as a}from"./signerSlot-BlijMq8C.js";import{t as o}from"./indexedDB-CA4tGqkr.js";import{n as s,s as c,t as l,u}from"./helpers-B7c1zc7h.js";import{i as ee}from"./pendingWalletRecoveryCodeBackup-DXFrQmO5.js";import{t as d}from"./walletOwnerOperation-CScYv2K6.js";import{t as f}from"./webauthnPromptCoordinator-npsSRD51.js";import{i as p}from"./collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js";function m(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===5&&n.every(e=>[`ok`,`challengeId`,`challenge_digest`,`expiresAtMs`,`otpChannel`].includes(e))&&t.get(`ok`)===!0)return{kind:`success`,challengeId:t.get(`challengeId`),challengeDigest:t.get(`challenge_digest`),expiresAtMs:t.get(`expiresAtMs`),otpChannel:t.get(`otpChannel`)};let r=[`ok`,`code`,`message`,`retryAfterMs`];if((t.size===3||t.size===4)&&n.every(e=>r.includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`&&typeof t.get(`message`)==`string`&&(t.size===3||typeof t.get(`retryAfterMs`)==`number`)){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function h(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/custody/email-otp/challenge`,body:{walletId:e.walletId,providerSubjectId:e.providerSubjectId,operation:e.operation,payload:e.payload,...e.requestOrigin?{requestOrigin:e.requestOrigin}:{}},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`Email OTP challenge request failed`}}let n=m(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status!==200||n.kind!==`success`)return{kind:t.status>=400&&t.status<500?`rejected`:`transport_failed`,message:r||`Email OTP challenge failed (HTTP ${t.status})`};let i=typeof n.challengeId==`string`?n.challengeId.trim():``,a=typeof n.challengeDigest==`string`?n.challengeDigest.trim():``,o=Number(n.expiresAtMs),s=typeof n.otpChannel==`string`?n.otpChannel.trim():``;return!i||!a||!Number.isSafeInteger(o)||o<=0||!s?{kind:`transport_failed`,message:`Email OTP challenge returned an unusable payload`}:{kind:`ready`,challengeId:i,challenge_digest:a,expiresAtMs:o,otpChannel:s}}function g(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[`ok`,`activeCodeCount`,`totalCodeCount`,`issuedAtMs`,`storeVersion`,`backupOutstanding`],r=[...t.keys()];if(t.size===n.length&&r.every(e=>n.includes(e))&&t.get(`ok`)===!0)return{kind:`success`,activeCodeCount:t.get(`activeCodeCount`),totalCodeCount:t.get(`totalCodeCount`),issuedAtMs:t.get(`issuedAtMs`),storeVersion:t.get(`storeVersion`),backupOutstanding:t.get(`backupOutstanding`)};let i=[`ok`,`code`,`message`];if(t.size===i.length&&r.every(e=>i.includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function _(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/${encodeURIComponent(e.walletId)}/recovery/status`,body:{requestId:e.requestId,factorProof:e.factorProof},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`recovery status request failed`}}let n=g(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===401||t.status===403)return{kind:`unauthorized`,message:r||`recovery status is unauthorized`};if(t.status===404)return{kind:`no_recovery_set`,message:r||`this wallet has no recovery set`};if(t.status!==200)return{kind:`transport_failed`,message:r||`recovery status failed (HTTP ${t.status})`};if(n.kind!==`success`)return{kind:`transport_failed`,message:`recovery status returned an unusable payload`};let i=Number(n.activeCodeCount),a=Number(n.totalCodeCount),o=Number(n.issuedAtMs),s=typeof n.storeVersion==`string`?n.storeVersion.trim():``;return!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<i||!Number.isSafeInteger(o)||o<=0||!s||typeof n.backupOutstanding!=`boolean`?{kind:`transport_failed`,message:`recovery status returned an unusable payload`}:{kind:`ready`,walletId:e.walletId,activeCodeCount:i,totalCodeCount:a,issuedAtMs:o,storeVersion:s,backupOutstanding:n.backupOutstanding,pendingLocalBackup:!1}}function v(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===2&&n.includes(`ok`)&&n.includes(`issuedAtMs`)&&t.get(`ok`)===!0)return{kind:`success`,issuedAtMs:t.get(`issuedAtMs`)};if(t.size===3&&n.includes(`ok`)&&n.includes(`code`)&&n.includes(`message`)&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function y(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/recovery/acknowledge-backup`,body:{walletId:e.walletId,requestId:e.requestId,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:e.factorProof},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`recovery backup acknowledgement failed`}}let n=v(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===401||t.status===403)return{kind:`unauthorized`,message:r||`recovery backup acknowledgement is unauthorized`};if(t.status===404)return{kind:`no_recovery_set`,message:r||`this wallet has no recovery set`};if(t.status===409)return{kind:`conflict`,message:r||`Recovery codes changed. Check status and review the current set.`};if(t.status!==200)return{kind:`transport_failed`,message:r||`recovery backup acknowledgement failed (HTTP ${t.status})`};if(n.kind!==`success`)return{kind:`transport_failed`,message:`recovery backup acknowledgement returned an unusable payload`};let i=Number(n.issuedAtMs);return!Number.isSafeInteger(i)||i<=0?{kind:`transport_failed`,message:`recovery backup acknowledgement returned an unusable payload`}:{kind:`acknowledged`,walletId:e.walletId,issuedAtMs:i}}function b(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===3&&n.every(e=>[`ok`,`issuedAtMs`,`storeVersion`].includes(e))&&t.get(`ok`)===!0)return{kind:`success`,issuedAtMs:t.get(`issuedAtMs`),storeVersion:t.get(`storeVersion`)};if(t.size===3&&n.every(e=>[`ok`,`code`,`message`].includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function x(e){let t=await S({relayUrl:e.relayUrl,path:`/wallets/recovery/rotate`,body:{walletId:e.walletId,expectedStoreVersion:e.expectedStoreVersion,manifestKekWraps:e.replacement.manifestKekWraps,entries:[e.replacement.entry],recoveryCodeLocators:e.recoveryCodeLocators,factorProof:e.factorProof},fetchImpl:e.fetchImpl}),n=b(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===200&&n.kind===`success`){let e=Number(n.issuedAtMs),t=typeof n.storeVersion==`string`?n.storeVersion.trim():``;return!Number.isSafeInteger(e)||e<=0||!t?{kind:`transport_failed`,message:`rotation returned an unusable response`}:{kind:`rotated`,issuedAtMs:e,storeVersion:t}}return t.status===404?{kind:`no_recovery_set`,message:r||`no recovery set`}:t.status===409?{kind:`conflict`,message:r||`recovery set changed`}:t.status===400?{kind:`rejected`,message:r||`rotation rejected`}:{kind:`transport_failed`,message:r||`rotation failed (HTTP ${t.status})`}}async function S(n){let r=`${t(n.relayUrl)}${n.path}`;return await(n.fetchImpl||fetch)(r,e({headers:{Accept:`application/json`},body:n.body}))}var C=class extends Error{code=`wallet_origin_webauthn_unavailable`;constructor(e){super(e),this.name=`WalletOriginWebAuthnUnavailableError`}};async function w(e,t,n){let r=T(e,t);try{return e===`create`?await navigator.credentials.create({publicKey:r,...n.abortSignal?{signal:n.abortSignal}:{}}):await navigator.credentials.get({publicKey:r,...n.abortSignal?{signal:n.abortSignal}:{}})}catch(t){throw e===`create`&&(N(t)||P(t))?new C(`Wallet-origin WebAuthn registration is unavailable: ${F(t)}`):t}}function T(e,t){return e===`create`?E(t):D(t)}function E(e){return{...e,challenge:M(e.challenge),user:{...e.user,id:M(e.user.id)},excludeCredentials:e.excludeCredentials?.map(O),extensions:k(e.extensions)}}function D(e){return{...e,challenge:M(e.challenge),allowCredentials:e.allowCredentials?.map(O),extensions:k(e.extensions)}}function O(e){return{...e,id:M(e.id)}}function k(e){if(!e)return e;let t={...e},n=t.prf;if(n&&typeof n==`object`){let e={...n};if(e.eval&&typeof e.eval==`object`&&(e.eval=A(e.eval)),e.evalByCredential&&typeof e.evalByCredential==`object`){let t={};for(let[n,r]of Object.entries(e.evalByCredential))t[n]=r&&typeof r==`object`?A(r):r;e.evalByCredential=t}t.prf=e}return t}function A(e){return{...e,...j(e.first)?{first:M(e.first)}:{},...j(e.second)?{second:M(e.second)}:{}}}function j(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function M(e){if(e instanceof ArrayBuffer)return e.slice(0);let t=e,n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice();if(e instanceof DataView)return new DataView(n.buffer);let r=Object.getPrototypeOf(e).constructor;return new r(n.buffer)}function N(e){let t=F(e);return/origin of the document is not the same as its ancestors/i.test(t)}function P(e){let t=I(e),n=F(e),r=t===`NotAllowedError`,i=/document is not focused|not focused|focus/i.test(n);return!!(r&&i)}function F(e){return String(e?.message||``)}function I(e){let t=e?.name;return typeof t==`string`?t:``}function L(e,t){return(e||t||``).toLowerCase()}function R(e){let t=n(String(e||``));if(t.length!==32)throw Error(`Invalid WebAuthn challenge: expected 32 bytes, got ${t.length}`);return t}function z(e){if(e.kind!==`wallet_registration`)throw Error(`Wallet registration challenge is unavailable`);return e.challengeB64u}function B(e){let t=a(String(e.walletId||``).trim());if(String(e.intendedUserName||``).trim()!==String(t))throw Error(`WebAuthn registration user.name must match walletId`);return{walletId:t}}var V=class{rpIdOverride;abortController;removePageAbortHandlers;removeExternalAbortListener;constructor(e){this.rpIdOverride=e}getRpId(){try{return L(this.rpIdOverride,window?.location?.hostname)}catch{return this.rpIdOverride||``}}getAuthenticationCredentialsSerializedForChallengeB64u(e){let t=`webauthn-get-${i(12,`WebAuthn get request IDs`)}`;return f.runImmediate({owner:{kind:`wallet_request`,requestId:t,operation:`authentication`},operation:this.executeAuthenticationCredential.bind(this,e)})}async executeAuthenticationCredential({subjectId:e,challengeB64u:t,allowCredentials:r=[],includeSecondPrfOutput:i=!1,cancellation:a={kind:`none`}}){this.abortController=new AbortController,this.removePageAbortHandlers=q(this.abortController),this.removeExternalAbortListener=H(this.abortController,a);let o=this.getRpId(),u={challenge:R(t),rpId:o,userVerification:`preferred`,timeout:6e4,extensions:{prf:{eval:{first:l(),second:s()}}}};r.length>0&&(u.allowCredentials=r.map(e=>({id:n(e.id),type:`public-key`,transports:e.transports})));try{let e=c({credential:await w(`get`,u,{abortSignal:this.abortController.signal}),firstPrfOutput:!0,secondPrfOutput:i});return G(e,t),e}finally{this.removePageAbortHandlers?.(),this.removePageAbortHandlers=void 0,this.removeExternalAbortListener?.(),this.removeExternalAbortListener=void 0,this.abortController=void 0}}generateRegistrationCredentialsInternal(e){switch(e.prompt.kind){case`reserved`:return f.runReserved({reservation:e.prompt.reservation,owner:e.prompt.owner,operation:this.executeRegistrationCredential.bind(this,e)});case`immediate`:return f.runImmediate({owner:{kind:`wallet_request`,requestId:e.prompt.requestId,operation:`registration`},operation:this.executeRegistrationCredential.bind(this,e)})}}async executeRegistrationCredential(e){this.abortController=new AbortController,this.removePageAbortHandlers=q(this.abortController),this.removeExternalAbortListener=H(this.abortController,e.prompt.cancellation);let t=this.getRpId(),r=B({walletId:e.walletId,intendedUserName:e.intendedUserName}),i=e.kind===`wallet_recovery`?e.recoveryRegistration:null,a=e.kind===`wallet_add_auth_method`?e.registration:null,o=i??a,c=o?.rpId??t;if(o&&c!==t)throw Error(`Wallet recovery RP ID does not match the wallet origin`);let u=o?{challenge:R(o.challengeB64u),rp:{name:`Seams Wallet`,id:c},user:{id:n(o.user.idB64u),name:o.user.name,displayName:o.user.displayName},pubKeyCredParams:o.pubKeyCredParams.map(e=>({...e})),authenticatorSelection:{...o.authenticatorSelection},timeout:o.timeoutMs,attestation:o.attestation,extensions:{prf:{eval:{first:n(o.extensions.prf.eval.firstB64u),second:n(o.extensions.prf.eval.secondB64u)}}},excludeCredentials:o.excludeCredentials.map(e=>({type:e.type,id:n(e.id)}))}:{challenge:R(z(e)),rp:{name:`WebAuthn Passkey`,id:c},user:{id:new TextEncoder().encode(K(e.walletId,e.signerSlot)),name:r.walletId,displayName:r.walletId},pubKeyCredParams:[{alg:-7,type:`public-key`},{alg:-257,type:`public-key`}],authenticatorSelection:{residentKey:`required`,userVerification:`preferred`},timeout:6e4,attestation:`none`,extensions:{prf:{eval:{first:l(),second:s()}}}};try{return await w(`create`,u,{abortSignal:this.abortController.signal})}finally{this.removePageAbortHandlers?.(),this.removePageAbortHandlers=void 0,this.removeExternalAbortListener?.(),this.removeExternalAbortListener=void 0,this.abortController=void 0}}};function H(e,t){if(t.kind===`none`)return;let n=t.signal,r=e.abort.bind(e);if(n.aborted){r();return}return n.addEventListener(`abort`,r,{once:!0}),n.removeEventListener.bind(n,`abort`,r)}function U(e){return String(e||``).trim().replace(/=+$/g,``)}function W(e){let t=String(e.response?.clientDataJSON||``).trim();if(!t)throw Error(`WebAuthn authentication response missing clientDataJSON`);let r=``;try{r=new TextDecoder().decode(n(t))}catch(e){throw Error(`WebAuthn authentication response has invalid clientDataJSON encoding: ${e instanceof Error?e.message:String(e)}`)}let i;try{i=JSON.parse(r)}catch(e){throw Error(`WebAuthn authentication response has invalid clientDataJSON JSON: ${e instanceof Error?e.message:String(e)}`)}let a=i&&typeof i==`object`?i.challenge:void 0;if(typeof a!=`string`||!a.trim())throw Error(`WebAuthn authentication response clientDataJSON missing challenge`);return a}function G(e,t){let n=U(W(e)),r=U(t);if(n!==r)throw Error(`Unexpected authentication response challenge "${n}", expected "${r}"`)}function K(e,t){return t===void 0||t===1?e:`${e} (${t})`}function q(e){let t=()=>{document.hidden&&e.abort()},n=()=>{e.abort()},r=()=>{e.abort()};return document.addEventListener(`visibilitychange`,t,{passive:!0}),window.addEventListener(`pagehide`,n,{passive:!0}),window.addEventListener(`beforeunload`,r,{passive:!0}),()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`beforeunload`,r)}}async function J(e){let t=e.request.payload.walletId,n=window.location.origin,r=await d({walletId:t,operation:e.request.operation,payload:e.request.payload,requestOrigin:n}),i=await p({credentialStore:o,touchIdPrompt:new V(e.rpId),walletId:t,challengeB64u:r,includeSecondPrfOutput:!1}),a=ee(i);if(!a)throw Error(`Wallet recovery proof did not receive a passkey credential`);return{kind:`passkey`,walletId:t,rpId:e.rpId,credentialIdB64u:a,challenge_digest:r,webauthn_authentication:u(i)}}function Y(){return r(`wallet-recovery-admin`,16,`wallet recovery administration request IDs`)}async function X(e){let t=Y(),n={walletId:e.walletId,requestId:t},r=await J({rpId:e.rpId,request:{operation:`recovery_status`,payload:n}});return await _({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,factorProof:r})}async function Z(e){let t=Y(),n={walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs},r=await J({rpId:e.rpId,request:{operation:`recovery_backup_acknowledge`,payload:n}});return await y({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:r})}async function Q(e){let t=await o.resolveSelectedWalletAuthority(e);if(t.kind!==`resolved`||t.selection.lockState!==`unlocked`||String(t.selection.walletId)!==e||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.kind!==`email_otp`||t.authMethod.status!==`active`||t.authority.state!==`active`||String(t.authMethod.walletId)!==e||String(t.authority.walletId)!==e)throw Error(`Unlock this wallet with its active Email OTP method`);let n=await o.listWalletAuthMethodsForWallet(e),r=null;for(let e of n)if(!(e.kind!==`email_otp`||e.status!==`active`||e.localStatus!==`synced`||String(e.authority.bindingId)!==String(t.authMethod.walletAuthMethodId))){if(r!==null)throw Error(`The selected Email OTP owner method is duplicated`);r=String(e.authority.factor.providerUserId||``).trim()}if(!r)throw Error(`The selected Email OTP owner method is unavailable on this wallet`);return{walletAuthMethodId:String(t.authMethod.walletAuthMethodId),providerSubjectId:r}}async function $(e){let t=e.request.payload.walletId,{providerSubjectId:n}=await Q(t),r=window.location.origin,i=await d({walletId:t,operation:e.request.operation,payload:e.request.payload,requestOrigin:r}),a=await h({relayUrl:e.relayUrl,walletId:t,providerSubjectId:n,operation:e.request.operation,payload:e.request.payload,requestOrigin:r});if(a.kind!==`ready`)throw Error(a.message);if(a.challenge_digest!==i)throw Error(`Recovery Email OTP challenge does not match this operation`);let o=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:e.request.operation,walletId:t,emailAddress:`your email`,challengeId:a.challengeId});if(o.challengeId!==a.challengeId)throw Error(`Recovery Email OTP confirmation changed its challenge`);return{kind:`email_otp`,provider_subject_id:n,challenge_id:o.challengeId,otp_code:o.otpCode,challenge_digest:i}}async function te(e){let t=Y(),n={walletId:e.walletId,requestId:t},r=await $({context:e.context,relayUrl:e.relayUrl,request:{operation:`recovery_status`,payload:n}});return await _({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,factorProof:r})}async function ne(e){let t=Y(),n={walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs},r=await $({context:e.context,relayUrl:e.relayUrl,request:{operation:`recovery_backup_acknowledge`,payload:n}});return await y({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:r})}export{X as a,_ as c,te as i,h as l,Z as n,Q as o,$ as r,V as s,ne as t,x as u};
|
|
1
|
+
import{o as e,u as t}from"./participants-BXdREC5k.js";import{r as n}from"./base64-BmKR3UqU.js";import{r,t as i}from"./secureRandomId-8LSc91aN.js";import{o as a}from"./signerSlot-BlijMq8C.js";import{t as o}from"./indexedDB-BqsYXybq.js";import{n as s,s as c,t as l,u}from"./helpers-B7c1zc7h.js";import{i as ee}from"./pendingWalletRecoveryCodeBackup-8iMhQU-E.js";import{t as d}from"./walletOwnerOperation-BJPxzo-k.js";import{t as f}from"./webauthnPromptCoordinator-npsSRD51.js";import{i as p}from"./collectAuthenticationCredentialForChallengeB64u-BoFVpdRS.js";function m(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===5&&n.every(e=>[`ok`,`challengeId`,`challenge_digest`,`expiresAtMs`,`otpChannel`].includes(e))&&t.get(`ok`)===!0)return{kind:`success`,challengeId:t.get(`challengeId`),challengeDigest:t.get(`challenge_digest`),expiresAtMs:t.get(`expiresAtMs`),otpChannel:t.get(`otpChannel`)};let r=[`ok`,`code`,`message`,`retryAfterMs`];if((t.size===3||t.size===4)&&n.every(e=>r.includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`&&typeof t.get(`message`)==`string`&&(t.size===3||typeof t.get(`retryAfterMs`)==`number`)){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function h(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/custody/email-otp/challenge`,body:{walletId:e.walletId,providerSubjectId:e.providerSubjectId,operation:e.operation,payload:e.payload,...e.requestOrigin?{requestOrigin:e.requestOrigin}:{}},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`Email OTP challenge request failed`}}let n=m(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status!==200||n.kind!==`success`)return{kind:t.status>=400&&t.status<500?`rejected`:`transport_failed`,message:r||`Email OTP challenge failed (HTTP ${t.status})`};let i=typeof n.challengeId==`string`?n.challengeId.trim():``,a=typeof n.challengeDigest==`string`?n.challengeDigest.trim():``,o=Number(n.expiresAtMs),s=typeof n.otpChannel==`string`?n.otpChannel.trim():``;return!i||!a||!Number.isSafeInteger(o)||o<=0||!s?{kind:`transport_failed`,message:`Email OTP challenge returned an unusable payload`}:{kind:`ready`,challengeId:i,challenge_digest:a,expiresAtMs:o,otpChannel:s}}function g(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[`ok`,`activeCodeCount`,`totalCodeCount`,`issuedAtMs`,`storeVersion`,`backupOutstanding`],r=[...t.keys()];if(t.size===n.length&&r.every(e=>n.includes(e))&&t.get(`ok`)===!0)return{kind:`success`,activeCodeCount:t.get(`activeCodeCount`),totalCodeCount:t.get(`totalCodeCount`),issuedAtMs:t.get(`issuedAtMs`),storeVersion:t.get(`storeVersion`),backupOutstanding:t.get(`backupOutstanding`)};let i=[`ok`,`code`,`message`];if(t.size===i.length&&r.every(e=>i.includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function _(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/${encodeURIComponent(e.walletId)}/recovery/status`,body:{requestId:e.requestId,factorProof:e.factorProof},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`recovery status request failed`}}let n=g(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===401||t.status===403)return{kind:`unauthorized`,message:r||`recovery status is unauthorized`};if(t.status===404)return{kind:`no_recovery_set`,message:r||`this wallet has no recovery set`};if(t.status!==200)return{kind:`transport_failed`,message:r||`recovery status failed (HTTP ${t.status})`};if(n.kind!==`success`)return{kind:`transport_failed`,message:`recovery status returned an unusable payload`};let i=Number(n.activeCodeCount),a=Number(n.totalCodeCount),o=Number(n.issuedAtMs),s=typeof n.storeVersion==`string`?n.storeVersion.trim():``;return!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<i||!Number.isSafeInteger(o)||o<=0||!s||typeof n.backupOutstanding!=`boolean`?{kind:`transport_failed`,message:`recovery status returned an unusable payload`}:{kind:`ready`,walletId:e.walletId,activeCodeCount:i,totalCodeCount:a,issuedAtMs:o,storeVersion:s,backupOutstanding:n.backupOutstanding,pendingLocalBackup:!1}}function v(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===2&&n.includes(`ok`)&&n.includes(`issuedAtMs`)&&t.get(`ok`)===!0)return{kind:`success`,issuedAtMs:t.get(`issuedAtMs`)};if(t.size===3&&n.includes(`ok`)&&n.includes(`code`)&&n.includes(`message`)&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function y(e){let t;try{t=await S({relayUrl:e.relayUrl,path:`/wallets/recovery/acknowledge-backup`,body:{walletId:e.walletId,requestId:e.requestId,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:e.factorProof},fetchImpl:e.fetchImpl})}catch(e){return{kind:`transport_failed`,message:e instanceof Error?e.message:`recovery backup acknowledgement failed`}}let n=v(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===401||t.status===403)return{kind:`unauthorized`,message:r||`recovery backup acknowledgement is unauthorized`};if(t.status===404)return{kind:`no_recovery_set`,message:r||`this wallet has no recovery set`};if(t.status===409)return{kind:`conflict`,message:r||`Recovery codes changed. Check status and review the current set.`};if(t.status!==200)return{kind:`transport_failed`,message:r||`recovery backup acknowledgement failed (HTTP ${t.status})`};if(n.kind!==`success`)return{kind:`transport_failed`,message:`recovery backup acknowledgement returned an unusable payload`};let i=Number(n.issuedAtMs);return!Number.isSafeInteger(i)||i<=0?{kind:`transport_failed`,message:`recovery backup acknowledgement returned an unusable payload`}:{kind:`acknowledged`,walletId:e.walletId,issuedAtMs:i}}function b(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===3&&n.every(e=>[`ok`,`issuedAtMs`,`storeVersion`].includes(e))&&t.get(`ok`)===!0)return{kind:`success`,issuedAtMs:t.get(`issuedAtMs`),storeVersion:t.get(`storeVersion`)};if(t.size===3&&n.every(e=>[`ok`,`code`,`message`].includes(e))&&t.get(`ok`)===!1&&typeof t.get(`code`)==`string`){let e=t.get(`message`);return{kind:`failure`,message:typeof e==`string`&&e.trim()?e.trim():null}}return{kind:`invalid`}}async function x(e){let t=await S({relayUrl:e.relayUrl,path:`/wallets/recovery/rotate`,body:{walletId:e.walletId,expectedStoreVersion:e.expectedStoreVersion,manifestKekWraps:e.replacement.manifestKekWraps,entries:[e.replacement.entry],recoveryCodeLocators:e.recoveryCodeLocators,factorProof:e.factorProof},fetchImpl:e.fetchImpl}),n=b(await t.json().catch(()=>null)),r=n.kind===`failure`&&n.message?n.message:``;if(t.status===200&&n.kind===`success`){let e=Number(n.issuedAtMs),t=typeof n.storeVersion==`string`?n.storeVersion.trim():``;return!Number.isSafeInteger(e)||e<=0||!t?{kind:`transport_failed`,message:`rotation returned an unusable response`}:{kind:`rotated`,issuedAtMs:e,storeVersion:t}}return t.status===404?{kind:`no_recovery_set`,message:r||`no recovery set`}:t.status===409?{kind:`conflict`,message:r||`recovery set changed`}:t.status===400?{kind:`rejected`,message:r||`rotation rejected`}:{kind:`transport_failed`,message:r||`rotation failed (HTTP ${t.status})`}}async function S(n){let r=`${t(n.relayUrl)}${n.path}`;return await(n.fetchImpl||fetch)(r,e({headers:{Accept:`application/json`},body:n.body}))}var C=class extends Error{code=`wallet_origin_webauthn_unavailable`;constructor(e){super(e),this.name=`WalletOriginWebAuthnUnavailableError`}};async function w(e,t,n){let r=T(e,t);try{return e===`create`?await navigator.credentials.create({publicKey:r,...n.abortSignal?{signal:n.abortSignal}:{}}):await navigator.credentials.get({publicKey:r,...n.abortSignal?{signal:n.abortSignal}:{}})}catch(t){throw e===`create`&&(N(t)||P(t))?new C(`Wallet-origin WebAuthn registration is unavailable: ${F(t)}`):t}}function T(e,t){return e===`create`?E(t):D(t)}function E(e){return{...e,challenge:M(e.challenge),user:{...e.user,id:M(e.user.id)},excludeCredentials:e.excludeCredentials?.map(O),extensions:k(e.extensions)}}function D(e){return{...e,challenge:M(e.challenge),allowCredentials:e.allowCredentials?.map(O),extensions:k(e.extensions)}}function O(e){return{...e,id:M(e.id)}}function k(e){if(!e)return e;let t={...e},n=t.prf;if(n&&typeof n==`object`){let e={...n};if(e.eval&&typeof e.eval==`object`&&(e.eval=A(e.eval)),e.evalByCredential&&typeof e.evalByCredential==`object`){let t={};for(let[n,r]of Object.entries(e.evalByCredential))t[n]=r&&typeof r==`object`?A(r):r;e.evalByCredential=t}t.prf=e}return t}function A(e){return{...e,...j(e.first)?{first:M(e.first)}:{},...j(e.second)?{second:M(e.second)}:{}}}function j(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}function M(e){if(e instanceof ArrayBuffer)return e.slice(0);let t=e,n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice();if(e instanceof DataView)return new DataView(n.buffer);let r=Object.getPrototypeOf(e).constructor;return new r(n.buffer)}function N(e){let t=F(e);return/origin of the document is not the same as its ancestors/i.test(t)}function P(e){let t=I(e),n=F(e),r=t===`NotAllowedError`,i=/document is not focused|not focused|focus/i.test(n);return!!(r&&i)}function F(e){return String(e?.message||``)}function I(e){let t=e?.name;return typeof t==`string`?t:``}function L(e,t){return(e||t||``).toLowerCase()}function R(e){let t=n(String(e||``));if(t.length!==32)throw Error(`Invalid WebAuthn challenge: expected 32 bytes, got ${t.length}`);return t}function z(e){if(e.kind!==`wallet_registration`)throw Error(`Wallet registration challenge is unavailable`);return e.challengeB64u}function B(e){let t=a(String(e.walletId||``).trim());if(String(e.intendedUserName||``).trim()!==String(t))throw Error(`WebAuthn registration user.name must match walletId`);return{walletId:t}}var V=class{rpIdOverride;abortController;removePageAbortHandlers;removeExternalAbortListener;constructor(e){this.rpIdOverride=e}getRpId(){try{return L(this.rpIdOverride,window?.location?.hostname)}catch{return this.rpIdOverride||``}}getAuthenticationCredentialsSerializedForChallengeB64u(e){let t=`webauthn-get-${i(12,`WebAuthn get request IDs`)}`;return f.runImmediate({owner:{kind:`wallet_request`,requestId:t,operation:`authentication`},operation:this.executeAuthenticationCredential.bind(this,e)})}async executeAuthenticationCredential({subjectId:e,challengeB64u:t,allowCredentials:r=[],includeSecondPrfOutput:i=!1,cancellation:a={kind:`none`}}){this.abortController=new AbortController,this.removePageAbortHandlers=q(this.abortController),this.removeExternalAbortListener=H(this.abortController,a);let o=this.getRpId(),u={challenge:R(t),rpId:o,userVerification:`preferred`,timeout:6e4,extensions:{prf:{eval:{first:l(),second:s()}}}};r.length>0&&(u.allowCredentials=r.map(e=>({id:n(e.id),type:`public-key`,transports:e.transports})));try{let e=c({credential:await w(`get`,u,{abortSignal:this.abortController.signal}),firstPrfOutput:!0,secondPrfOutput:i});return G(e,t),e}finally{this.removePageAbortHandlers?.(),this.removePageAbortHandlers=void 0,this.removeExternalAbortListener?.(),this.removeExternalAbortListener=void 0,this.abortController=void 0}}generateRegistrationCredentialsInternal(e){switch(e.prompt.kind){case`reserved`:return f.runReserved({reservation:e.prompt.reservation,owner:e.prompt.owner,operation:this.executeRegistrationCredential.bind(this,e)});case`immediate`:return f.runImmediate({owner:{kind:`wallet_request`,requestId:e.prompt.requestId,operation:`registration`},operation:this.executeRegistrationCredential.bind(this,e)})}}async executeRegistrationCredential(e){this.abortController=new AbortController,this.removePageAbortHandlers=q(this.abortController),this.removeExternalAbortListener=H(this.abortController,e.prompt.cancellation);let t=this.getRpId(),r=B({walletId:e.walletId,intendedUserName:e.intendedUserName}),i=e.kind===`wallet_recovery`?e.recoveryRegistration:null,a=e.kind===`wallet_add_auth_method`?e.registration:null,o=i??a,c=o?.rpId??t;if(o&&c!==t)throw Error(`Wallet recovery RP ID does not match the wallet origin`);let u=o?{challenge:R(o.challengeB64u),rp:{name:`Seams Wallet`,id:c},user:{id:n(o.user.idB64u),name:o.user.name,displayName:o.user.displayName},pubKeyCredParams:o.pubKeyCredParams.map(e=>({...e})),authenticatorSelection:{...o.authenticatorSelection},timeout:o.timeoutMs,attestation:o.attestation,extensions:{prf:{eval:{first:n(o.extensions.prf.eval.firstB64u),second:n(o.extensions.prf.eval.secondB64u)}}},excludeCredentials:o.excludeCredentials.map(e=>({type:e.type,id:n(e.id)}))}:{challenge:R(z(e)),rp:{name:`WebAuthn Passkey`,id:c},user:{id:new TextEncoder().encode(K(e.walletId,e.signerSlot)),name:r.walletId,displayName:r.walletId},pubKeyCredParams:[{alg:-7,type:`public-key`},{alg:-257,type:`public-key`}],authenticatorSelection:{residentKey:`required`,userVerification:`preferred`},timeout:6e4,attestation:`none`,extensions:{prf:{eval:{first:l(),second:s()}}}};try{return await w(`create`,u,{abortSignal:this.abortController.signal})}finally{this.removePageAbortHandlers?.(),this.removePageAbortHandlers=void 0,this.removeExternalAbortListener?.(),this.removeExternalAbortListener=void 0,this.abortController=void 0}}};function H(e,t){if(t.kind===`none`)return;let n=t.signal,r=e.abort.bind(e);if(n.aborted){r();return}return n.addEventListener(`abort`,r,{once:!0}),n.removeEventListener.bind(n,`abort`,r)}function U(e){return String(e||``).trim().replace(/=+$/g,``)}function W(e){let t=String(e.response?.clientDataJSON||``).trim();if(!t)throw Error(`WebAuthn authentication response missing clientDataJSON`);let r=``;try{r=new TextDecoder().decode(n(t))}catch(e){throw Error(`WebAuthn authentication response has invalid clientDataJSON encoding: ${e instanceof Error?e.message:String(e)}`)}let i;try{i=JSON.parse(r)}catch(e){throw Error(`WebAuthn authentication response has invalid clientDataJSON JSON: ${e instanceof Error?e.message:String(e)}`)}let a=i&&typeof i==`object`?i.challenge:void 0;if(typeof a!=`string`||!a.trim())throw Error(`WebAuthn authentication response clientDataJSON missing challenge`);return a}function G(e,t){let n=U(W(e)),r=U(t);if(n!==r)throw Error(`Unexpected authentication response challenge "${n}", expected "${r}"`)}function K(e,t){return t===void 0||t===1?e:`${e} (${t})`}function q(e){let t=()=>{document.hidden&&e.abort()},n=()=>{e.abort()},r=()=>{e.abort()};return document.addEventListener(`visibilitychange`,t,{passive:!0}),window.addEventListener(`pagehide`,n,{passive:!0}),window.addEventListener(`beforeunload`,r,{passive:!0}),()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`pagehide`,n),window.removeEventListener(`beforeunload`,r)}}async function J(e){let t=e.request.payload.walletId,n=window.location.origin,r=await d({walletId:t,operation:e.request.operation,payload:e.request.payload,requestOrigin:n}),i=await p({credentialStore:o,touchIdPrompt:new V(e.rpId),walletId:t,challengeB64u:r,includeSecondPrfOutput:!1}),a=ee(i);if(!a)throw Error(`Wallet recovery proof did not receive a passkey credential`);return{kind:`passkey`,walletId:t,rpId:e.rpId,credentialIdB64u:a,challenge_digest:r,webauthn_authentication:u(i)}}function Y(){return r(`wallet-recovery-admin`,16,`wallet recovery administration request IDs`)}async function X(e){let t=Y(),n={walletId:e.walletId,requestId:t},r=await J({rpId:e.rpId,request:{operation:`recovery_status`,payload:n}});return await _({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,factorProof:r})}async function Z(e){let t=Y(),n={walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs},r=await J({rpId:e.rpId,request:{operation:`recovery_backup_acknowledge`,payload:n}});return await y({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:r})}async function Q(e){let t=await o.resolveSelectedWalletAuthority(e);if(t.kind!==`resolved`||t.selection.lockState!==`unlocked`||String(t.selection.walletId)!==e||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.kind!==`email_otp`||t.authMethod.status!==`active`||t.authority.state!==`active`||String(t.authMethod.walletId)!==e||String(t.authority.walletId)!==e)throw Error(`Unlock this wallet with its active Email OTP method`);let n=await o.listWalletAuthMethodsForWallet(e),r=null;for(let e of n)if(!(e.kind!==`email_otp`||e.status!==`active`||e.localStatus!==`synced`||String(e.authority.bindingId)!==String(t.authMethod.walletAuthMethodId))){if(r!==null)throw Error(`The selected Email OTP owner method is duplicated`);r=String(e.authority.factor.providerUserId||``).trim()}if(!r)throw Error(`The selected Email OTP owner method is unavailable on this wallet`);return{walletAuthMethodId:String(t.authMethod.walletAuthMethodId),providerSubjectId:r}}async function $(e){let t=e.request.payload.walletId,{providerSubjectId:n}=await Q(t),r=window.location.origin,i=await d({walletId:t,operation:e.request.operation,payload:e.request.payload,requestOrigin:r}),a=await h({relayUrl:e.relayUrl,walletId:t,providerSubjectId:n,operation:e.request.operation,payload:e.request.payload,requestOrigin:r});if(a.kind!==`ready`)throw Error(a.message);if(a.challenge_digest!==i)throw Error(`Recovery Email OTP challenge does not match this operation`);let o=await e.context.signingEngine.requestEmailOtpOwnerConfirmation({purpose:e.request.operation,walletId:t,emailAddress:`your email`,challengeId:a.challengeId});if(o.challengeId!==a.challengeId)throw Error(`Recovery Email OTP confirmation changed its challenge`);return{kind:`email_otp`,provider_subject_id:n,challenge_id:o.challengeId,otp_code:o.otpCode,challenge_digest:i}}async function te(e){let t=Y(),n={walletId:e.walletId,requestId:t},r=await $({context:e.context,relayUrl:e.relayUrl,request:{operation:`recovery_status`,payload:n}});return await _({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,factorProof:r})}async function ne(e){let t=Y(),n={walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs},r=await $({context:e.context,relayUrl:e.relayUrl,request:{operation:`recovery_backup_acknowledge`,payload:n}});return await y({relayUrl:e.relayUrl,walletId:e.walletId,requestId:t,expectedIssuedAtMs:e.expectedIssuedAtMs,factorProof:r})}export{X as a,_ as c,te as i,h as l,Z as n,Q as o,$ as r,V as s,ne as t,x as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,E as t,M as n,N as r,O as i,c as a,j as o,k as s,s as c}from"./domainIds-t1lp25yU.js";import{S as l,i as u,t as d,y as f}from"./digests-BIaE0DMd.js";import{o as p,u as m}from"./participants-BXdREC5k.js";import{i as h,r as g}from"./base64-BmKR3UqU.js";import{s as _}from"./walletDbName-Ca0rCq5r.js";import{D as v,E as y,G as b,H as x,J as S,M as C,N as ee,O as w,W as T,X as E,j as te,k as ne}from"./activeWalletSession-BJ4B-nJo.js";import{n as re,t as ie}from"./signingSessionSeal-BFOBKj-J.js";import{l as D}from"./capabilityKinds-DVlGMspk.js";import{d as ae,t as O}from"./accountIds-DGWFzEnw.js";import{x as k}from"./registrationIntent-C1-Kyx_-.js";import{m as oe}from"./walletAuthority-DbGaSw7D.js";import{A as se,Ct as ce,Dt as le,Et as ue,Nt as de,Pt as fe,S as pe,Tt as me,X as he,jt as ge,kt as _e,ut as ve,wt as ye,xt as be}from"./digestEncoding-34kXJoJr.js";import{i as xe}from"./walletAuthMethodRecord-BW-XV4fv.js";import{C as Se}from"./ecdsaCapabilityManifest--1Ztngfx.js";import{O as Ce,_ as A,g as we,h as Te,t as j,y as M}from"./indexedDB-CA4tGqkr.js";import{r as Ee}from"./walletCustodyEcdsaContinuity-BnyL1Ryu.js";import{o as De}from"./helpers-B7c1zc7h.js";import{P as Oe,h as ke,m as Ae}from"./accountLifecycle-B5a9SCM7.js";import{a as je,n as N,t as Me}from"./wallet-recovery-DXdm68_Q.js";import{n as Ne}from"./challengeDelivery-Dj9HrjW9.js";function Pe(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`wallet recovery target must be an object`);let t=e,n=Object.keys(t);switch(t.kind){case`passkey`:{if(n.length!==2||!n.includes(`rpId`))throw Error(`Passkey recovery target fields are invalid`);let e=r(t.rpId);if(!e.ok)throw Error(`Passkey recovery target RP ID is invalid`);return{kind:`passkey`,rpId:e.value}}case`google_email_otp`:if(n.length!==2||!n.includes(`googleProvider`)||t.googleProvider!==`google`)throw Error(`Google Email OTP recovery target fields are invalid`);return{kind:`google_email_otp`,googleProvider:`google`};default:throw Error(`wallet recovery target kind is unsupported`)}}const Fe=[`ok`,`walletId`,`target`,`recoveryOperationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`wrap`,`entries`,`keyManifest`,`reservationId`,`reservationExpiresAtMs`,`storeVersion`],Ie=[...Fe,`registration`];function P(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Le(e,t,n){let r=new Set(t),i=Object.keys(e);if(i.length!==r.size||i.some(e=>!r.has(e)))throw Error(`${n} contains unexpected fields`)}function F(e,t,n){let r=P(e,n);return Le(r,t,n),r}function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)?Reflect.get(e,t):void 0}function Re(e){try{return P(e,`walletRecoveryPrepare response`)}catch{return null}}function ze(e){let t=s(e.walletId);if(!t.ok)throw Error(`wallet recovery ${t.error.message}`);return JSON.stringify({walletId:String(t.value),wrap:e.prepared.wrap,entry:e.prepared.entries[0]})}async function Be(e){let t=await Ve(e);return t.ok?await He({response:t.response,target:e.target,reservationId:e.reservationId}):{kind:t.kind}}async function Ve(e){let t=`${m(e.relayUrl)}/wallets/recovery/prepare`,n=e.fetchImpl||fetch;try{return{ok:!0,response:await n(t,p({body:{recoveryCodeB64u:e.recoveryCodeB64u,reservationId:e.reservationId,target:e.target}}))}}catch{return{ok:!1,kind:`transport_uncertain`}}}async function He(e){let n=e.response,r=Re(await n.json().catch(()=>({})));if(n.status===200&&r&&I(r,`ok`)===!0)try{let n=F(r,e.target.kind===`passkey`?Ie:Fe,`walletRecoveryPrepare`),a=Je()(I(n,`wrap`),`walletRecoveryPrepare.wrap`),c=Ye(I(n,`entries`)),l=s(I(n,`walletId`));if(!l.ok)throw Error(`walletRecoveryPrepare.walletId is invalid`);let u=l.value,d=Pe(I(n,`target`));if(!Ke(d,e.target))throw Error(`wallet recovery preparation changed the recovery target`);let f=o(I(n,`recoveryOperationId`)),p=D(I(n,`targetDeviceId`)),m=i(I(n,`targetAuthorityId`)),h=t(I(n,`targetWalletAuthMethodId`));if(!f.ok||!p.ok||!m.ok||!h.ok)throw Error(`wallet recovery preparation target identity is invalid`);let g=Xe(I(n,`keyManifest`),u),_=M(I(n,`reservationId`)),v=ee(I(n,`reservationExpiresAtMs`),`walletRecoveryPrepare.reservationExpiresAtMs`),y=L(I(n,`storeVersion`),`storeVersion`);if(_!==e.reservationId)throw Error(`wallet recovery preparation changed the reservation identity`);let b={kind:`prepared`,walletId:u,recoveryOperationId:f.value,targetDeviceId:p.value,targetAuthorityId:m.value,targetWalletAuthMethodId:h.value,wrap:a,entries:c,keyManifest:g,reservationId:_,reservationExpiresAtMs:v,storeVersion:y};switch(d.kind){case`passkey`:{let e=Ue(String(u),d.rpId)(I(n,`registration`),`registration`);if(e.walletAuthMethodId!==h.value)throw Error(`wallet recovery registration changed the target auth method`);return{...b,target:d,registration:e}}case`google_email_otp`:if(Object.prototype.hasOwnProperty.call(n,`registration`))throw Error(`Google Email OTP recovery cannot carry passkey registration`);return{...b,target:d};default:return qe(d)}}catch{return{kind:`transport_uncertain`}}return n.status===409?{kind:`retryable_conflict`}:n.status===401&&r&&I(r,`code`)===`recovery_code_used`?{kind:`consumed`}:n.status===401||n.status===400?{kind:`refused`}:{kind:`transport_uncertain`}}function Ue(e,i){let a=h(new TextEncoder().encode(e)),o=T({type:x(`public-key`),id:(e,t)=>{let r=b(n)(e,t);return ct(r,t),r}});return T({kind:x(`webauthn_recovery_registration_v1`),challengeId:L,challengeB64u:(e,t)=>st(e,32,t),replacementId:L,walletAuthMethodId:b(t),rpId:b(r),user:T({idB64u:ct,name:L,displayName:L},(t,n)=>{if(t.idB64u!==a||t.name!==e||t.displayName!==e)throw Error(`${n} is bound to another wallet`)}),pubKeyCredParams:(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw Error(`${t} is invalid`);return[We(-7)(e[0],`${t}[0]`),We(-257)(e[1],`${t}[1]`)]},authenticatorSelection:T({residentKey:x(`required`),userVerification:x(`preferred`)}),timeoutMs:(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} is invalid`);return n},attestation:x(`none`),extensions:T({prf:T({eval:T({firstB64u:Ge(ie),secondB64u:Ge(re)})})}),excludeCredentials:(e,t)=>f(e,t).map((e,n)=>o(e,`${t}[${n}]`))},(e,t)=>{if(e.rpId!==i)throw Error(`${t} changed the relying party`)})}function We(e){return T({type:x(`public-key`),alg:(t,n)=>{if(t!==e)throw Error(`${n} is invalid`);return e}})}function Ge(e){return(t,n)=>{let r=st(t,e.length,n);if(r!==h(e))throw Error(`${n} is unsupported`);return r}}function Ke(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId;case`google_email_otp`:return t.kind===`google_email_otp`&&e.googleProvider===t.googleProvider;default:return qe(e)}}function qe(e){throw Error(`unsupported wallet recovery target: ${String(e)}`)}function Je(){return T({nonceB64u:ne,wrappedManifestKekB64u:w,aadHashB64u:y})}function Ye(e){if(!Array.isArray(e)||e.length!==1)throw Error(`walletRecoveryPrepare.entries must contain exactly one custody seed`);return[je(e[0],`walletRecoveryPrepare.entries[0]`)]}function L(e,t){if(typeof e!=`string`||!e.trim())throw Error(`walletRecoveryPrepare.${t} must be a non-empty string`);return e.trim()}function Xe(e,t){let n=F(e,[`version`,`walletId`,`entries`],`walletRecoveryPrepare.keyManifest`);if(I(n,`version`)!==`wallet_recovery_preparation_key_manifest_v1`)throw Error(`walletRecoveryPrepare.keyManifest version is invalid`);let r=L(I(n,`walletId`),`keyManifest.walletId`);if(r!==t)throw Error(`walletRecoveryPrepare.keyManifest changed the wallet identity`);let i=I(n,`entries`);if(!Array.isArray(i)||i.length===0)throw Error(`walletRecoveryPrepare.keyManifest must contain a key set`);let a=i.map(e=>Ze(e,r));if(new Set(a.map(e=>e.keySetId)).size!==a.length)throw Error(`walletRecoveryPrepare.keyManifest contains duplicate key sets`);return{version:`wallet_recovery_preparation_key_manifest_v1`,walletId:r,entries:a}}function Ze(e,t){switch(I(P(e,`walletRecoveryPrepare.keyManifest.entries[]`),`kind`)){case`near_ed25519`:{let n=F(e,[`kind`,`keySetId`,`signerId`,`nearAccountId`,`recordedKeyManifestDigestB64u`,`recoveryBasis`],`walletRecoveryPrepare.keyManifest.entries[].near_ed25519`),r=L(I(n,`signerId`),`keyManifest.entries[].signerId`),i=L(I(n,`keySetId`),`keyManifest.entries[].keySetId`),a=`near_ed25519:${r}`;if(i!==a)throw Error(`walletRecoveryPrepare NEAR key-set identity is inconsistent`);let o=L(I(n,`nearAccountId`),`keyManifest.entries[].nearAccountId`),s=Qe(I(n,`recoveryBasis`),t);return{kind:`near_ed25519`,keySetId:a,signerId:r,nearAccountId:o,recordedKeyManifestDigestB64u:y(I(n,`recordedKeyManifestDigestB64u`),`walletRecoveryPrepare.keyManifest.entries[].recordedKeyManifestDigestB64u`),recoveryBasis:s}}case`evm_family_ecdsa`:{let n=F(e,[`kind`,`keySetId`,`keyHandle`,`evmFamilySigningKeySlotId`,`recordedKeyManifestDigestB64u`,`recoveryBasis`],`walletRecoveryPrepare.keyManifest.entries[].evm_family_ecdsa`),r=L(I(n,`keyHandle`),`keyManifest.entries[].keyHandle`),i=L(I(n,`keySetId`),`keyManifest.entries[].keySetId`),a=`evm_family_ecdsa:${r}`;if(i!==a)throw Error(`walletRecoveryPrepare ECDSA key-set identity is inconsistent`);let o=$e(I(n,`recoveryBasis`),t);return{kind:`evm_family_ecdsa`,keySetId:a,keyHandle:r,evmFamilySigningKeySlotId:_e(I(n,`evmFamilySigningKeySlotId`)),recordedKeyManifestDigestB64u:y(I(n,`recordedKeyManifestDigestB64u`),`walletRecoveryPrepare.keyManifest.entries[].recordedKeyManifestDigestB64u`),recoveryBasis:o}}default:throw Error(`walletRecoveryPrepare key-manifest entry kind is invalid`)}}function Qe(e,t){let n=F(e,[`capabilityKind`,`activeCapabilityBinding`,`scope`,`applicationBinding`,`participantIds`,`registeredPublicKey`,`runtimePolicyScope`,`activationTranscript`,`activationStateEpoch`,`signingWorkerVerifyingShare`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis`),r=I(n,`capabilityKind`);if(r!==`registration`&&r!==`recovery`)throw Error(`walletRecoveryPrepare NEAR recovery capability kind is invalid`);let i=R(I(n,`activeCapabilityBinding`),32,`NEAR recovery active capability binding`),a=rt(I(n,`scope`)),o=it(I(n,`applicationBinding`)),s=ot(I(n,`participantIds`),`NEAR recovery participant IDs`),c=R(I(n,`registeredPublicKey`),32,`NEAR recovery registered public key`),l=at(I(n,`runtimePolicyScope`)),u=R(I(n,`activationTranscript`),32,`NEAR recovery activation transcript`),d=Number(I(n,`activationStateEpoch`));if(!Number.isSafeInteger(d)||d<=0)throw Error(`walletRecoveryPrepare NEAR recovery activation state epoch is invalid`);let f=R(I(n,`signingWorkerVerifyingShare`),32,`NEAR recovery signing-worker verifying share`);if(o.wallet_id!==t||a.account_id!==t||a.root_share_epoch!==l.signingRootVersion)throw Error(`walletRecoveryPrepare NEAR recovery basis changed its wallet scope`);return{capabilityKind:r,activeCapabilityBinding:i,scope:a,applicationBinding:o,participantIds:s,registeredPublicKey:c,runtimePolicyScope:l,activationTranscript:u,activationStateEpoch:d,signingWorkerVerifyingShare:f}}function $e(e,t){let n=F(e,[`publicCapability`,`activationReceipt`,`serverGeneration`,`clientRootPublicKey33B64u`,`chainTargets`,`ecdsaThresholdKeyId`,`signingRootId`,`signingRootVersion`,`runtimePolicyScope`,`participantIds`,`possessionChallenge`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis`),r=pe(I(n,`publicCapability`)),i=se(I(n,`activationReceipt`));if(r.client_id!==t)throw Error(`walletRecoveryPrepare ECDSA recovery capability changed the wallet scope`);let a=me(I(n,`signingRootId`)),o=ue(I(n,`signingRootVersion`)),s=at(I(n,`runtimePolicyScope`));if(s.signingRootVersion!==o)throw Error(`walletRecoveryPrepare ECDSA recovery scope changed the signing root`);let c=be(I(n,`serverGeneration`));if(String(i.server_generation)!==String(c))throw Error(`walletRecoveryPrepare ECDSA activation receipt changed server generation`);let l=Me(I(n,`possessionChallenge`));if(l.walletId!==t||l.expectedServerGeneration!==String(c)||l.derivationClientSharePublicKey33B64u!==r.public_identity.derivation_client_share_public_key33_b64u)throw Error(`walletRecoveryPrepare ECDSA possession challenge changed its capability`);return{publicCapability:r,activationReceipt:i,serverGeneration:c,clientRootPublicKey33B64u:ye(L(I(n,`clientRootPublicKey33B64u`),`keyManifest.entries[].recoveryBasis.clientRootPublicKey33B64u`)),chainTargets:et(I(n,`chainTargets`)),ecdsaThresholdKeyId:le(I(n,`ecdsaThresholdKeyId`)),signingRootId:a,signingRootVersion:o,runtimePolicyScope:s,participantIds:nt(I(n,`participantIds`)),possessionChallenge:l}}function et(e){if(!Array.isArray(e)||e.length===0)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are invalid`);let t=e.map((e,t)=>tt(e,t));if(new Set(t.map(Ce)).size!==t.length)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are duplicated`);let n=t[0];if(!n)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are invalid`);return[n,...t.slice(1)]}function tt(e,t){let n=`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.chainTargets[${t}]`,r=P(e,n),i=I(r,`kind`);Le(r,i===`evm`?[`kind`,`namespace`,`chainId`,`networkSlug`]:[`kind`,`chainId`,`networkSlug`],n);let a=I(r,`namespace`),o=Number(I(r,`chainId`));if(!Number.isSafeInteger(o)||o<=0)throw Error(`walletRecoveryPrepare ECDSA recovery chain id is invalid`);let s=I(r,`networkSlug`),c=typeof s==`string`&&s.trim()?s.trim():null;if(i===`evm`){if(a!==`eip155`)throw Error(`walletRecoveryPrepare ECDSA recovery EVM namespace is invalid`);return{kind:`evm`,namespace:`eip155`,chainId:o,networkSlug:c??`evm-${o}`}}if(i===`tempo`)return{kind:`tempo`,chainId:o,networkSlug:c??`tempo-${o}`};throw Error(`walletRecoveryPrepare ECDSA recovery chain family is invalid`)}function nt(e){if(!Array.isArray(e)||e.length!==2||e[0]!==1||e[1]!==2)throw Error(`walletRecoveryPrepare ECDSA recovery participant IDs are invalid`);return[1,2]}function rt(e){let t=F(e,[`lifecycle_id`,`root_share_epoch`,`account_id`,`threshold_session_id`,`signer_set_id`,`signing_worker_id`,`material_activation`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.scope`);return{lifecycle_id:L(I(t,`lifecycle_id`),`keyManifest.entries[].recoveryBasis.scope.lifecycle_id`),root_share_epoch:L(I(t,`root_share_epoch`),`keyManifest.entries[].recoveryBasis.scope.root_share_epoch`),account_id:L(I(t,`account_id`),`keyManifest.entries[].recoveryBasis.scope.account_id`),threshold_session_id:L(I(t,`threshold_session_id`),`keyManifest.entries[].recoveryBasis.scope.threshold_session_id`),signer_set_id:L(I(t,`signer_set_id`),`keyManifest.entries[].recoveryBasis.scope.signer_set_id`),signing_worker_id:L(I(t,`signing_worker_id`),`keyManifest.entries[].recoveryBasis.scope.signing_worker_id`),material_activation:ge(I(t,`material_activation`))}}function it(e){let t=F(e,[`wallet_id`,`near_ed25519_signing_key_id`,`signing_root_id`,`key_creation_signer_slot`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.applicationBinding`),n=Number(I(t,`key_creation_signer_slot`));if(!Number.isSafeInteger(n)||n<=0)throw Error(`walletRecoveryPrepare NEAR recovery key-creation signer slot is invalid`);return{wallet_id:L(I(t,`wallet_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.wallet_id`),near_ed25519_signing_key_id:L(I(t,`near_ed25519_signing_key_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.near_ed25519_signing_key_id`),signing_root_id:L(I(t,`signing_root_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.signing_root_id`),key_creation_signer_slot:n}}function at(e){let t=F(e,[`orgId`,`projectId`,`envId`,`signingRootVersion`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.runtimePolicyScope`);try{return E(t)}catch{throw Error(`walletRecoveryPrepare NEAR recovery runtime policy scope is invalid`)}}function ot(e,t){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||Number(e[0])<=0||Number(e[1])<=0||Number(e[0])===Number(e[1]))throw Error(`walletRecoveryPrepare ${t} is invalid`);return[Number(e[0]),Number(e[1])]}function st(e,t,n){let r=L(e,n),i=g(r);if(i.length!==t||h(i)!==r)throw Error(`walletRecoveryPrepare ${n} is invalid`);return r}function ct(e,t){let n=L(e,t),r=g(n);if(r.length===0||h(r)!==n)throw Error(`walletRecoveryPrepare ${t} is invalid`);return n}function R(e,t,n){if(!Array.isArray(e)||e.length!==t||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`walletRecoveryPrepare ${n} is invalid`);return e.map(Number)}const lt=`/wallets/recovery/finalize`;async function ut(e){let t=`${m(e.relayUrl)}${lt}`,n=e.fetchImpl||fetch,r;try{r=De(e.webauthnRegistration)}catch{return{kind:`refused`}}let i;try{let t=new Set;i=e.ecdsaMaterialPossessionProofs.map(e=>{if(typeof e.keySetId!=`string`||!e.keySetId.startsWith(`evm_family_ecdsa:`)||e.keySetId.length<=17)throw Error(`ECDSA possession proof key-set id is invalid`);if(t.has(e.keySetId))throw Error(`ECDSA possession proof key-set ids are duplicated`);return t.add(e.keySetId),{keySetId:e.keySetId,proof:N(e.proof)}})}catch{return{kind:`refused`}}let a;try{if(a=k(e.replacementEnvelope,`walletRecoveryFinalize.replacementEnvelope`),String(a.walletId)!==String(e.walletId))throw Error(`replacement envelope changed the wallet identity`);if(String(a.envelopeId)!==String(e.replacementId))throw Error(`replacement envelope changed the replacement identity`);if(a.factor.kind!==`passkey`)throw Error(`replacement envelope is not bound to a passkey`)}catch{return{kind:`refused`}}let o;try{o=await n(t,p({body:{kind:`finalize`,walletId:e.walletId,reservationId:e.reservationId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,challengeId:e.challengeId,replacementId:e.replacementId,webauthnRegistration:r,replacementEnvelope:a,ecdsaMaterialPossessionProofs:i}}))}catch{return{kind:`transport_uncertain`}}let s=ft(await o.json().catch(()=>({})));if(o.status===200&&s.kind===`success`)try{let t=await A(s.projection,pt(e,a));if(t.kind!==`passkey`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:t.storeVersion,authority:t.authority,authMethod:t.authMethod}}catch{return{kind:`transport_uncertain`}}return o.status===409?{kind:`retryable_conflict`}:o.status===400||o.status===401?{kind:`refused`}:{kind:`transport_uncertain`}}async function dt(e){let t;try{if(t=k(e.replacementEnvelope,`walletRecoveryReplay.replacementEnvelope`),String(t.walletId)!==String(e.walletId)||String(t.envelopeId)!==String(e.replacementId)||t.factor.kind!==`passkey`)throw Error(`recovery replay envelope identity is invalid`)}catch{return{kind:`refused`}}let n;try{n=await(e.fetchImpl??fetch)(`${m(e.relayUrl)}${lt}`,p({body:{kind:`replay`,walletId:e.walletId,reservationId:e.reservationId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,replacementId:e.replacementId,replacementEnvelope:t}}))}catch{return{kind:`transport_uncertain`}}let r=ft(await n.json().catch(()=>({})));if(n.status===200&&r.kind===`success`)try{let n=await A(r.projection,pt(e,t));if(n.kind!==`passkey`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:n.storeVersion,authority:n.authority,authMethod:n.authMethod}}catch{return{kind:`transport_uncertain`}}return n.status===409?{kind:`retryable_conflict`}:n.status===400||n.status===401?{kind:`refused`}:{kind:`transport_uncertain`}}function ft(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===2&&n.includes(`ok`)&&n.includes(`projection`)&&t.get(`ok`)===!0)return{kind:`success`,projection:t.get(`projection`)};let r=t.get(`code`),i=t.get(`message`);return t.size===3&&n.includes(`ok`)&&n.includes(`code`)&&n.includes(`message`)&&t.get(`ok`)===!1&&typeof r==`string`&&typeof i==`string`?{kind:`failure`,code:r,message:i}:{kind:`invalid`}}function pt(e,n){if(n.factor.kind!==`passkey`)throw Error(`replacement envelope is not a passkey envelope`);return{kind:`passkey`,walletId:z(s(e.walletId)),recoveryOperationId:z(o(e.recoveryOperationId)),targetDeviceId:z(D(e.targetDeviceId)),targetAuthorityId:z(i(e.targetAuthorityId)),targetWalletAuthMethodId:z(t(e.targetWalletAuthMethodId)),rpId:n.factor.rpId,credentialIdB64u:n.factor.credentialIdB64u}}function z(e){if(!e.ok)throw Error(`invalid recovery identity`);return e.value}function B(e){return e.target.kind===`passkey`}function mt(e){return{kind:`email_otp_enrollment_reference_v1`,enrollmentId:e.enrollment.enrollmentId,enrollmentSealKeyVersion:e.enrollment.kind===`existing`?e.enrollment.enrollmentSealKeyVersion:e.enrollment.material.enrollmentSealKeyVersion}}const ht=[`kind`,`keySetId`,`applicationBindingDigestB64u`,`registeredPublicKeyB64u`,`participantIds`,`stateEpoch`,`signingWorkerVerifyingShareB64u`,`materialActivation`,`sealed`],gt=[`kind`,`keySetId`,`possessionProof`,`readyStateBlobB64u`,`publicFacts`],_t=[`contextBinding32B64u`,`derivationClientSharePublicKey33B64u`,`clientVerifyingShare33B64u`,`relayerPublicKey33B64u`,`groupPublicKey33B64u`,`ethereumAddress`,`clientShareRetryCounter`,`relayerShareRetryCounter`],vt=[`kind`,`version`,`recoveryOperationId`,`walletId`,`reservationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`replacementEnvelope`,`keyManifest`,`nearKeySets`,`ecdsaKeySets`,`target`];function V(e,t,n){if(S(e,t,n),Object.keys(e).length!==t.length)throw Error(n+` fields are invalid`)}function H(e,t){if(typeof e!=`string`||!e||e.trim()!==e)throw Error(t+` must be a non-empty canonical string`);return e}function U(e,t,n){let r=H(e,t),i=g(r);if(n!==void 0&&i.byteLength!==n)throw Error(t+` must decode to `+n+` bytes`);return r}function yt(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(t+` must be a non-negative safe integer`);return e}function bt(e,t){if(!Array.isArray(e)||e.length!==2||e.some(xt))throw Error(t+` must contain two positive participant IDs`);return[e[0],e[1]]}function xt(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<1}function St(e,t){let n=H(l(t,`recovery durable NEAR key set`).keySetId,`recovery durable NEAR keySetId`),r=e.entries.find(e=>e.keySetId===n);if(!r||r.kind!==`near_ed25519`)throw Error(`recovery durable NEAR key-set manifest entry is invalid`);return r}function Ct(e,t){let n=H(l(t,`recovery durable ECDSA key set`).keySetId,`recovery durable ECDSA keySetId`),r=e.entries.find(e=>e.keySetId===n);if(!r||r.kind!==`evm_family_ecdsa`)throw Error(`recovery durable ECDSA key-set manifest entry is invalid`);return r}function wt(e){let t=_(e);if(!t)throw Error(`recovery runtime policy scope is invalid`);return t}function Tt(t,n){let r=l(t,`recovery durable NEAR key set`);if(V(r,ht,`recovery durable NEAR key set`),r.kind!==`near_ed25519`||r.keySetId!==n.keySetId)throw Error(`recovery durable NEAR key-set identity is invalid`);let i=n.recoveryBasis,a=i.scope.threshold_session_id;if(!e(a).ok)throw Error(`recovery durable NEAR thresholdSessionId is invalid`);let o={kind:Oe,applicationBindingDigestB64u:y(r.applicationBindingDigestB64u,`recovery durable NEAR application binding digest`),registeredPublicKeyB64u:v(r.registeredPublicKeyB64u,`recovery durable NEAR registered public key`),participantIds:bt(r.participantIds,`recovery durable NEAR participantIds`),stateEpoch:H(r.stateEpoch,`recovery durable NEAR stateEpoch`),walletId:i.applicationBinding.wallet_id,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:i.applicationBinding.near_ed25519_signing_key_id,signerSlot:te(i.applicationBinding.key_creation_signer_slot,`recovery durable NEAR signerSlot`),signingWorkerId:i.scope.signing_worker_id,signingWorkerVerifyingShareB64u:v(r.signingWorkerVerifyingShareB64u,`recovery durable NEAR signing-worker verifying share`)},s=l(r.sealed,`recovery durable NEAR sealed material`);return V(s,[`ciphertextB64u`,`nonceB64u`],`recovery durable NEAR sealed material`),{kind:`near_ed25519`,keySetId:n.keySetId,binding:o,thresholdSessionId:a,runtimePolicyScope:wt(i.runtimePolicyScope),materialActivation:ge(r.materialActivation),sealed:{ciphertextB64u:w(s.ciphertextB64u,`recovery durable NEAR ciphertext`),nonceB64u:ne(s.nonceB64u,`recovery durable NEAR nonce`)}}}function Et(e){let t=l(e,`recovery durable ECDSA public facts`);V(t,_t,`recovery durable ECDSA public facts`);let n=H(t.ethereumAddress,`recovery durable ECDSA ethereumAddress`).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw Error(`recovery durable ECDSA ethereumAddress is invalid`);return{contextBinding32B64u:y(t.contextBinding32B64u,`recovery durable ECDSA context binding`),derivationClientSharePublicKey33B64u:C(t.derivationClientSharePublicKey33B64u,`recovery durable ECDSA client share`),clientVerifyingShare33B64u:C(t.clientVerifyingShare33B64u,`recovery durable ECDSA client verifying share`),relayerPublicKey33B64u:C(t.relayerPublicKey33B64u,`recovery durable ECDSA relayer public key`),groupPublicKey33B64u:C(t.groupPublicKey33B64u,`recovery durable ECDSA group public key`),ethereumAddress:n,clientShareRetryCounter:yt(t.clientShareRetryCounter,`recovery durable ECDSA client-share retry counter`),relayerShareRetryCounter:yt(t.relayerShareRetryCounter,`recovery durable ECDSA relayer-share retry counter`)}}function Dt(e,t){let n=l(e,`recovery durable ECDSA key set`);if(V(n,gt,`recovery durable ECDSA key set`),n.kind!==`evm_family_ecdsa`||n.keySetId!==t.keySetId)throw Error(`recovery durable ECDSA key-set identity is invalid`);return{kind:`evm_family_ecdsa`,entry:t,possessionProof:N(n.possessionProof),readyStateBlobB64u:U(n.readyStateBlobB64u,`recovery durable ECDSA ready-state blob`),publicFacts:Et(n.publicFacts)}}function Ot(e){let t=l(e,`recovery durable registration`);if(V(t,[`kind`,`id`,`rawId`,`type`,`authenticatorAttachment`,`response`],`recovery durable registration`),t.kind!==`wallet_recovery_redacted_registration_v1`)throw Error(`recovery durable registration kind is invalid`);if(t.authenticatorAttachment!==null&&typeof t.authenticatorAttachment!=`string`)throw Error(`recovery durable registration authenticatorAttachment is invalid`);let n=l(t.response,`recovery durable registration response`);if(V(n,[`clientDataJSON`,`attestationObject`,`transports`],`recovery durable registration response`),!Array.isArray(n.transports))throw Error(`recovery durable registration transports are invalid`);return{kind:`wallet_recovery_redacted_registration_v1`,id:H(t.id,`recovery durable registration id`),rawId:U(t.rawId,`recovery durable registration rawId`),type:H(t.type,`recovery durable registration type`),authenticatorAttachment:t.authenticatorAttachment,response:{clientDataJSON:U(n.clientDataJSON,`recovery durable registration clientDataJSON`),attestationObject:U(n.attestationObject,`recovery durable registration attestationObject`),transports:n.transports.map((e,t)=>H(e,`recovery durable registration transports[`+t+`]`))}}}function kt(e){let t=l(e,`recovery durable Email OTP enrollment`);if(t.kind===`existing`)return V(t,[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`],`recovery durable existing Email OTP enrollment`),{kind:`existing`,enrollmentId:H(t.enrollmentId,`recovery enrollmentId`),enrollmentSealKeyVersion:H(t.enrollmentSealKeyVersion,`recovery enrollment seal-key version`)};if(t.kind!==`create`)throw Error(`recovery durable Email OTP enrollment kind is invalid`);V(t,[`kind`,`enrollmentId`,`providerSubject`,`verifiedEmail`,`material`],`recovery durable create Email OTP enrollment`);let n=l(t.material,`recovery durable enrollment material`);return V(n,[`enrollmentSealKeyVersion`,`clientUnlockPublicKeyB64u`,`unlockKeyVersion`,`serverSealedFactorCiphertextB64u`],`recovery durable enrollment material`),{kind:`create`,enrollmentId:H(t.enrollmentId,`recovery enrollmentId`),providerSubject:H(t.providerSubject,`recovery enrollment providerSubject`),verifiedEmail:H(t.verifiedEmail,`recovery enrollment verifiedEmail`),material:{enrollmentSealKeyVersion:H(n.enrollmentSealKeyVersion,`recovery enrollment material seal-key version`),clientUnlockPublicKeyB64u:U(n.clientUnlockPublicKeyB64u,`recovery enrollment client unlock public key`),unlockKeyVersion:H(n.unlockKeyVersion,`recovery enrollment unlock-key version`),serverSealedFactorCiphertextB64u:U(n.serverSealedFactorCiphertextB64u,`recovery enrollment sealed factor ciphertext`)}}}function W(e){let n=l(e,`wallet recovery durable payload`);if(n.kind!==`wallet_recovery_durable_payload_v1`||n.version!==1)throw Error(`wallet recovery durable payload version is invalid`);V(n,[...vt,...l(n.target,`wallet recovery durable target`).kind===`passkey`?[`replacementId`,`challengeId`,`registration`]:[`providerSubject`,`verifiedEmail`,`emailHashHex`,`registrationAuthorityId`,`replacementId`,`enrollment`]],`wallet recovery durable payload`);let c=o(n.recoveryOperationId),u=s(n.walletId),d;try{d=M(n.reservationId)}catch(e){throw Error(`wallet recovery durable reservationId is invalid`,{cause:e})}let f=D(n.targetDeviceId),p=i(n.targetAuthorityId),m=t(n.targetWalletAuthMethodId);if(!c.ok||!u.ok||!f.ok||!p.ok||!m.ok)throw Error(`wallet recovery durable payload identity is invalid`);if(!Array.isArray(n.nearKeySets)||!Array.isArray(n.ecdsaKeySets))throw Error(`wallet recovery durable key-set arrays are invalid`);let h=Xe(n.keyManifest,String(u.value)),g=n.nearKeySets.map(e=>Tt(e,St(h,e))),_=n.ecdsaKeySets.map(e=>Dt(e,Ct(h,e))),v=[...g.map(e=>e.keySetId),..._.map(e=>e.entry.keySetId)];if(new Set(v).size!==v.length)throw Error(`wallet recovery durable key-set ids are duplicated`);if(h.entries.length!==v.length||h.entries.some(e=>!v.includes(e.keySetId)))throw Error(`wallet recovery durable key-set manifest coverage is invalid`);let y={kind:`wallet_recovery_durable_payload_v1`,version:1,recoveryOperationId:c.value,walletId:u.value,reservationId:d,targetDeviceId:f.value,targetAuthorityId:p.value,targetWalletAuthMethodId:m.value,replacementEnvelope:k(n.replacementEnvelope,`wallet recovery durable replacementEnvelope`),keyManifest:h,nearKeySets:g,ecdsaKeySets:_};if(String(y.replacementEnvelope.walletId)!==String(u.value))throw Error(`wallet recovery durable replacement envelope wallet changed`);if(y.replacementEnvelope.ownership.kind!==`method_bound`||y.replacementEnvelope.ownership.walletAuthMethodId!==m.value)throw Error(`wallet recovery durable replacement envelope method changed`);for(let e of g)if(e.binding.walletId!==String(u.value))throw Error(`wallet recovery durable NEAR binding wallet changed`);let b=l(n.target,`wallet recovery durable target`);if(b.kind===`passkey`){V(b,[`kind`,`rpId`],`wallet recovery durable passkey target`);let e=r(b.rpId);if(!e.ok)throw Error(`wallet recovery durable passkey RP ID is invalid`);let t=Ot(n.registration);if(t.rawId!==y.replacementEnvelope.factor.credentialIdB64u)throw Error(`wallet recovery durable passkey registration identity changed`);if(y.replacementEnvelope.factor.kind!==`passkey`)throw Error(`wallet recovery durable passkey envelope factor is invalid`);if(y.replacementEnvelope.factor.rpId!==e.value||y.replacementEnvelope.factor.credentialIdB64u!==t.rawId)throw Error(`wallet recovery durable passkey envelope identity changed`);let i=H(n.replacementId,`wallet recovery durable replacementId`);if(String(y.replacementEnvelope.envelopeId)!==i)throw Error(`wallet recovery durable passkey envelope id changed`);return{...y,target:{kind:`passkey`,rpId:e.value},replacementId:i,challengeId:H(n.challengeId,`wallet recovery durable challengeId`),registration:t}}if(b.kind!==`google_email_otp`)throw Error(`wallet recovery durable target kind is invalid`);V(b,[`kind`],`wallet recovery durable Email OTP target`);let x=H(n.providerSubject,`wallet recovery providerSubject`);if(!a(x).ok)throw Error(`wallet recovery durable providerSubject is invalid`);let S=H(n.verifiedEmail,`wallet recovery durable verifiedEmail`),C=H(n.emailHashHex,`wallet recovery durable emailHashHex`);if(!/^[0-9a-f]{64}$/.test(C))throw Error(`wallet recovery durable emailHashHex is invalid`);let ee=H(n.registrationAuthorityId,`wallet recovery durable registrationAuthorityId`),w=kt(n.enrollment);if(y.replacementEnvelope.factor.kind!==`email_otp`)throw Error(`wallet recovery durable Email OTP envelope factor is invalid`);let T=w.kind===`existing`?{enrollmentId:w.enrollmentId,enrollmentSealKeyVersion:w.enrollmentSealKeyVersion}:{enrollmentId:w.enrollmentId,enrollmentSealKeyVersion:w.material.enrollmentSealKeyVersion};if(y.replacementEnvelope.factor.enrollmentId!==T.enrollmentId||y.replacementEnvelope.factor.enrollmentSealKeyVersion!==T.enrollmentSealKeyVersion)throw Error(`wallet recovery durable Email OTP envelope identity changed`);if(w.kind===`create`&&(w.providerSubject!==x||w.verifiedEmail!==S))throw Error(`wallet recovery durable Email OTP enrollment identity changed`);let E=H(n.replacementId,`wallet recovery durable replacementId`);if(String(y.replacementEnvelope.envelopeId)!==E)throw Error(`wallet recovery durable Email OTP envelope id changed`);return{...y,target:{kind:`google_email_otp`},providerSubject:x,verifiedEmail:S,emailHashHex:C,registrationAuthorityId:ee,replacementId:E,enrollment:w}}function At(e){let t=e.nearKeySets.map(e=>({kind:e.kind,keySetId:e.keySetId,applicationBindingDigestB64u:e.binding.applicationBindingDigestB64u,registeredPublicKeyB64u:e.binding.registeredPublicKeyB64u,participantIds:e.binding.participantIds,stateEpoch:e.binding.stateEpoch,signingWorkerVerifyingShareB64u:e.binding.signingWorkerVerifyingShareB64u,materialActivation:e.materialActivation,sealed:e.sealed})),n=e.ecdsaKeySets.map(e=>({kind:e.kind,keySetId:e.entry.keySetId,possessionProof:e.possessionProof,readyStateBlobB64u:e.readyStateBlobB64u,publicFacts:e.publicFacts})),r={kind:e.kind,version:e.version,recoveryOperationId:String(e.recoveryOperationId),walletId:String(e.walletId),reservationId:String(e.reservationId),targetDeviceId:String(e.targetDeviceId),targetAuthorityId:String(e.targetAuthorityId),targetWalletAuthMethodId:String(e.targetWalletAuthMethodId),replacementEnvelope:e.replacementEnvelope,keyManifest:e.keyManifest,nearKeySets:t,ecdsaKeySets:n},i=B(e)?{...r,target:e.target,replacementId:e.replacementId,challengeId:e.challengeId,registration:e.registration}:{...r,target:e.target,providerSubject:e.providerSubject,verifiedEmail:e.verifiedEmail,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId,replacementId:e.replacementId,enrollment:e.enrollment};return W(i),i}async function G(e){if(B(e))return;let t=await u(e.verifiedEmail);if(e.emailHashHex!==t)throw Error(`wallet recovery durable email hash does not match verified email`);if(e.enrollment.kind===`create`&&(e.enrollment.providerSubject!==e.providerSubject||e.enrollment.verifiedEmail!==e.verifiedEmail))throw Error(`wallet recovery durable enrollment does not match Email OTP identity`)}function K(e){if(B(e)){let t=n(e.registration.rawId);if(!t.ok)throw Error(`wallet recovery durable passkey credential id is invalid`);return{kind:`passkey`,rpId:e.target.rpId,credentialIdB64u:t.value}}let t=a(e.providerSubject);if(!t.ok)throw Error(`wallet recovery durable providerSubject is invalid`);return{kind:`google_email_otp`,providerSubject:t.value,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId,enrollment:mt(e)}}function jt(e){return{kind:`near_ed25519`,keySetId:e.entry.keySetId,applicationBindingDigestB64u:e.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:h(e.metadata.registeredPublicKey),participantIds:e.metadata.participantIds,stateEpoch:String(e.metadata.stateEpoch),signingWorkerVerifyingShareB64u:h(e.metadata.signingWorkerVerifyingShare),materialActivation:fe(e.metadata.materialActivation),sealed:{ciphertextB64u:e.localMaterial.b64u,nonceB64u:e.localMaterial.nonceB64u}}}function Mt(e){return{kind:`evm_family_ecdsa`,keySetId:e.entry.keySetId,possessionProof:N(e.activation.possessionProof),readyStateBlobB64u:e.readyStateBlobB64u,publicFacts:e.publicFacts}}function Nt(e){return{kind:`wallet_recovery_redacted_registration_v1`,id:e.id,rawId:e.rawId,type:e.type,authenticatorAttachment:e.authenticatorAttachment??null,response:{clientDataJSON:e.response.clientDataJSON,attestationObject:e.response.attestationObject,transports:[...e.response.transports]}}}async function Pt(e){let t={kind:`wallet_recovery_durable_payload_v1`,version:1,recoveryOperationId:String(e.prepared.recoveryOperationId),walletId:e.walletId,reservationId:e.prepared.reservationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,replacementEnvelope:k(e.recovered.replacementEnvelope,`wallet recovery durable replacement envelope`),keyManifest:{version:`wallet_recovery_preparation_key_manifest_v1`,walletId:String(e.walletId),entries:[...e.recovered.nearKeySets.map(e=>e.entry),...e.recovered.ecdsaKeySets.map(e=>e.entry)]},nearKeySets:e.recovered.nearKeySets.map(jt),ecdsaKeySets:e.recovered.ecdsaKeySets.map(Mt)};if(e.replacement.kind===`passkey`){if(e.target.kind!==`passkey`)throw Error(`wallet recovery durable payload branch is invalid`);let n=e.prepared.registration;if(!n)throw Error(`wallet recovery registration options are unavailable`);let r=Nt(e.replacement.registration);if(r.rawId!==e.replacement.credentialIdB64u)throw Error(`wallet recovery passkey registration rawId changed its credential identity`);let i=W({...t,target:{kind:`passkey`,rpId:e.target.rpId},replacementId:n.replacementId,challengeId:n.challengeId,registration:r});return await G(i),i}if(e.target.kind!==`google_email_otp`)throw Error(`wallet recovery durable payload branch is invalid`);let n=e.replacement.enrollment;if(e.replacement.factor.walletAuthMethodId!==t.targetWalletAuthMethodId)throw Error(`wallet recovery Email OTP factor method changed its target identity`);let r=await u(e.replacement.verifiedEmail),i=W({...t,target:{kind:`google_email_otp`},enrollment:n,providerSubject:e.replacement.providerSubject,verifiedEmail:e.replacement.verifiedEmail,emailHashHex:r,registrationAuthorityId:e.replacement.registrationAuthorityId,replacementId:e.replacement.factor.replacementId});return await G(i),i}function Ft(e){return new TextEncoder().encode(d({kind:`pending_wallet_recovery_commit_v1`,version:1,...e}))}function It(e){return Ft({recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:K(e)})}async function Lt(e){let t=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);if(!(t instanceof CryptoKey))throw Error(`wallet recovery durable key generation failed`);let n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(At(e)));return{kind:`wallet_recovery_encrypted_material_v1`,key:t,iv:n,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,additionalData:It(e)},t,r))}}async function Rt(e){let t=await crypto.subtle.decrypt({name:`AES-GCM`,iv:e.localMaterial.iv.slice(),additionalData:zt(e)},e.localMaterial.key,e.localMaterial.ciphertext.slice()),n=W(JSON.parse(new TextDecoder().decode(t)));if(await G(n),!Bt(e,n))throw Error(`wallet recovery durable payload identity does not match its journal`);return n}function zt(e){return Ft({recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:e.target})}function q(e){let t=o(e);if(!t.ok)throw Error(`wallet recovery operation id is invalid`);return t.value}function Bt(e,t){let n={kind:`pending_wallet_recovery_commit_v1`,version:1,recoveryOperationId:q(t.recoveryOperationId),walletId:t.walletId,reservationId:t.reservationId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,localMaterial:e.localMaterial,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs},r=K(t);if(e.stage===`awaiting_server_promotion`)return Te(e,{...n,stage:`awaiting_server_promotion`,target:r});switch(r.kind){case`passkey`:return e.projection.kind===`passkey`?Te(e,{...n,stage:`server_promoted`,target:r,projection:e.projection}):!1;case`google_email_otp`:return e.projection.kind===`google_email_otp`?Te(e,{...n,stage:`server_promoted`,target:r,projection:e.projection}):!1}}function Vt(e,t,n,r){return{kind:`pending_wallet_recovery_commit_v1`,version:1,recoveryOperationId:q(e.recoveryOperationId),walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:K(e),localMaterial:t,createdAtMs:n,updatedAtMs:r}}function Ht(e,t,n=Date.now()){return{...Vt(e,t,n,n),stage:`awaiting_server_promotion`}}function Ut(e,t,n,r=Date.now()){let i=Vt(t,e.localMaterial,e.createdAtMs,Math.max(r,e.createdAtMs+1));if(B(t)){if(n.kind!==`passkey`)throw Error(`wallet recovery promotion projection branch changed`);return{...i,stage:`server_promoted`,target:K(t),projection:n}}if(n.kind!==`google_email_otp`)throw Error(`wallet recovery promotion projection branch changed`);return{...i,stage:`server_promoted`,target:K(t),projection:n}}const Wt=`/wallets/recovery/google-email-otp/finalize`;async function Gt(e){let t=await J(e,`/wallets/recovery/google/verify`,{recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,idToken:e.idToken});if(!t.ok)return t.failure;try{let n=Xt(t.body),r=Yt(n,e),i=Q(c(n.challengeId)),a=Number(n.expiresAtMs);if(!Number.isSafeInteger(a)||a<=0)throw Error(`invalid expiry`);return{kind:`verified`,...r,challengeId:i,delivery:Ne(n.delivery,`walletRecoveryGoogleVerify.delivery`),expiresAtMs:a}}catch{return{kind:`transport_uncertain`}}}async function Kt(e){let t=await J(e,`/wallets/recovery/email-otp/verify`,{recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,challengeId:e.challengeId,otpCode:e.otpCode});if(!t.ok)return t.failure;try{let n=Zt(t.body),r=Yt(n,e),i=Q(c(n.challengeId));if(i!==e.challengeId)throw Error(`challenge changed`);return{kind:`verified`,...r,challengeId:i}}catch{return{kind:`transport_uncertain`}}}async function qt(e){let t,n;try{if(t=k(e.replacementEnvelope,`walletRecoveryGoogleEmailOtpFinalize.replacementEnvelope`),t.factor.kind!==`email_otp`)throw Error(`wrong factor`);n=e.ecdsaMaterialPossessionProofs.map(e=>({keySetId:e.keySetId,proof:N(e.proof)}))}catch{return{kind:`refused`}}let r=await J(e,Wt,{kind:`finalize`,recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,replacementEnvelope:t,ecdsaMaterialPossessionProofs:n,...e.emailOtpEnrollment?{emailOtpEnrollment:e.emailOtpEnrollment}:{}});if(!r.ok)return r.failure;try{let n=await A(Qt(r.body,`walletRecoveryGoogleEmailOtpFinalize`).projection,en(e,t));if(n.kind!==`google_email_otp`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:n.storeVersion,authority:n.authority,authMethod:n.authMethod}}catch{return{kind:`transport_uncertain`}}}async function Jt(e){let t;try{if(t=k(e.replacementEnvelope,`walletRecoveryGoogleEmailOtpReplay.replacementEnvelope`),t.factor.kind!==`email_otp`||String(t.walletId)!==String(e.walletId))throw Error(`recovery replay envelope identity is invalid`)}catch{return{kind:`refused`}}let n=await J(e,Wt,{kind:`replay`,recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,replacementEnvelope:t});if(!n.ok)return n.failure;try{let r=await A(Qt(n.body,`walletRecoveryGoogleEmailOtpReplay`).projection,en(e,t));if(r.kind!==`google_email_otp`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:r.storeVersion,authority:r.authority,authMethod:r.authMethod}}catch{return{kind:`transport_uncertain`}}}async function J(e,t,n){let r;try{r=await(e.fetchImpl??fetch)(`${m(e.relayUrl)}${t}`,p({body:n}))}catch{return{ok:!1,failure:{kind:`transport_uncertain`}}}let i=await r.json().catch(()=>void 0);return r.status===200?{ok:!0,body:i}:r.status===409||r.status===429?{ok:!1,failure:{kind:`retryable_conflict`}}:r.status===400||r.status===401?{ok:!1,failure:{kind:`refused`}}:{ok:!1,failure:{kind:`transport_uncertain`}}}function Yt(e,t){let n=Q(o(e.recoveryOperationId)),r=M(e.reservationId);if(n!==t.recoveryOperationId||r!==t.reservationId)throw Error(`recovery operation identity changed`);return{recoveryOperationId:n,reservationId:r}}function Xt(e){let t=Y(e,[`ok`,`recoveryOperationId`,`reservationId`,`challengeId`,`delivery`,`expiresAtMs`],`walletRecoveryGoogleVerify`);return X(t,`walletRecoveryGoogleVerify`),{recoveryOperationId:Z(t,`recoveryOperationId`),reservationId:Z(t,`reservationId`),challengeId:Z(t,`challengeId`),delivery:Z(t,`delivery`),expiresAtMs:Z(t,`expiresAtMs`)}}function Zt(e){let t=Y(e,[`ok`,`recoveryOperationId`,`reservationId`,`challengeId`],`walletRecoveryEmailOtpVerify`);return X(t,`walletRecoveryEmailOtpVerify`),{recoveryOperationId:Z(t,`recoveryOperationId`),reservationId:Z(t,`reservationId`),challengeId:Z(t,`challengeId`)}}function Qt(e,t){let n=Y(e,[`ok`,`projection`],t);return X(n,t),{projection:Z(n,`projection`)}}function Y(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be a JSON object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Error(`${n} must be a plain JSON object`);let i=Object.keys(e);if(i.length!==t.length||!$t(i,t))throw Error(`${n} has an unexpected response shape`);return e}function $t(e,t){for(let n of t)if(!e.includes(n))return!1;return!0}function X(e,t){if(Z(e,`ok`)!==!0)throw Error(`${t} did not succeed`)}function Z(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!(`value`in n))throw Error(`response field ${t} is missing`);return n.value}function Q(e){if(!e.ok)throw Error(`invalid domain identity`);return e.value}function $(e){if(typeof e!=`string`||!e.trim())throw Error(`value must be a string`);return e.trim()}function en(e,t){if(t.factor.kind!==`email_otp`)throw Error(`replacement envelope is not an Email OTP envelope`);return{kind:`google_email_otp`,walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,providerSubject:Q(a(e.expectedProviderSubject)),emailHashHex:tn(e.expectedEmailHashHex),registrationAuthorityId:$(e.expectedRegistrationAuthorityId),enrollment:{kind:`email_otp_enrollment_reference_v1`,enrollmentId:$(t.factor.enrollmentId),enrollmentSealKeyVersion:$(t.factor.enrollmentSealKeyVersion)}}}function tn(e){let t=$(e);if(!/^[0-9a-f]{64}$/.test(t))throw Error(`email hash is invalid`);return t}async function nn(e,t){if(e.version!==t.version||e.storeVersion!==t.storeVersion||e.walletId!==t.walletId||e.recoveryOperationId!==t.recoveryOperationId||e.targetDeviceId!==t.targetDeviceId||e.targetAuthorityId!==t.targetAuthorityId||e.targetWalletAuthMethodId!==t.targetWalletAuthMethodId||!await oe(e.authority,t.authority)||!xe(e.authMethod,t.authMethod)||e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`?e.target.kind===t.target.kind&&e.target.rpId===t.target.rpId&&e.target.credentialIdB64u===t.target.credentialIdB64u:!1;case`google_email_otp`:return t.kind===`google_email_otp`?e.target.kind===t.target.kind&&e.target.provider===t.target.provider&&e.target.providerSubject===t.target.providerSubject&&e.target.emailHashHex===t.target.emailHashHex&&e.target.registrationAuthorityId===t.target.registrationAuthorityId&&e.target.enrollment.kind===t.target.enrollment.kind&&e.target.enrollment.enrollmentId===t.target.enrollment.enrollmentId&&e.target.enrollment.enrollmentSealKeyVersion===t.target.enrollment.enrollmentSealKeyVersion:!1;default:return rn(e)}}function rn(e){throw Error(`unsupported wallet recovery projection: ${String(e)}`)}function an(e){let t=q(e.payload.recoveryOperationId);switch(e.kind){case`passkey`:return we({kind:`passkey`,storeVersion:e.promotion.storeVersion,walletId:e.payload.walletId,recoveryOperationId:t,targetDeviceId:e.payload.targetDeviceId,targetAuthorityId:e.payload.targetAuthorityId,targetWalletAuthMethodId:e.payload.targetWalletAuthMethodId,authority:e.promotion.authority,authMethod:e.promotion.authMethod});case`google_email_otp`:{let n=a(e.payload.providerSubject);if(!n.ok)throw Error(`wallet recovery provider subject is invalid`);return we({kind:`google_email_otp`,storeVersion:e.promotion.storeVersion,walletId:e.payload.walletId,recoveryOperationId:t,targetDeviceId:e.payload.targetDeviceId,targetAuthorityId:e.payload.targetAuthorityId,targetWalletAuthMethodId:e.payload.targetWalletAuthMethodId,authority:e.promotion.authority,authMethod:e.promotion.authMethod,providerSubject:n.value,emailHashHex:e.payload.emailHashHex,registrationAuthorityId:e.payload.registrationAuthorityId,enrollment:mt(e.payload)})}}}function on(e){return e.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.possessionProof}))}function sn(e){return{id:e.registration.id,rawId:e.registration.rawId,type:e.registration.type,authenticatorAttachment:e.registration.authenticatorAttachment??void 0,response:{clientDataJSON:e.registration.response.clientDataJSON,attestationObject:e.registration.response.attestationObject,transports:[...e.registration.response.transports]},clientExtensionResults:{prf:{results:{first:void 0,second:void 0}}}}}async function cn(e){let{payload:t}=e;if(B(t)){let n=await ut({relayUrl:e.relayUrl,walletId:String(t.walletId),reservationId:String(t.reservationId),recoveryOperationId:q(t.recoveryOperationId),targetDeviceId:String(t.targetDeviceId),targetAuthorityId:String(t.targetAuthorityId),targetWalletAuthMethodId:String(t.targetWalletAuthMethodId),challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:sn(t),replacementEnvelope:t.replacementEnvelope,ecdsaMaterialPossessionProofs:on(t),fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`passkey`,payload:t,promotion:n}:n}let n=await qt({relayUrl:e.relayUrl,recoveryOperationId:q(t.recoveryOperationId),reservationId:t.reservationId,walletId:t.walletId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,expectedProviderSubject:t.providerSubject,expectedEmailHashHex:t.emailHashHex,expectedRegistrationAuthorityId:t.registrationAuthorityId,replacementEnvelope:t.replacementEnvelope,ecdsaMaterialPossessionProofs:on(t),emailOtpEnrollment:ln(t.enrollment),fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`google_email_otp`,payload:t,promotion:n}:n}function ln(e){return e.kind===`create`?{kind:`create`,material:e.material}:null}async function un(e){let{payload:t}=e;if(B(t)){let n=await dt({relayUrl:e.relayUrl,walletId:String(t.walletId),reservationId:String(t.reservationId),recoveryOperationId:q(t.recoveryOperationId),targetDeviceId:String(t.targetDeviceId),targetAuthorityId:String(t.targetAuthorityId),targetWalletAuthMethodId:String(t.targetWalletAuthMethodId),replacementId:t.replacementId,replacementEnvelope:t.replacementEnvelope,fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`passkey`,payload:t,promotion:n}:n}let n=await Jt({relayUrl:e.relayUrl,recoveryOperationId:q(t.recoveryOperationId),reservationId:t.reservationId,walletId:t.walletId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,expectedProviderSubject:t.providerSubject,expectedEmailHashHex:t.emailHashHex,expectedRegistrationAuthorityId:t.registrationAuthorityId,replacementEnvelope:t.replacementEnvelope,fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`google_email_otp`,payload:t,promotion:n}:n}function dn(e){return e.kind===`passkey`||e.kind===`google_email_otp`}async function fn(e){let t=await un(e);return dn(t)||t.kind!==`refused`?t:await cn(e)}function pn(e,t){return{walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:t.target.credentialIdB64u},verifier:{kind:`webauthn`,rpId:t.target.rpId},bindingId:t.authMethod.walletAuthMethodId}}function mn(e,t){let n=he({walletId:e.walletId,provider:`google`,providerUserId:e.providerSubject,emailHashHex:e.emailHashHex});return{walletId:n.walletId,factor:n.factor,verifier:n.verifier,bindingId:t.authMethod.walletAuthMethodId}}async function hn(e,t){if(B(e)){if(t.kind!==`passkey`)throw Error(`wallet recovery projection branch changed`);return ve({authority:pn(e,t)})}if(t.kind!==`google_email_otp`)throw Error(`wallet recovery projection branch changed`);return ve({authority:mn(e,t)})}async function gn(e){let t=[],n=[];for(let r of e.payload.ecdsaKeySets){let i=r.entry,a=i.recoveryBasis,o=await ce({walletId:e.payload.walletId,signingRootId:a.signingRootId,signingRootVersion:a.signingRootVersion}),s=await Ee({authority:e.authority,chainTargets:a.chainTargets,walletId:String(e.payload.walletId),keyHandle:i.keyHandle,ecdsaThresholdKeyId:a.ecdsaThresholdKeyId,signingRootId:a.signingRootId,signingRootVersion:a.signingRootVersion,relayerKeyId:o,participantIds:a.participantIds,publicCapability:a.publicCapability,activationReceipt:a.activationReceipt,runtimePolicyScope:a.runtimePolicyScope,readyStateBlobB64u:r.readyStateBlobB64u,publicFacts:r.publicFacts});n.push(s);for(let n of a.chainTargets)t.push(_n({payload:e.payload,keySet:r,chainTarget:n,materialRef:s.roleLocalMaterialRef,relayerKeyId:o}))}return{walletKeys:t,ecdsaContinuity:n}}function _n(e){let t=e.keySet.entry,n=t.recoveryBasis,r=e.keySet.publicFacts,i=Se({walletId:e.payload.walletId,chainTarget:e.chainTarget,keyHandle:t.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,applicationBindingDigestB64u:n.publicCapability.context.application_binding_digest_b64u,clientParticipantId:1,relayerParticipantId:2,participantIds:n.participantIds,contextBinding32B64u:r.contextBinding32B64u,derivationClientSharePublicKey33B64u:r.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:r.relayerPublicKey33B64u,groupPublicKey33B64u:r.groupPublicKey33B64u,ethereumAddress:r.ethereumAddress,publicCapability:n.publicCapability});return{keyScope:`evm-family`,chainTarget:e.chainTarget,walletId:String(e.payload.walletId),evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,keyHandle:t.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,thresholdEcdsaPublicKeyB64u:r.groupPublicKey33B64u,thresholdOwnerAddress:r.ethereumAddress,relayerKeyId:e.relayerKeyId,relayerVerifyingShareB64u:r.relayerPublicKey33B64u,participantIds:n.participantIds,publicCapability:n.publicCapability,roleLocalMaterialRef:e.materialRef,ecdsaRoleLocalPublicFacts:i}}function vn(e){if(e.nearKeySets.length!==1)throw Error(`wallet recovery requires exactly one NEAR key set`);return e.nearKeySets[0]}function yn(e){return[...e.registration.response.transports]}function bn(e){return`ed25519:${ae(g(vn(e).binding.registeredPublicKeyB64u))}`}function xn(t,n){let r=e(n.thresholdSessionId);if(!r.ok)throw Error(`recovery NEAR threshold session id is invalid`);return{walletId:t.walletId,nearAccountId:O(n.binding.nearAccountId),thresholdSessionId:r.value,runtimePolicyScope:n.runtimePolicyScope,materialActivation:de(n.materialActivation)}}async function Sn(e){if(B(e.payload)){if(e.projection.kind!==`passkey`)throw Error(`wallet recovery projection branch changed`);let t={walletId:e.payload.walletId,rpId:e.projection.target.rpId,credentialIdB64u:e.projection.target.credentialIdB64u,credentialPublicKeyB64u:e.projection.authMethod.credentialPublicKeyB64u,transports:yn(e.payload),walletKeys:e.walletKeys};if(e.payload.nearKeySets.length===0)return ke({kind:`evm_family_ecdsa`,...t});let n=vn(e.payload);return ke({kind:`near_ed25519`,...t,nearAccountId:O(n.binding.nearAccountId),nearEd25519SigningKeyId:n.binding.nearEd25519SigningKeyId,signerSlot:n.binding.signerSlot,operationalPublicKey:bn(e.payload),relayerKeyId:n.binding.signingWorkerId,participantIds:n.binding.participantIds,custodyMaterials:e.payload.nearKeySets.map(e=>({binding:e.binding,sealed:e.sealed}))})}if(e.projection.kind!==`google_email_otp`)throw Error(`wallet recovery projection branch changed`);let t=mn(e.payload,e.projection),n={walletId:e.payload.walletId,email:e.payload.verifiedEmail,registrationAuthorityId:e.payload.registrationAuthorityId,authority:t,walletKeys:e.walletKeys};if(e.payload.nearKeySets.length===0)return Ae({kind:`evm_family_ecdsa`,...n});let r=vn(e.payload);return Ae({kind:`near_ed25519`,...n,nearAccountId:O(r.binding.nearAccountId),nearEd25519SigningKeyId:r.binding.nearEd25519SigningKeyId,signerSlot:r.binding.signerSlot,operationalPublicKey:bn(e.payload),relayerKeyId:r.binding.signingWorkerId,participantIds:r.binding.participantIds,custodyMaterials:e.payload.nearKeySets.map(e=>({binding:e.binding,sealed:e.sealed}))})}async function Cn(e){let t=e.pending.projection,n=await hn(e.payload,t),r=await gn({payload:e.payload,authority:n}),i=await Sn({payload:e.payload,projection:t,walletKeys:r.walletKeys});await j.publishPendingWalletRecoveryCommit({pending:e.pending,authority:t.authority,authMethod:t.authMethod,registration:i,ecdsaContinuity:r.ecdsaContinuity,ed25519PublicCapabilityReferences:e.payload.nearKeySets.map(t=>xn(e.payload,t))})}async function wn(e){let t=await j.listPendingWalletRecoveryCommits(),n=[];for(let r of t)try{let t=await Rt(r),i=r.stage===`awaiting_server_promotion`?await fn({relayUrl:e.relayUrl,payload:t,fetchImpl:e.fetchImpl}):await un({relayUrl:e.relayUrl,payload:t,fetchImpl:e.fetchImpl});if(!dn(i)){if(i.kind===`refused`){await j.deletePendingWalletRecoveryCommit(r.recoveryOperationId),n.push({kind:`discarded`,recoveryOperationId:String(r.recoveryOperationId)});continue}n.push({kind:`pending`,recoveryOperationId:String(r.recoveryOperationId),failure:i});continue}let a=i,o=an(a),s=r.stage===`awaiting_server_promotion`?await j.advancePendingWalletRecoveryCommit({awaiting:r,promoted:Ut(r,a.payload,o,r.updatedAtMs+1)}):r;if(r.stage===`server_promoted`&&!await nn(r.projection,o))throw Error(`wallet recovery replay projection changed`);await Cn({pending:s,payload:a.payload}),n.push({kind:`completed`,recoveryOperationId:String(r.recoveryOperationId)})}catch(e){console.warn(`[SeamsWeb] pending wallet recovery replay failed before classification:`,String(r.recoveryOperationId),e instanceof Error?e.message:String(e||`unknown error`)),n.push({kind:`corrupt`,recoveryOperationId:String(r.recoveryOperationId)})}return n}async function Tn(e){let t=await Pt(e.operation);return{payload:t,pending:Ht(t,await Lt(t),e.nowMs)}}async function En(e){let t=an(e.promotion);return j.advancePendingWalletRecoveryCommit({awaiting:e.awaiting,promoted:Ut(e.awaiting,e.promotion.payload,t,e.awaiting.updatedAtMs+1)})}export{qt as a,B as c,Be as d,wn as i,ut as l,En as n,Kt as o,Cn as r,Gt as s,Tn as t,ze as u};
|
|
1
|
+
import{C as e,E as t,M as n,N as r,O as i,c as a,j as o,k as s,s as c}from"./domainIds-t1lp25yU.js";import{S as l,i as u,t as d,y as f}from"./digests-BIaE0DMd.js";import{o as p,u as m}from"./participants-BXdREC5k.js";import{i as h,r as g}from"./base64-BmKR3UqU.js";import{s as _}from"./walletDbName-B6-CV_Rq.js";import{D as v,E as y,G as b,H as x,J as S,M as C,N as ee,O as w,W as T,X as E,j as te,k as ne}from"./activeWalletSession-HAOgRKzn.js";import{n as re,t as ie}from"./signingSessionSeal-BFOBKj-J.js";import{l as D}from"./capabilityKinds-Cafn86Y1.js";import{d as ae,t as O}from"./accountIds-DGWFzEnw.js";import{x as k}from"./registrationIntent-Cb3tggIM.js";import{m as oe}from"./walletAuthority-CU9nO0Ze.js";import{A as se,Ct as ce,Dt as le,Et as ue,Nt as de,Pt as fe,S as pe,Tt as me,X as he,jt as ge,kt as _e,ut as ve,wt as ye,xt as be}from"./digestEncoding-Rx8Vjy4J.js";import{i as xe}from"./walletAuthMethodRecord--fvGr8r1.js";import{C as Se}from"./ecdsaCapabilityManifest-BbPXL-qh.js";import{O as Ce,_ as A,g as we,h as Te,t as j,y as M}from"./indexedDB-BqsYXybq.js";import{r as Ee}from"./walletCustodyEcdsaContinuity-BUdDyRl_.js";import{o as De}from"./helpers-B7c1zc7h.js";import{P as Oe,h as ke,m as Ae}from"./accountLifecycle-B5a9SCM7.js";import{a as je,n as N,t as Me}from"./wallet-recovery-Bfm-oUoP.js";import{n as Ne}from"./challengeDelivery-Dj9HrjW9.js";function Pe(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`wallet recovery target must be an object`);let t=e,n=Object.keys(t);switch(t.kind){case`passkey`:{if(n.length!==2||!n.includes(`rpId`))throw Error(`Passkey recovery target fields are invalid`);let e=r(t.rpId);if(!e.ok)throw Error(`Passkey recovery target RP ID is invalid`);return{kind:`passkey`,rpId:e.value}}case`google_email_otp`:if(n.length!==2||!n.includes(`googleProvider`)||t.googleProvider!==`google`)throw Error(`Google Email OTP recovery target fields are invalid`);return{kind:`google_email_otp`,googleProvider:`google`};default:throw Error(`wallet recovery target kind is unsupported`)}}const Fe=[`ok`,`walletId`,`target`,`recoveryOperationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`wrap`,`entries`,`keyManifest`,`reservationId`,`reservationExpiresAtMs`,`storeVersion`],Ie=[...Fe,`registration`];function P(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Le(e,t,n){let r=new Set(t),i=Object.keys(e);if(i.length!==r.size||i.some(e=>!r.has(e)))throw Error(`${n} contains unexpected fields`)}function F(e,t,n){let r=P(e,n);return Le(r,t,n),r}function I(e,t){return Object.prototype.hasOwnProperty.call(e,t)?Reflect.get(e,t):void 0}function Re(e){try{return P(e,`walletRecoveryPrepare response`)}catch{return null}}function ze(e){let t=s(e.walletId);if(!t.ok)throw Error(`wallet recovery ${t.error.message}`);return JSON.stringify({walletId:String(t.value),wrap:e.prepared.wrap,entry:e.prepared.entries[0]})}async function Be(e){let t=await Ve(e);return t.ok?await He({response:t.response,target:e.target,reservationId:e.reservationId}):{kind:t.kind}}async function Ve(e){let t=`${m(e.relayUrl)}/wallets/recovery/prepare`,n=e.fetchImpl||fetch;try{return{ok:!0,response:await n(t,p({body:{recoveryCodeB64u:e.recoveryCodeB64u,reservationId:e.reservationId,target:e.target}}))}}catch{return{ok:!1,kind:`transport_uncertain`}}}async function He(e){let n=e.response,r=Re(await n.json().catch(()=>({})));if(n.status===200&&r&&I(r,`ok`)===!0)try{let n=F(r,e.target.kind===`passkey`?Ie:Fe,`walletRecoveryPrepare`),a=Je()(I(n,`wrap`),`walletRecoveryPrepare.wrap`),c=Ye(I(n,`entries`)),l=s(I(n,`walletId`));if(!l.ok)throw Error(`walletRecoveryPrepare.walletId is invalid`);let u=l.value,d=Pe(I(n,`target`));if(!Ke(d,e.target))throw Error(`wallet recovery preparation changed the recovery target`);let f=o(I(n,`recoveryOperationId`)),p=D(I(n,`targetDeviceId`)),m=i(I(n,`targetAuthorityId`)),h=t(I(n,`targetWalletAuthMethodId`));if(!f.ok||!p.ok||!m.ok||!h.ok)throw Error(`wallet recovery preparation target identity is invalid`);let g=Xe(I(n,`keyManifest`),u),_=M(I(n,`reservationId`)),v=ee(I(n,`reservationExpiresAtMs`),`walletRecoveryPrepare.reservationExpiresAtMs`),y=L(I(n,`storeVersion`),`storeVersion`);if(_!==e.reservationId)throw Error(`wallet recovery preparation changed the reservation identity`);let b={kind:`prepared`,walletId:u,recoveryOperationId:f.value,targetDeviceId:p.value,targetAuthorityId:m.value,targetWalletAuthMethodId:h.value,wrap:a,entries:c,keyManifest:g,reservationId:_,reservationExpiresAtMs:v,storeVersion:y};switch(d.kind){case`passkey`:{let e=Ue(String(u),d.rpId)(I(n,`registration`),`registration`);if(e.walletAuthMethodId!==h.value)throw Error(`wallet recovery registration changed the target auth method`);return{...b,target:d,registration:e}}case`google_email_otp`:if(Object.prototype.hasOwnProperty.call(n,`registration`))throw Error(`Google Email OTP recovery cannot carry passkey registration`);return{...b,target:d};default:return qe(d)}}catch{return{kind:`transport_uncertain`}}return n.status===409?{kind:`retryable_conflict`}:n.status===401&&r&&I(r,`code`)===`recovery_code_used`?{kind:`consumed`}:n.status===401||n.status===400?{kind:`refused`}:{kind:`transport_uncertain`}}function Ue(e,i){let a=h(new TextEncoder().encode(e)),o=T({type:x(`public-key`),id:(e,t)=>{let r=b(n)(e,t);return ct(r,t),r}});return T({kind:x(`webauthn_recovery_registration_v1`),challengeId:L,challengeB64u:(e,t)=>st(e,32,t),replacementId:L,walletAuthMethodId:b(t),rpId:b(r),user:T({idB64u:ct,name:L,displayName:L},(t,n)=>{if(t.idB64u!==a||t.name!==e||t.displayName!==e)throw Error(`${n} is bound to another wallet`)}),pubKeyCredParams:(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw Error(`${t} is invalid`);return[We(-7)(e[0],`${t}[0]`),We(-257)(e[1],`${t}[1]`)]},authenticatorSelection:T({residentKey:x(`required`),userVerification:x(`preferred`)}),timeoutMs:(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} is invalid`);return n},attestation:x(`none`),extensions:T({prf:T({eval:T({firstB64u:Ge(ie),secondB64u:Ge(re)})})}),excludeCredentials:(e,t)=>f(e,t).map((e,n)=>o(e,`${t}[${n}]`))},(e,t)=>{if(e.rpId!==i)throw Error(`${t} changed the relying party`)})}function We(e){return T({type:x(`public-key`),alg:(t,n)=>{if(t!==e)throw Error(`${n} is invalid`);return e}})}function Ge(e){return(t,n)=>{let r=st(t,e.length,n);if(r!==h(e))throw Error(`${n} is unsupported`);return r}}function Ke(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId;case`google_email_otp`:return t.kind===`google_email_otp`&&e.googleProvider===t.googleProvider;default:return qe(e)}}function qe(e){throw Error(`unsupported wallet recovery target: ${String(e)}`)}function Je(){return T({nonceB64u:ne,wrappedManifestKekB64u:w,aadHashB64u:y})}function Ye(e){if(!Array.isArray(e)||e.length!==1)throw Error(`walletRecoveryPrepare.entries must contain exactly one custody seed`);return[je(e[0],`walletRecoveryPrepare.entries[0]`)]}function L(e,t){if(typeof e!=`string`||!e.trim())throw Error(`walletRecoveryPrepare.${t} must be a non-empty string`);return e.trim()}function Xe(e,t){let n=F(e,[`version`,`walletId`,`entries`],`walletRecoveryPrepare.keyManifest`);if(I(n,`version`)!==`wallet_recovery_preparation_key_manifest_v1`)throw Error(`walletRecoveryPrepare.keyManifest version is invalid`);let r=L(I(n,`walletId`),`keyManifest.walletId`);if(r!==t)throw Error(`walletRecoveryPrepare.keyManifest changed the wallet identity`);let i=I(n,`entries`);if(!Array.isArray(i)||i.length===0)throw Error(`walletRecoveryPrepare.keyManifest must contain a key set`);let a=i.map(e=>Ze(e,r));if(new Set(a.map(e=>e.keySetId)).size!==a.length)throw Error(`walletRecoveryPrepare.keyManifest contains duplicate key sets`);return{version:`wallet_recovery_preparation_key_manifest_v1`,walletId:r,entries:a}}function Ze(e,t){switch(I(P(e,`walletRecoveryPrepare.keyManifest.entries[]`),`kind`)){case`near_ed25519`:{let n=F(e,[`kind`,`keySetId`,`signerId`,`nearAccountId`,`recordedKeyManifestDigestB64u`,`recoveryBasis`],`walletRecoveryPrepare.keyManifest.entries[].near_ed25519`),r=L(I(n,`signerId`),`keyManifest.entries[].signerId`),i=L(I(n,`keySetId`),`keyManifest.entries[].keySetId`),a=`near_ed25519:${r}`;if(i!==a)throw Error(`walletRecoveryPrepare NEAR key-set identity is inconsistent`);let o=L(I(n,`nearAccountId`),`keyManifest.entries[].nearAccountId`),s=Qe(I(n,`recoveryBasis`),t);return{kind:`near_ed25519`,keySetId:a,signerId:r,nearAccountId:o,recordedKeyManifestDigestB64u:y(I(n,`recordedKeyManifestDigestB64u`),`walletRecoveryPrepare.keyManifest.entries[].recordedKeyManifestDigestB64u`),recoveryBasis:s}}case`evm_family_ecdsa`:{let n=F(e,[`kind`,`keySetId`,`keyHandle`,`evmFamilySigningKeySlotId`,`recordedKeyManifestDigestB64u`,`recoveryBasis`],`walletRecoveryPrepare.keyManifest.entries[].evm_family_ecdsa`),r=L(I(n,`keyHandle`),`keyManifest.entries[].keyHandle`),i=L(I(n,`keySetId`),`keyManifest.entries[].keySetId`),a=`evm_family_ecdsa:${r}`;if(i!==a)throw Error(`walletRecoveryPrepare ECDSA key-set identity is inconsistent`);let o=$e(I(n,`recoveryBasis`),t);return{kind:`evm_family_ecdsa`,keySetId:a,keyHandle:r,evmFamilySigningKeySlotId:_e(I(n,`evmFamilySigningKeySlotId`)),recordedKeyManifestDigestB64u:y(I(n,`recordedKeyManifestDigestB64u`),`walletRecoveryPrepare.keyManifest.entries[].recordedKeyManifestDigestB64u`),recoveryBasis:o}}default:throw Error(`walletRecoveryPrepare key-manifest entry kind is invalid`)}}function Qe(e,t){let n=F(e,[`capabilityKind`,`activeCapabilityBinding`,`scope`,`applicationBinding`,`participantIds`,`registeredPublicKey`,`runtimePolicyScope`,`activationTranscript`,`activationStateEpoch`,`signingWorkerVerifyingShare`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis`),r=I(n,`capabilityKind`);if(r!==`registration`&&r!==`recovery`)throw Error(`walletRecoveryPrepare NEAR recovery capability kind is invalid`);let i=R(I(n,`activeCapabilityBinding`),32,`NEAR recovery active capability binding`),a=rt(I(n,`scope`)),o=it(I(n,`applicationBinding`)),s=ot(I(n,`participantIds`),`NEAR recovery participant IDs`),c=R(I(n,`registeredPublicKey`),32,`NEAR recovery registered public key`),l=at(I(n,`runtimePolicyScope`)),u=R(I(n,`activationTranscript`),32,`NEAR recovery activation transcript`),d=Number(I(n,`activationStateEpoch`));if(!Number.isSafeInteger(d)||d<=0)throw Error(`walletRecoveryPrepare NEAR recovery activation state epoch is invalid`);let f=R(I(n,`signingWorkerVerifyingShare`),32,`NEAR recovery signing-worker verifying share`);if(o.wallet_id!==t||a.account_id!==t||a.root_share_epoch!==l.signingRootVersion)throw Error(`walletRecoveryPrepare NEAR recovery basis changed its wallet scope`);return{capabilityKind:r,activeCapabilityBinding:i,scope:a,applicationBinding:o,participantIds:s,registeredPublicKey:c,runtimePolicyScope:l,activationTranscript:u,activationStateEpoch:d,signingWorkerVerifyingShare:f}}function $e(e,t){let n=F(e,[`publicCapability`,`activationReceipt`,`serverGeneration`,`clientRootPublicKey33B64u`,`chainTargets`,`ecdsaThresholdKeyId`,`signingRootId`,`signingRootVersion`,`runtimePolicyScope`,`participantIds`,`possessionChallenge`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis`),r=pe(I(n,`publicCapability`)),i=se(I(n,`activationReceipt`));if(r.client_id!==t)throw Error(`walletRecoveryPrepare ECDSA recovery capability changed the wallet scope`);let a=me(I(n,`signingRootId`)),o=ue(I(n,`signingRootVersion`)),s=at(I(n,`runtimePolicyScope`));if(s.signingRootVersion!==o)throw Error(`walletRecoveryPrepare ECDSA recovery scope changed the signing root`);let c=be(I(n,`serverGeneration`));if(String(i.server_generation)!==String(c))throw Error(`walletRecoveryPrepare ECDSA activation receipt changed server generation`);let l=Me(I(n,`possessionChallenge`));if(l.walletId!==t||l.expectedServerGeneration!==String(c)||l.derivationClientSharePublicKey33B64u!==r.public_identity.derivation_client_share_public_key33_b64u)throw Error(`walletRecoveryPrepare ECDSA possession challenge changed its capability`);return{publicCapability:r,activationReceipt:i,serverGeneration:c,clientRootPublicKey33B64u:ye(L(I(n,`clientRootPublicKey33B64u`),`keyManifest.entries[].recoveryBasis.clientRootPublicKey33B64u`)),chainTargets:et(I(n,`chainTargets`)),ecdsaThresholdKeyId:le(I(n,`ecdsaThresholdKeyId`)),signingRootId:a,signingRootVersion:o,runtimePolicyScope:s,participantIds:nt(I(n,`participantIds`)),possessionChallenge:l}}function et(e){if(!Array.isArray(e)||e.length===0)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are invalid`);let t=e.map((e,t)=>tt(e,t));if(new Set(t.map(Ce)).size!==t.length)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are duplicated`);let n=t[0];if(!n)throw Error(`walletRecoveryPrepare ECDSA recovery chain targets are invalid`);return[n,...t.slice(1)]}function tt(e,t){let n=`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.chainTargets[${t}]`,r=P(e,n),i=I(r,`kind`);Le(r,i===`evm`?[`kind`,`namespace`,`chainId`,`networkSlug`]:[`kind`,`chainId`,`networkSlug`],n);let a=I(r,`namespace`),o=Number(I(r,`chainId`));if(!Number.isSafeInteger(o)||o<=0)throw Error(`walletRecoveryPrepare ECDSA recovery chain id is invalid`);let s=I(r,`networkSlug`),c=typeof s==`string`&&s.trim()?s.trim():null;if(i===`evm`){if(a!==`eip155`)throw Error(`walletRecoveryPrepare ECDSA recovery EVM namespace is invalid`);return{kind:`evm`,namespace:`eip155`,chainId:o,networkSlug:c??`evm-${o}`}}if(i===`tempo`)return{kind:`tempo`,chainId:o,networkSlug:c??`tempo-${o}`};throw Error(`walletRecoveryPrepare ECDSA recovery chain family is invalid`)}function nt(e){if(!Array.isArray(e)||e.length!==2||e[0]!==1||e[1]!==2)throw Error(`walletRecoveryPrepare ECDSA recovery participant IDs are invalid`);return[1,2]}function rt(e){let t=F(e,[`lifecycle_id`,`root_share_epoch`,`account_id`,`threshold_session_id`,`signer_set_id`,`signing_worker_id`,`material_activation`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.scope`);return{lifecycle_id:L(I(t,`lifecycle_id`),`keyManifest.entries[].recoveryBasis.scope.lifecycle_id`),root_share_epoch:L(I(t,`root_share_epoch`),`keyManifest.entries[].recoveryBasis.scope.root_share_epoch`),account_id:L(I(t,`account_id`),`keyManifest.entries[].recoveryBasis.scope.account_id`),threshold_session_id:L(I(t,`threshold_session_id`),`keyManifest.entries[].recoveryBasis.scope.threshold_session_id`),signer_set_id:L(I(t,`signer_set_id`),`keyManifest.entries[].recoveryBasis.scope.signer_set_id`),signing_worker_id:L(I(t,`signing_worker_id`),`keyManifest.entries[].recoveryBasis.scope.signing_worker_id`),material_activation:ge(I(t,`material_activation`))}}function it(e){let t=F(e,[`wallet_id`,`near_ed25519_signing_key_id`,`signing_root_id`,`key_creation_signer_slot`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.applicationBinding`),n=Number(I(t,`key_creation_signer_slot`));if(!Number.isSafeInteger(n)||n<=0)throw Error(`walletRecoveryPrepare NEAR recovery key-creation signer slot is invalid`);return{wallet_id:L(I(t,`wallet_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.wallet_id`),near_ed25519_signing_key_id:L(I(t,`near_ed25519_signing_key_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.near_ed25519_signing_key_id`),signing_root_id:L(I(t,`signing_root_id`),`keyManifest.entries[].recoveryBasis.applicationBinding.signing_root_id`),key_creation_signer_slot:n}}function at(e){let t=F(e,[`orgId`,`projectId`,`envId`,`signingRootVersion`],`walletRecoveryPrepare.keyManifest.entries[].recoveryBasis.runtimePolicyScope`);try{return E(t)}catch{throw Error(`walletRecoveryPrepare NEAR recovery runtime policy scope is invalid`)}}function ot(e,t){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||Number(e[0])<=0||Number(e[1])<=0||Number(e[0])===Number(e[1]))throw Error(`walletRecoveryPrepare ${t} is invalid`);return[Number(e[0]),Number(e[1])]}function st(e,t,n){let r=L(e,n),i=g(r);if(i.length!==t||h(i)!==r)throw Error(`walletRecoveryPrepare ${n} is invalid`);return r}function ct(e,t){let n=L(e,t),r=g(n);if(r.length===0||h(r)!==n)throw Error(`walletRecoveryPrepare ${t} is invalid`);return n}function R(e,t,n){if(!Array.isArray(e)||e.length!==t||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`walletRecoveryPrepare ${n} is invalid`);return e.map(Number)}const lt=`/wallets/recovery/finalize`;async function ut(e){let t=`${m(e.relayUrl)}${lt}`,n=e.fetchImpl||fetch,r;try{r=De(e.webauthnRegistration)}catch{return{kind:`refused`}}let i;try{let t=new Set;i=e.ecdsaMaterialPossessionProofs.map(e=>{if(typeof e.keySetId!=`string`||!e.keySetId.startsWith(`evm_family_ecdsa:`)||e.keySetId.length<=17)throw Error(`ECDSA possession proof key-set id is invalid`);if(t.has(e.keySetId))throw Error(`ECDSA possession proof key-set ids are duplicated`);return t.add(e.keySetId),{keySetId:e.keySetId,proof:N(e.proof)}})}catch{return{kind:`refused`}}let a;try{if(a=k(e.replacementEnvelope,`walletRecoveryFinalize.replacementEnvelope`),String(a.walletId)!==String(e.walletId))throw Error(`replacement envelope changed the wallet identity`);if(String(a.envelopeId)!==String(e.replacementId))throw Error(`replacement envelope changed the replacement identity`);if(a.factor.kind!==`passkey`)throw Error(`replacement envelope is not bound to a passkey`)}catch{return{kind:`refused`}}let o;try{o=await n(t,p({body:{kind:`finalize`,walletId:e.walletId,reservationId:e.reservationId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,challengeId:e.challengeId,replacementId:e.replacementId,webauthnRegistration:r,replacementEnvelope:a,ecdsaMaterialPossessionProofs:i}}))}catch{return{kind:`transport_uncertain`}}let s=ft(await o.json().catch(()=>({})));if(o.status===200&&s.kind===`success`)try{let t=await A(s.projection,pt(e,a));if(t.kind!==`passkey`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:t.storeVersion,authority:t.authority,authMethod:t.authMethod}}catch{return{kind:`transport_uncertain`}}return o.status===409?{kind:`retryable_conflict`}:o.status===400||o.status===401?{kind:`refused`}:{kind:`transport_uncertain`}}async function dt(e){let t;try{if(t=k(e.replacementEnvelope,`walletRecoveryReplay.replacementEnvelope`),String(t.walletId)!==String(e.walletId)||String(t.envelopeId)!==String(e.replacementId)||t.factor.kind!==`passkey`)throw Error(`recovery replay envelope identity is invalid`)}catch{return{kind:`refused`}}let n;try{n=await(e.fetchImpl??fetch)(`${m(e.relayUrl)}${lt}`,p({body:{kind:`replay`,walletId:e.walletId,reservationId:e.reservationId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,replacementId:e.replacementId,replacementEnvelope:t}}))}catch{return{kind:`transport_uncertain`}}let r=ft(await n.json().catch(()=>({})));if(n.status===200&&r.kind===`success`)try{let n=await A(r.projection,pt(e,t));if(n.kind!==`passkey`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:n.storeVersion,authority:n.authority,authMethod:n.authMethod}}catch{return{kind:`transport_uncertain`}}return n.status===409?{kind:`retryable_conflict`}:n.status===400||n.status===401?{kind:`refused`}:{kind:`transport_uncertain`}}function ft(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`invalid`};let t=new Map(Object.entries(e)),n=[...t.keys()];if(t.size===2&&n.includes(`ok`)&&n.includes(`projection`)&&t.get(`ok`)===!0)return{kind:`success`,projection:t.get(`projection`)};let r=t.get(`code`),i=t.get(`message`);return t.size===3&&n.includes(`ok`)&&n.includes(`code`)&&n.includes(`message`)&&t.get(`ok`)===!1&&typeof r==`string`&&typeof i==`string`?{kind:`failure`,code:r,message:i}:{kind:`invalid`}}function pt(e,n){if(n.factor.kind!==`passkey`)throw Error(`replacement envelope is not a passkey envelope`);return{kind:`passkey`,walletId:z(s(e.walletId)),recoveryOperationId:z(o(e.recoveryOperationId)),targetDeviceId:z(D(e.targetDeviceId)),targetAuthorityId:z(i(e.targetAuthorityId)),targetWalletAuthMethodId:z(t(e.targetWalletAuthMethodId)),rpId:n.factor.rpId,credentialIdB64u:n.factor.credentialIdB64u}}function z(e){if(!e.ok)throw Error(`invalid recovery identity`);return e.value}function B(e){return e.target.kind===`passkey`}function mt(e){return{kind:`email_otp_enrollment_reference_v1`,enrollmentId:e.enrollment.enrollmentId,enrollmentSealKeyVersion:e.enrollment.kind===`existing`?e.enrollment.enrollmentSealKeyVersion:e.enrollment.material.enrollmentSealKeyVersion}}const ht=[`kind`,`keySetId`,`applicationBindingDigestB64u`,`registeredPublicKeyB64u`,`participantIds`,`stateEpoch`,`signingWorkerVerifyingShareB64u`,`materialActivation`,`sealed`],gt=[`kind`,`keySetId`,`possessionProof`,`readyStateBlobB64u`,`publicFacts`],_t=[`contextBinding32B64u`,`derivationClientSharePublicKey33B64u`,`clientVerifyingShare33B64u`,`relayerPublicKey33B64u`,`groupPublicKey33B64u`,`ethereumAddress`,`clientShareRetryCounter`,`relayerShareRetryCounter`],vt=[`kind`,`version`,`recoveryOperationId`,`walletId`,`reservationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`replacementEnvelope`,`keyManifest`,`nearKeySets`,`ecdsaKeySets`,`target`];function V(e,t,n){if(S(e,t,n),Object.keys(e).length!==t.length)throw Error(n+` fields are invalid`)}function H(e,t){if(typeof e!=`string`||!e||e.trim()!==e)throw Error(t+` must be a non-empty canonical string`);return e}function U(e,t,n){let r=H(e,t),i=g(r);if(n!==void 0&&i.byteLength!==n)throw Error(t+` must decode to `+n+` bytes`);return r}function yt(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(t+` must be a non-negative safe integer`);return e}function bt(e,t){if(!Array.isArray(e)||e.length!==2||e.some(xt))throw Error(t+` must contain two positive participant IDs`);return[e[0],e[1]]}function xt(e){return typeof e!=`number`||!Number.isSafeInteger(e)||e<1}function St(e,t){let n=H(l(t,`recovery durable NEAR key set`).keySetId,`recovery durable NEAR keySetId`),r=e.entries.find(e=>e.keySetId===n);if(!r||r.kind!==`near_ed25519`)throw Error(`recovery durable NEAR key-set manifest entry is invalid`);return r}function Ct(e,t){let n=H(l(t,`recovery durable ECDSA key set`).keySetId,`recovery durable ECDSA keySetId`),r=e.entries.find(e=>e.keySetId===n);if(!r||r.kind!==`evm_family_ecdsa`)throw Error(`recovery durable ECDSA key-set manifest entry is invalid`);return r}function wt(e){let t=_(e);if(!t)throw Error(`recovery runtime policy scope is invalid`);return t}function Tt(t,n){let r=l(t,`recovery durable NEAR key set`);if(V(r,ht,`recovery durable NEAR key set`),r.kind!==`near_ed25519`||r.keySetId!==n.keySetId)throw Error(`recovery durable NEAR key-set identity is invalid`);let i=n.recoveryBasis,a=i.scope.threshold_session_id;if(!e(a).ok)throw Error(`recovery durable NEAR thresholdSessionId is invalid`);let o={kind:Oe,applicationBindingDigestB64u:y(r.applicationBindingDigestB64u,`recovery durable NEAR application binding digest`),registeredPublicKeyB64u:v(r.registeredPublicKeyB64u,`recovery durable NEAR registered public key`),participantIds:bt(r.participantIds,`recovery durable NEAR participantIds`),stateEpoch:H(r.stateEpoch,`recovery durable NEAR stateEpoch`),walletId:i.applicationBinding.wallet_id,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:i.applicationBinding.near_ed25519_signing_key_id,signerSlot:te(i.applicationBinding.key_creation_signer_slot,`recovery durable NEAR signerSlot`),signingWorkerId:i.scope.signing_worker_id,signingWorkerVerifyingShareB64u:v(r.signingWorkerVerifyingShareB64u,`recovery durable NEAR signing-worker verifying share`)},s=l(r.sealed,`recovery durable NEAR sealed material`);return V(s,[`ciphertextB64u`,`nonceB64u`],`recovery durable NEAR sealed material`),{kind:`near_ed25519`,keySetId:n.keySetId,binding:o,thresholdSessionId:a,runtimePolicyScope:wt(i.runtimePolicyScope),materialActivation:ge(r.materialActivation),sealed:{ciphertextB64u:w(s.ciphertextB64u,`recovery durable NEAR ciphertext`),nonceB64u:ne(s.nonceB64u,`recovery durable NEAR nonce`)}}}function Et(e){let t=l(e,`recovery durable ECDSA public facts`);V(t,_t,`recovery durable ECDSA public facts`);let n=H(t.ethereumAddress,`recovery durable ECDSA ethereumAddress`).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw Error(`recovery durable ECDSA ethereumAddress is invalid`);return{contextBinding32B64u:y(t.contextBinding32B64u,`recovery durable ECDSA context binding`),derivationClientSharePublicKey33B64u:C(t.derivationClientSharePublicKey33B64u,`recovery durable ECDSA client share`),clientVerifyingShare33B64u:C(t.clientVerifyingShare33B64u,`recovery durable ECDSA client verifying share`),relayerPublicKey33B64u:C(t.relayerPublicKey33B64u,`recovery durable ECDSA relayer public key`),groupPublicKey33B64u:C(t.groupPublicKey33B64u,`recovery durable ECDSA group public key`),ethereumAddress:n,clientShareRetryCounter:yt(t.clientShareRetryCounter,`recovery durable ECDSA client-share retry counter`),relayerShareRetryCounter:yt(t.relayerShareRetryCounter,`recovery durable ECDSA relayer-share retry counter`)}}function Dt(e,t){let n=l(e,`recovery durable ECDSA key set`);if(V(n,gt,`recovery durable ECDSA key set`),n.kind!==`evm_family_ecdsa`||n.keySetId!==t.keySetId)throw Error(`recovery durable ECDSA key-set identity is invalid`);return{kind:`evm_family_ecdsa`,entry:t,possessionProof:N(n.possessionProof),readyStateBlobB64u:U(n.readyStateBlobB64u,`recovery durable ECDSA ready-state blob`),publicFacts:Et(n.publicFacts)}}function Ot(e){let t=l(e,`recovery durable registration`);if(V(t,[`kind`,`id`,`rawId`,`type`,`authenticatorAttachment`,`response`],`recovery durable registration`),t.kind!==`wallet_recovery_redacted_registration_v1`)throw Error(`recovery durable registration kind is invalid`);if(t.authenticatorAttachment!==null&&typeof t.authenticatorAttachment!=`string`)throw Error(`recovery durable registration authenticatorAttachment is invalid`);let n=l(t.response,`recovery durable registration response`);if(V(n,[`clientDataJSON`,`attestationObject`,`transports`],`recovery durable registration response`),!Array.isArray(n.transports))throw Error(`recovery durable registration transports are invalid`);return{kind:`wallet_recovery_redacted_registration_v1`,id:H(t.id,`recovery durable registration id`),rawId:U(t.rawId,`recovery durable registration rawId`),type:H(t.type,`recovery durable registration type`),authenticatorAttachment:t.authenticatorAttachment,response:{clientDataJSON:U(n.clientDataJSON,`recovery durable registration clientDataJSON`),attestationObject:U(n.attestationObject,`recovery durable registration attestationObject`),transports:n.transports.map((e,t)=>H(e,`recovery durable registration transports[`+t+`]`))}}}function kt(e){let t=l(e,`recovery durable Email OTP enrollment`);if(t.kind===`existing`)return V(t,[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`],`recovery durable existing Email OTP enrollment`),{kind:`existing`,enrollmentId:H(t.enrollmentId,`recovery enrollmentId`),enrollmentSealKeyVersion:H(t.enrollmentSealKeyVersion,`recovery enrollment seal-key version`)};if(t.kind!==`create`)throw Error(`recovery durable Email OTP enrollment kind is invalid`);V(t,[`kind`,`enrollmentId`,`providerSubject`,`verifiedEmail`,`material`],`recovery durable create Email OTP enrollment`);let n=l(t.material,`recovery durable enrollment material`);return V(n,[`enrollmentSealKeyVersion`,`clientUnlockPublicKeyB64u`,`unlockKeyVersion`,`serverSealedFactorCiphertextB64u`],`recovery durable enrollment material`),{kind:`create`,enrollmentId:H(t.enrollmentId,`recovery enrollmentId`),providerSubject:H(t.providerSubject,`recovery enrollment providerSubject`),verifiedEmail:H(t.verifiedEmail,`recovery enrollment verifiedEmail`),material:{enrollmentSealKeyVersion:H(n.enrollmentSealKeyVersion,`recovery enrollment material seal-key version`),clientUnlockPublicKeyB64u:U(n.clientUnlockPublicKeyB64u,`recovery enrollment client unlock public key`),unlockKeyVersion:H(n.unlockKeyVersion,`recovery enrollment unlock-key version`),serverSealedFactorCiphertextB64u:U(n.serverSealedFactorCiphertextB64u,`recovery enrollment sealed factor ciphertext`)}}}function W(e){let n=l(e,`wallet recovery durable payload`);if(n.kind!==`wallet_recovery_durable_payload_v1`||n.version!==1)throw Error(`wallet recovery durable payload version is invalid`);V(n,[...vt,...l(n.target,`wallet recovery durable target`).kind===`passkey`?[`replacementId`,`challengeId`,`registration`]:[`providerSubject`,`verifiedEmail`,`emailHashHex`,`registrationAuthorityId`,`replacementId`,`enrollment`]],`wallet recovery durable payload`);let c=o(n.recoveryOperationId),u=s(n.walletId),d;try{d=M(n.reservationId)}catch(e){throw Error(`wallet recovery durable reservationId is invalid`,{cause:e})}let f=D(n.targetDeviceId),p=i(n.targetAuthorityId),m=t(n.targetWalletAuthMethodId);if(!c.ok||!u.ok||!f.ok||!p.ok||!m.ok)throw Error(`wallet recovery durable payload identity is invalid`);if(!Array.isArray(n.nearKeySets)||!Array.isArray(n.ecdsaKeySets))throw Error(`wallet recovery durable key-set arrays are invalid`);let h=Xe(n.keyManifest,String(u.value)),g=n.nearKeySets.map(e=>Tt(e,St(h,e))),_=n.ecdsaKeySets.map(e=>Dt(e,Ct(h,e))),v=[...g.map(e=>e.keySetId),..._.map(e=>e.entry.keySetId)];if(new Set(v).size!==v.length)throw Error(`wallet recovery durable key-set ids are duplicated`);if(h.entries.length!==v.length||h.entries.some(e=>!v.includes(e.keySetId)))throw Error(`wallet recovery durable key-set manifest coverage is invalid`);let y={kind:`wallet_recovery_durable_payload_v1`,version:1,recoveryOperationId:c.value,walletId:u.value,reservationId:d,targetDeviceId:f.value,targetAuthorityId:p.value,targetWalletAuthMethodId:m.value,replacementEnvelope:k(n.replacementEnvelope,`wallet recovery durable replacementEnvelope`),keyManifest:h,nearKeySets:g,ecdsaKeySets:_};if(String(y.replacementEnvelope.walletId)!==String(u.value))throw Error(`wallet recovery durable replacement envelope wallet changed`);if(y.replacementEnvelope.ownership.kind!==`method_bound`||y.replacementEnvelope.ownership.walletAuthMethodId!==m.value)throw Error(`wallet recovery durable replacement envelope method changed`);for(let e of g)if(e.binding.walletId!==String(u.value))throw Error(`wallet recovery durable NEAR binding wallet changed`);let b=l(n.target,`wallet recovery durable target`);if(b.kind===`passkey`){V(b,[`kind`,`rpId`],`wallet recovery durable passkey target`);let e=r(b.rpId);if(!e.ok)throw Error(`wallet recovery durable passkey RP ID is invalid`);let t=Ot(n.registration);if(t.rawId!==y.replacementEnvelope.factor.credentialIdB64u)throw Error(`wallet recovery durable passkey registration identity changed`);if(y.replacementEnvelope.factor.kind!==`passkey`)throw Error(`wallet recovery durable passkey envelope factor is invalid`);if(y.replacementEnvelope.factor.rpId!==e.value||y.replacementEnvelope.factor.credentialIdB64u!==t.rawId)throw Error(`wallet recovery durable passkey envelope identity changed`);let i=H(n.replacementId,`wallet recovery durable replacementId`);if(String(y.replacementEnvelope.envelopeId)!==i)throw Error(`wallet recovery durable passkey envelope id changed`);return{...y,target:{kind:`passkey`,rpId:e.value},replacementId:i,challengeId:H(n.challengeId,`wallet recovery durable challengeId`),registration:t}}if(b.kind!==`google_email_otp`)throw Error(`wallet recovery durable target kind is invalid`);V(b,[`kind`],`wallet recovery durable Email OTP target`);let x=H(n.providerSubject,`wallet recovery providerSubject`);if(!a(x).ok)throw Error(`wallet recovery durable providerSubject is invalid`);let S=H(n.verifiedEmail,`wallet recovery durable verifiedEmail`),C=H(n.emailHashHex,`wallet recovery durable emailHashHex`);if(!/^[0-9a-f]{64}$/.test(C))throw Error(`wallet recovery durable emailHashHex is invalid`);let ee=H(n.registrationAuthorityId,`wallet recovery durable registrationAuthorityId`),w=kt(n.enrollment);if(y.replacementEnvelope.factor.kind!==`email_otp`)throw Error(`wallet recovery durable Email OTP envelope factor is invalid`);let T=w.kind===`existing`?{enrollmentId:w.enrollmentId,enrollmentSealKeyVersion:w.enrollmentSealKeyVersion}:{enrollmentId:w.enrollmentId,enrollmentSealKeyVersion:w.material.enrollmentSealKeyVersion};if(y.replacementEnvelope.factor.enrollmentId!==T.enrollmentId||y.replacementEnvelope.factor.enrollmentSealKeyVersion!==T.enrollmentSealKeyVersion)throw Error(`wallet recovery durable Email OTP envelope identity changed`);if(w.kind===`create`&&(w.providerSubject!==x||w.verifiedEmail!==S))throw Error(`wallet recovery durable Email OTP enrollment identity changed`);let E=H(n.replacementId,`wallet recovery durable replacementId`);if(String(y.replacementEnvelope.envelopeId)!==E)throw Error(`wallet recovery durable Email OTP envelope id changed`);return{...y,target:{kind:`google_email_otp`},providerSubject:x,verifiedEmail:S,emailHashHex:C,registrationAuthorityId:ee,replacementId:E,enrollment:w}}function At(e){let t=e.nearKeySets.map(e=>({kind:e.kind,keySetId:e.keySetId,applicationBindingDigestB64u:e.binding.applicationBindingDigestB64u,registeredPublicKeyB64u:e.binding.registeredPublicKeyB64u,participantIds:e.binding.participantIds,stateEpoch:e.binding.stateEpoch,signingWorkerVerifyingShareB64u:e.binding.signingWorkerVerifyingShareB64u,materialActivation:e.materialActivation,sealed:e.sealed})),n=e.ecdsaKeySets.map(e=>({kind:e.kind,keySetId:e.entry.keySetId,possessionProof:e.possessionProof,readyStateBlobB64u:e.readyStateBlobB64u,publicFacts:e.publicFacts})),r={kind:e.kind,version:e.version,recoveryOperationId:String(e.recoveryOperationId),walletId:String(e.walletId),reservationId:String(e.reservationId),targetDeviceId:String(e.targetDeviceId),targetAuthorityId:String(e.targetAuthorityId),targetWalletAuthMethodId:String(e.targetWalletAuthMethodId),replacementEnvelope:e.replacementEnvelope,keyManifest:e.keyManifest,nearKeySets:t,ecdsaKeySets:n},i=B(e)?{...r,target:e.target,replacementId:e.replacementId,challengeId:e.challengeId,registration:e.registration}:{...r,target:e.target,providerSubject:e.providerSubject,verifiedEmail:e.verifiedEmail,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId,replacementId:e.replacementId,enrollment:e.enrollment};return W(i),i}async function G(e){if(B(e))return;let t=await u(e.verifiedEmail);if(e.emailHashHex!==t)throw Error(`wallet recovery durable email hash does not match verified email`);if(e.enrollment.kind===`create`&&(e.enrollment.providerSubject!==e.providerSubject||e.enrollment.verifiedEmail!==e.verifiedEmail))throw Error(`wallet recovery durable enrollment does not match Email OTP identity`)}function K(e){if(B(e)){let t=n(e.registration.rawId);if(!t.ok)throw Error(`wallet recovery durable passkey credential id is invalid`);return{kind:`passkey`,rpId:e.target.rpId,credentialIdB64u:t.value}}let t=a(e.providerSubject);if(!t.ok)throw Error(`wallet recovery durable providerSubject is invalid`);return{kind:`google_email_otp`,providerSubject:t.value,emailHashHex:e.emailHashHex,registrationAuthorityId:e.registrationAuthorityId,enrollment:mt(e)}}function jt(e){return{kind:`near_ed25519`,keySetId:e.entry.keySetId,applicationBindingDigestB64u:e.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:h(e.metadata.registeredPublicKey),participantIds:e.metadata.participantIds,stateEpoch:String(e.metadata.stateEpoch),signingWorkerVerifyingShareB64u:h(e.metadata.signingWorkerVerifyingShare),materialActivation:fe(e.metadata.materialActivation),sealed:{ciphertextB64u:e.localMaterial.b64u,nonceB64u:e.localMaterial.nonceB64u}}}function Mt(e){return{kind:`evm_family_ecdsa`,keySetId:e.entry.keySetId,possessionProof:N(e.activation.possessionProof),readyStateBlobB64u:e.readyStateBlobB64u,publicFacts:e.publicFacts}}function Nt(e){return{kind:`wallet_recovery_redacted_registration_v1`,id:e.id,rawId:e.rawId,type:e.type,authenticatorAttachment:e.authenticatorAttachment??null,response:{clientDataJSON:e.response.clientDataJSON,attestationObject:e.response.attestationObject,transports:[...e.response.transports]}}}async function Pt(e){let t={kind:`wallet_recovery_durable_payload_v1`,version:1,recoveryOperationId:String(e.prepared.recoveryOperationId),walletId:e.walletId,reservationId:e.prepared.reservationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,replacementEnvelope:k(e.recovered.replacementEnvelope,`wallet recovery durable replacement envelope`),keyManifest:{version:`wallet_recovery_preparation_key_manifest_v1`,walletId:String(e.walletId),entries:[...e.recovered.nearKeySets.map(e=>e.entry),...e.recovered.ecdsaKeySets.map(e=>e.entry)]},nearKeySets:e.recovered.nearKeySets.map(jt),ecdsaKeySets:e.recovered.ecdsaKeySets.map(Mt)};if(e.replacement.kind===`passkey`){if(e.target.kind!==`passkey`)throw Error(`wallet recovery durable payload branch is invalid`);let n=e.prepared.registration;if(!n)throw Error(`wallet recovery registration options are unavailable`);let r=Nt(e.replacement.registration);if(r.rawId!==e.replacement.credentialIdB64u)throw Error(`wallet recovery passkey registration rawId changed its credential identity`);let i=W({...t,target:{kind:`passkey`,rpId:e.target.rpId},replacementId:n.replacementId,challengeId:n.challengeId,registration:r});return await G(i),i}if(e.target.kind!==`google_email_otp`)throw Error(`wallet recovery durable payload branch is invalid`);let n=e.replacement.enrollment;if(e.replacement.factor.walletAuthMethodId!==t.targetWalletAuthMethodId)throw Error(`wallet recovery Email OTP factor method changed its target identity`);let r=await u(e.replacement.verifiedEmail),i=W({...t,target:{kind:`google_email_otp`},enrollment:n,providerSubject:e.replacement.providerSubject,verifiedEmail:e.replacement.verifiedEmail,emailHashHex:r,registrationAuthorityId:e.replacement.registrationAuthorityId,replacementId:e.replacement.factor.replacementId});return await G(i),i}function Ft(e){return new TextEncoder().encode(d({kind:`pending_wallet_recovery_commit_v1`,version:1,...e}))}function It(e){return Ft({recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:K(e)})}async function Lt(e){let t=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);if(!(t instanceof CryptoKey))throw Error(`wallet recovery durable key generation failed`);let n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(At(e)));return{kind:`wallet_recovery_encrypted_material_v1`,key:t,iv:n,ciphertext:new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:n,additionalData:It(e)},t,r))}}async function Rt(e){let t=await crypto.subtle.decrypt({name:`AES-GCM`,iv:e.localMaterial.iv.slice(),additionalData:zt(e)},e.localMaterial.key,e.localMaterial.ciphertext.slice()),n=W(JSON.parse(new TextDecoder().decode(t)));if(await G(n),!Bt(e,n))throw Error(`wallet recovery durable payload identity does not match its journal`);return n}function zt(e){return Ft({recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:e.target})}function q(e){let t=o(e);if(!t.ok)throw Error(`wallet recovery operation id is invalid`);return t.value}function Bt(e,t){let n={kind:`pending_wallet_recovery_commit_v1`,version:1,recoveryOperationId:q(t.recoveryOperationId),walletId:t.walletId,reservationId:t.reservationId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,localMaterial:e.localMaterial,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs},r=K(t);if(e.stage===`awaiting_server_promotion`)return Te(e,{...n,stage:`awaiting_server_promotion`,target:r});switch(r.kind){case`passkey`:return e.projection.kind===`passkey`?Te(e,{...n,stage:`server_promoted`,target:r,projection:e.projection}):!1;case`google_email_otp`:return e.projection.kind===`google_email_otp`?Te(e,{...n,stage:`server_promoted`,target:r,projection:e.projection}):!1}}function Vt(e,t,n,r){return{kind:`pending_wallet_recovery_commit_v1`,version:1,recoveryOperationId:q(e.recoveryOperationId),walletId:e.walletId,reservationId:e.reservationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,target:K(e),localMaterial:t,createdAtMs:n,updatedAtMs:r}}function Ht(e,t,n=Date.now()){return{...Vt(e,t,n,n),stage:`awaiting_server_promotion`}}function Ut(e,t,n,r=Date.now()){let i=Vt(t,e.localMaterial,e.createdAtMs,Math.max(r,e.createdAtMs+1));if(B(t)){if(n.kind!==`passkey`)throw Error(`wallet recovery promotion projection branch changed`);return{...i,stage:`server_promoted`,target:K(t),projection:n}}if(n.kind!==`google_email_otp`)throw Error(`wallet recovery promotion projection branch changed`);return{...i,stage:`server_promoted`,target:K(t),projection:n}}const Wt=`/wallets/recovery/google-email-otp/finalize`;async function Gt(e){let t=await J(e,`/wallets/recovery/google/verify`,{recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,idToken:e.idToken});if(!t.ok)return t.failure;try{let n=Xt(t.body),r=Yt(n,e),i=Q(c(n.challengeId)),a=Number(n.expiresAtMs);if(!Number.isSafeInteger(a)||a<=0)throw Error(`invalid expiry`);return{kind:`verified`,...r,challengeId:i,delivery:Ne(n.delivery,`walletRecoveryGoogleVerify.delivery`),expiresAtMs:a}}catch{return{kind:`transport_uncertain`}}}async function Kt(e){let t=await J(e,`/wallets/recovery/email-otp/verify`,{recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,challengeId:e.challengeId,otpCode:e.otpCode});if(!t.ok)return t.failure;try{let n=Zt(t.body),r=Yt(n,e),i=Q(c(n.challengeId));if(i!==e.challengeId)throw Error(`challenge changed`);return{kind:`verified`,...r,challengeId:i}}catch{return{kind:`transport_uncertain`}}}async function qt(e){let t,n;try{if(t=k(e.replacementEnvelope,`walletRecoveryGoogleEmailOtpFinalize.replacementEnvelope`),t.factor.kind!==`email_otp`)throw Error(`wrong factor`);n=e.ecdsaMaterialPossessionProofs.map(e=>({keySetId:e.keySetId,proof:N(e.proof)}))}catch{return{kind:`refused`}}let r=await J(e,Wt,{kind:`finalize`,recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,replacementEnvelope:t,ecdsaMaterialPossessionProofs:n,...e.emailOtpEnrollment?{emailOtpEnrollment:e.emailOtpEnrollment}:{}});if(!r.ok)return r.failure;try{let n=await A(Qt(r.body,`walletRecoveryGoogleEmailOtpFinalize`).projection,en(e,t));if(n.kind!==`google_email_otp`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:n.storeVersion,authority:n.authority,authMethod:n.authMethod}}catch{return{kind:`transport_uncertain`}}}async function Jt(e){let t;try{if(t=k(e.replacementEnvelope,`walletRecoveryGoogleEmailOtpReplay.replacementEnvelope`),t.factor.kind!==`email_otp`||String(t.walletId)!==String(e.walletId))throw Error(`recovery replay envelope identity is invalid`)}catch{return{kind:`refused`}}let n=await J(e,Wt,{kind:`replay`,recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId,replacementEnvelope:t});if(!n.ok)return n.failure;try{let r=await A(Qt(n.body,`walletRecoveryGoogleEmailOtpReplay`).projection,en(e,t));if(r.kind!==`google_email_otp`)throw Error(`recovery projection branch changed`);return{kind:`promoted`,storeVersion:r.storeVersion,authority:r.authority,authMethod:r.authMethod}}catch{return{kind:`transport_uncertain`}}}async function J(e,t,n){let r;try{r=await(e.fetchImpl??fetch)(`${m(e.relayUrl)}${t}`,p({body:n}))}catch{return{ok:!1,failure:{kind:`transport_uncertain`}}}let i=await r.json().catch(()=>void 0);return r.status===200?{ok:!0,body:i}:r.status===409||r.status===429?{ok:!1,failure:{kind:`retryable_conflict`}}:r.status===400||r.status===401?{ok:!1,failure:{kind:`refused`}}:{ok:!1,failure:{kind:`transport_uncertain`}}}function Yt(e,t){let n=Q(o(e.recoveryOperationId)),r=M(e.reservationId);if(n!==t.recoveryOperationId||r!==t.reservationId)throw Error(`recovery operation identity changed`);return{recoveryOperationId:n,reservationId:r}}function Xt(e){let t=Y(e,[`ok`,`recoveryOperationId`,`reservationId`,`challengeId`,`delivery`,`expiresAtMs`],`walletRecoveryGoogleVerify`);return X(t,`walletRecoveryGoogleVerify`),{recoveryOperationId:Z(t,`recoveryOperationId`),reservationId:Z(t,`reservationId`),challengeId:Z(t,`challengeId`),delivery:Z(t,`delivery`),expiresAtMs:Z(t,`expiresAtMs`)}}function Zt(e){let t=Y(e,[`ok`,`recoveryOperationId`,`reservationId`,`challengeId`],`walletRecoveryEmailOtpVerify`);return X(t,`walletRecoveryEmailOtpVerify`),{recoveryOperationId:Z(t,`recoveryOperationId`),reservationId:Z(t,`reservationId`),challengeId:Z(t,`challengeId`)}}function Qt(e,t){let n=Y(e,[`ok`,`projection`],t);return X(n,t),{projection:Z(n,`projection`)}}function Y(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be a JSON object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Error(`${n} must be a plain JSON object`);let i=Object.keys(e);if(i.length!==t.length||!$t(i,t))throw Error(`${n} has an unexpected response shape`);return e}function $t(e,t){for(let n of t)if(!e.includes(n))return!1;return!0}function X(e,t){if(Z(e,`ok`)!==!0)throw Error(`${t} did not succeed`)}function Z(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!(`value`in n))throw Error(`response field ${t} is missing`);return n.value}function Q(e){if(!e.ok)throw Error(`invalid domain identity`);return e.value}function $(e){if(typeof e!=`string`||!e.trim())throw Error(`value must be a string`);return e.trim()}function en(e,t){if(t.factor.kind!==`email_otp`)throw Error(`replacement envelope is not an Email OTP envelope`);return{kind:`google_email_otp`,walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,providerSubject:Q(a(e.expectedProviderSubject)),emailHashHex:tn(e.expectedEmailHashHex),registrationAuthorityId:$(e.expectedRegistrationAuthorityId),enrollment:{kind:`email_otp_enrollment_reference_v1`,enrollmentId:$(t.factor.enrollmentId),enrollmentSealKeyVersion:$(t.factor.enrollmentSealKeyVersion)}}}function tn(e){let t=$(e);if(!/^[0-9a-f]{64}$/.test(t))throw Error(`email hash is invalid`);return t}async function nn(e,t){if(e.version!==t.version||e.storeVersion!==t.storeVersion||e.walletId!==t.walletId||e.recoveryOperationId!==t.recoveryOperationId||e.targetDeviceId!==t.targetDeviceId||e.targetAuthorityId!==t.targetAuthorityId||e.targetWalletAuthMethodId!==t.targetWalletAuthMethodId||!await oe(e.authority,t.authority)||!xe(e.authMethod,t.authMethod)||e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`?e.target.kind===t.target.kind&&e.target.rpId===t.target.rpId&&e.target.credentialIdB64u===t.target.credentialIdB64u:!1;case`google_email_otp`:return t.kind===`google_email_otp`?e.target.kind===t.target.kind&&e.target.provider===t.target.provider&&e.target.providerSubject===t.target.providerSubject&&e.target.emailHashHex===t.target.emailHashHex&&e.target.registrationAuthorityId===t.target.registrationAuthorityId&&e.target.enrollment.kind===t.target.enrollment.kind&&e.target.enrollment.enrollmentId===t.target.enrollment.enrollmentId&&e.target.enrollment.enrollmentSealKeyVersion===t.target.enrollment.enrollmentSealKeyVersion:!1;default:return rn(e)}}function rn(e){throw Error(`unsupported wallet recovery projection: ${String(e)}`)}function an(e){let t=q(e.payload.recoveryOperationId);switch(e.kind){case`passkey`:return we({kind:`passkey`,storeVersion:e.promotion.storeVersion,walletId:e.payload.walletId,recoveryOperationId:t,targetDeviceId:e.payload.targetDeviceId,targetAuthorityId:e.payload.targetAuthorityId,targetWalletAuthMethodId:e.payload.targetWalletAuthMethodId,authority:e.promotion.authority,authMethod:e.promotion.authMethod});case`google_email_otp`:{let n=a(e.payload.providerSubject);if(!n.ok)throw Error(`wallet recovery provider subject is invalid`);return we({kind:`google_email_otp`,storeVersion:e.promotion.storeVersion,walletId:e.payload.walletId,recoveryOperationId:t,targetDeviceId:e.payload.targetDeviceId,targetAuthorityId:e.payload.targetAuthorityId,targetWalletAuthMethodId:e.payload.targetWalletAuthMethodId,authority:e.promotion.authority,authMethod:e.promotion.authMethod,providerSubject:n.value,emailHashHex:e.payload.emailHashHex,registrationAuthorityId:e.payload.registrationAuthorityId,enrollment:mt(e.payload)})}}}function on(e){return e.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.possessionProof}))}function sn(e){return{id:e.registration.id,rawId:e.registration.rawId,type:e.registration.type,authenticatorAttachment:e.registration.authenticatorAttachment??void 0,response:{clientDataJSON:e.registration.response.clientDataJSON,attestationObject:e.registration.response.attestationObject,transports:[...e.registration.response.transports]},clientExtensionResults:{prf:{results:{first:void 0,second:void 0}}}}}async function cn(e){let{payload:t}=e;if(B(t)){let n=await ut({relayUrl:e.relayUrl,walletId:String(t.walletId),reservationId:String(t.reservationId),recoveryOperationId:q(t.recoveryOperationId),targetDeviceId:String(t.targetDeviceId),targetAuthorityId:String(t.targetAuthorityId),targetWalletAuthMethodId:String(t.targetWalletAuthMethodId),challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:sn(t),replacementEnvelope:t.replacementEnvelope,ecdsaMaterialPossessionProofs:on(t),fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`passkey`,payload:t,promotion:n}:n}let n=await qt({relayUrl:e.relayUrl,recoveryOperationId:q(t.recoveryOperationId),reservationId:t.reservationId,walletId:t.walletId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,expectedProviderSubject:t.providerSubject,expectedEmailHashHex:t.emailHashHex,expectedRegistrationAuthorityId:t.registrationAuthorityId,replacementEnvelope:t.replacementEnvelope,ecdsaMaterialPossessionProofs:on(t),emailOtpEnrollment:ln(t.enrollment),fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`google_email_otp`,payload:t,promotion:n}:n}function ln(e){return e.kind===`create`?{kind:`create`,material:e.material}:null}async function un(e){let{payload:t}=e;if(B(t)){let n=await dt({relayUrl:e.relayUrl,walletId:String(t.walletId),reservationId:String(t.reservationId),recoveryOperationId:q(t.recoveryOperationId),targetDeviceId:String(t.targetDeviceId),targetAuthorityId:String(t.targetAuthorityId),targetWalletAuthMethodId:String(t.targetWalletAuthMethodId),replacementId:t.replacementId,replacementEnvelope:t.replacementEnvelope,fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`passkey`,payload:t,promotion:n}:n}let n=await Jt({relayUrl:e.relayUrl,recoveryOperationId:q(t.recoveryOperationId),reservationId:t.reservationId,walletId:t.walletId,targetDeviceId:t.targetDeviceId,targetAuthorityId:t.targetAuthorityId,targetWalletAuthMethodId:t.targetWalletAuthMethodId,expectedProviderSubject:t.providerSubject,expectedEmailHashHex:t.emailHashHex,expectedRegistrationAuthorityId:t.registrationAuthorityId,replacementEnvelope:t.replacementEnvelope,fetchImpl:e.fetchImpl});return n.kind===`promoted`?{kind:`google_email_otp`,payload:t,promotion:n}:n}function dn(e){return e.kind===`passkey`||e.kind===`google_email_otp`}async function fn(e){let t=await un(e);return dn(t)||t.kind!==`refused`?t:await cn(e)}function pn(e,t){return{walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:t.target.credentialIdB64u},verifier:{kind:`webauthn`,rpId:t.target.rpId},bindingId:t.authMethod.walletAuthMethodId}}function mn(e,t){let n=he({walletId:e.walletId,provider:`google`,providerUserId:e.providerSubject,emailHashHex:e.emailHashHex});return{walletId:n.walletId,factor:n.factor,verifier:n.verifier,bindingId:t.authMethod.walletAuthMethodId}}async function hn(e,t){if(B(e)){if(t.kind!==`passkey`)throw Error(`wallet recovery projection branch changed`);return ve({authority:pn(e,t)})}if(t.kind!==`google_email_otp`)throw Error(`wallet recovery projection branch changed`);return ve({authority:mn(e,t)})}async function gn(e){let t=[],n=[];for(let r of e.payload.ecdsaKeySets){let i=r.entry,a=i.recoveryBasis,o=await ce({walletId:e.payload.walletId,signingRootId:a.signingRootId,signingRootVersion:a.signingRootVersion}),s=await Ee({authority:e.authority,chainTargets:a.chainTargets,walletId:String(e.payload.walletId),keyHandle:i.keyHandle,ecdsaThresholdKeyId:a.ecdsaThresholdKeyId,signingRootId:a.signingRootId,signingRootVersion:a.signingRootVersion,relayerKeyId:o,participantIds:a.participantIds,publicCapability:a.publicCapability,activationReceipt:a.activationReceipt,runtimePolicyScope:a.runtimePolicyScope,readyStateBlobB64u:r.readyStateBlobB64u,publicFacts:r.publicFacts});n.push(s);for(let n of a.chainTargets)t.push(_n({payload:e.payload,keySet:r,chainTarget:n,materialRef:s.roleLocalMaterialRef,relayerKeyId:o}))}return{walletKeys:t,ecdsaContinuity:n}}function _n(e){let t=e.keySet.entry,n=t.recoveryBasis,r=e.keySet.publicFacts,i=Se({walletId:e.payload.walletId,chainTarget:e.chainTarget,keyHandle:t.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,applicationBindingDigestB64u:n.publicCapability.context.application_binding_digest_b64u,clientParticipantId:1,relayerParticipantId:2,participantIds:n.participantIds,contextBinding32B64u:r.contextBinding32B64u,derivationClientSharePublicKey33B64u:r.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:r.relayerPublicKey33B64u,groupPublicKey33B64u:r.groupPublicKey33B64u,ethereumAddress:r.ethereumAddress,publicCapability:n.publicCapability});return{keyScope:`evm-family`,chainTarget:e.chainTarget,walletId:String(e.payload.walletId),evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,keyHandle:t.keyHandle,ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,thresholdEcdsaPublicKeyB64u:r.groupPublicKey33B64u,thresholdOwnerAddress:r.ethereumAddress,relayerKeyId:e.relayerKeyId,relayerVerifyingShareB64u:r.relayerPublicKey33B64u,participantIds:n.participantIds,publicCapability:n.publicCapability,roleLocalMaterialRef:e.materialRef,ecdsaRoleLocalPublicFacts:i}}function vn(e){if(e.nearKeySets.length!==1)throw Error(`wallet recovery requires exactly one NEAR key set`);return e.nearKeySets[0]}function yn(e){return[...e.registration.response.transports]}function bn(e){return`ed25519:${ae(g(vn(e).binding.registeredPublicKeyB64u))}`}function xn(t,n){let r=e(n.thresholdSessionId);if(!r.ok)throw Error(`recovery NEAR threshold session id is invalid`);return{walletId:t.walletId,nearAccountId:O(n.binding.nearAccountId),thresholdSessionId:r.value,runtimePolicyScope:n.runtimePolicyScope,materialActivation:de(n.materialActivation)}}async function Sn(e){if(B(e.payload)){if(e.projection.kind!==`passkey`)throw Error(`wallet recovery projection branch changed`);let t={walletId:e.payload.walletId,rpId:e.projection.target.rpId,credentialIdB64u:e.projection.target.credentialIdB64u,credentialPublicKeyB64u:e.projection.authMethod.credentialPublicKeyB64u,transports:yn(e.payload),walletKeys:e.walletKeys};if(e.payload.nearKeySets.length===0)return ke({kind:`evm_family_ecdsa`,...t});let n=vn(e.payload);return ke({kind:`near_ed25519`,...t,nearAccountId:O(n.binding.nearAccountId),nearEd25519SigningKeyId:n.binding.nearEd25519SigningKeyId,signerSlot:n.binding.signerSlot,operationalPublicKey:bn(e.payload),relayerKeyId:n.binding.signingWorkerId,participantIds:n.binding.participantIds,custodyMaterials:e.payload.nearKeySets.map(e=>({binding:e.binding,sealed:e.sealed}))})}if(e.projection.kind!==`google_email_otp`)throw Error(`wallet recovery projection branch changed`);let t=mn(e.payload,e.projection),n={walletId:e.payload.walletId,email:e.payload.verifiedEmail,registrationAuthorityId:e.payload.registrationAuthorityId,authority:t,walletKeys:e.walletKeys};if(e.payload.nearKeySets.length===0)return Ae({kind:`evm_family_ecdsa`,...n});let r=vn(e.payload);return Ae({kind:`near_ed25519`,...n,nearAccountId:O(r.binding.nearAccountId),nearEd25519SigningKeyId:r.binding.nearEd25519SigningKeyId,signerSlot:r.binding.signerSlot,operationalPublicKey:bn(e.payload),relayerKeyId:r.binding.signingWorkerId,participantIds:r.binding.participantIds,custodyMaterials:e.payload.nearKeySets.map(e=>({binding:e.binding,sealed:e.sealed}))})}async function Cn(e){let t=e.pending.projection,n=await hn(e.payload,t),r=await gn({payload:e.payload,authority:n}),i=await Sn({payload:e.payload,projection:t,walletKeys:r.walletKeys});await j.publishPendingWalletRecoveryCommit({pending:e.pending,authority:t.authority,authMethod:t.authMethod,registration:i,ecdsaContinuity:r.ecdsaContinuity,ed25519PublicCapabilityReferences:e.payload.nearKeySets.map(t=>xn(e.payload,t))})}async function wn(e){let t=await j.listPendingWalletRecoveryCommits(),n=[];for(let r of t)try{let t=await Rt(r),i=r.stage===`awaiting_server_promotion`?await fn({relayUrl:e.relayUrl,payload:t,fetchImpl:e.fetchImpl}):await un({relayUrl:e.relayUrl,payload:t,fetchImpl:e.fetchImpl});if(!dn(i)){if(i.kind===`refused`){await j.deletePendingWalletRecoveryCommit(r.recoveryOperationId),n.push({kind:`discarded`,recoveryOperationId:String(r.recoveryOperationId)});continue}n.push({kind:`pending`,recoveryOperationId:String(r.recoveryOperationId),failure:i});continue}let a=i,o=an(a),s=r.stage===`awaiting_server_promotion`?await j.advancePendingWalletRecoveryCommit({awaiting:r,promoted:Ut(r,a.payload,o,r.updatedAtMs+1)}):r;if(r.stage===`server_promoted`&&!await nn(r.projection,o))throw Error(`wallet recovery replay projection changed`);await Cn({pending:s,payload:a.payload}),n.push({kind:`completed`,recoveryOperationId:String(r.recoveryOperationId)})}catch(e){console.warn(`[SeamsWeb] pending wallet recovery replay failed before classification:`,String(r.recoveryOperationId),e instanceof Error?e.message:String(e||`unknown error`)),n.push({kind:`corrupt`,recoveryOperationId:String(r.recoveryOperationId)})}return n}async function Tn(e){let t=await Pt(e.operation);return{payload:t,pending:Ht(t,await Lt(t),e.nowMs)}}async function En(e){let t=an(e.promotion);return j.advancePendingWalletRecoveryCommit({awaiting:e.awaiting,promoted:Ut(e.awaiting,e.promotion.payload,t,e.awaiting.updatedAtMs+1)})}export{qt as a,B as c,Be as d,wn as i,ut as l,En as n,Kt as o,Cn as r,Gt as s,Tn as t,ze as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,o as t,u as n}from"./participants-BXdREC5k.js";import{i as r,n as i}from"./activeWalletSession-
|
|
1
|
+
import{c as e,o as t,u as n}from"./participants-BXdREC5k.js";import{i as r,n as i}from"./activeWalletSession-HAOgRKzn.js";import{d as a,h as o}from"./capabilityKinds-Cafn86Y1.js";const s=(e,t)=>globalThis.fetch(e,t),c=new WeakMap;let l=0;const u=new Map;function d(e){return JSON.stringify([e])}function f(e,t){return d(e.operationCredential.token)+JSON.stringify([n(e.relayerUrl),t.walletSessionId,t.quotaId])}function p(e,t,n,r){let i=c.get(e);i||(i=new Map,c.set(e,i));let a=i.get(t);if(a&&a.sequence>n)return r;if(u.delete(t),i.delete(t),i.set(t,{kind:`local_wallet_session_observation`,sequence:n,status:r}),i.size>32){let e=i.keys().next();e.done||i.delete(e.value)}return r}function m(e){let t=e.remainingUses-1;return t>0?{...e,remainingUses:t}:{...e,status:`exhausted`,remainingUses:0,quotaLifecycle:`exhausted`}}var h=class e{readsByFetch=new Map;suppliedStatus={kind:`remote`};static fromPrepare(t,n){let r=new e;return r.suppliedStatus={kind:`server_response`,key:f(t,n),status:n,observation:m(n)},r}static fromRegistration(t,n){let r=g(n),i=new e;return i.suppliedStatus={kind:`server_response`,key:f({relayerUrl:t,operationCredential:n.operationCredential},r),status:r,observation:r},i}static acceptRegistrationSession(e,t){let n=g(t);if(u.set(f({relayerUrl:e,operationCredential:t.operationCredential},n),n),u.size>8){let e=u.keys().next();e.done||u.delete(e.value)}}static forHostObservation(){let t=new e;return t.suppliedStatus={kind:`host_observation`},t}static forgetCredential(e){let t=d(e);for(let e of[c.get(s),u])if(e)for(let n of[...e.keys()])n.startsWith(t)&&e.delete(n)}invalidateCredential(t){let n=d(t);for(let e of this.readsByFetch.values())for(let t of e.keys())t.startsWith(n)&&e.delete(t);this.suppliedStatus={kind:`remote`},e.forgetCredential(t)}static observationForConfirmation(e,t){return c.get(e.fetchImpl??s)?.get(f(e,t))??null}read(e,t){if(this.suppliedStatus.kind===`server_response`){if(this.suppliedStatus.key!==f(e,t))throw Error(`Wallet Session response identity changed before reconciliation`);return p(e.fetchImpl??s,this.suppliedStatus.key,++l,this.suppliedStatus.observation),Promise.resolve(this.suppliedStatus.status)}let n=e.fetchImpl??s,r=this.readsByFetch.get(n);r||(r=new Map,this.readsByFetch.set(n,r));let i=f(e,t),a=r.get(i);if(a)return a;let o=++l,c=this.suppliedStatus.kind===`host_observation`?u.get(i):void 0,d=c?Promise.resolve(p(n,i,o,c)):D(e).read(t).then(p.bind(null,n,i,o));return r.set(i,d),d}};function g(e){return{status:`active`,walletSessionId:e.walletSessionId,quotaId:e.quotaId,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs,quotaLifecycle:`active`,authorization:e.walletSession}}const _=[`ok`,`status`,`walletSessionId`,`quotaId`,`remainingUses`,`expiresAtMs`,`quotaLifecycle`,`authorization`],v=[`ok`,`status`,`walletSessionId`,`quotaId`];function y(e){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return{kind:`error`,message:null};let t=new Map(Object.entries(e)),n=[...t.keys()],r=t.get(`status`),i=t.get(`walletSessionId`),a=t.get(`quotaId`);if(t.get(`ok`)===!0&&typeof r==`string`){let e=r===`active`||r===`exhausted`||r===`expired`||r===`superseded`||r===`authority_unavailable`||r===`method_unavailable`||r===`capability_unavailable`?r:null;if(e&&n.length===_.length){let r=new Set(_);if(n.every(e=>r.has(e)))return{kind:`observed`,status:e,walletSessionId:i,quotaId:a,remainingUses:t.get(`remainingUses`),expiresAtMs:t.get(`expiresAtMs`),quotaLifecycle:t.get(`quotaLifecycle`),authorization:t.get(`authorization`)}}if((r===`missing`||r===`invalid`)&&n.length===v.length){let e=new Set(v);if(n.every(t=>e.has(t)))return{kind:`terminal`,status:r,walletSessionId:i,quotaId:a}}}if(n.every(e=>e===`code`||e===`message`)){let e=t.get(`message`);return{kind:`error`,message:typeof e==`string`?e:null}}return{kind:`error`,message:null}}function b(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function x(e,t){let n=o(e.walletSessionId),r=a(e.quotaId);return!n.ok||!r.ok||n.value!==t.walletSessionId||r.value!==t.quotaId?null:{walletSessionId:n.value,quotaId:r.value}}function S(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function C(e,t){if(e.quotaLifecycle!==`active`&&e.quotaLifecycle!==`exhausted`||!S(e.remainingUses)||e.quotaLifecycle===`exhausted`!=(e.remainingUses===0)||!b(e.expiresAtMs))return null;let n;try{n=i(e.authorization)}catch{return null}return n.quotaId!==t.quotaId||n.expiresAtMs!==e.expiresAtMs?null:{remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs,quotaLifecycle:e.quotaLifecycle,authorization:n}}function w(e,t){return T(y(e),t)}function T(e,t){if(e.kind===`error`)return null;let n=x(e,t);if(!n)return null;if(e.kind===`terminal`)return{status:e.status,...n};switch(e.status){case`active`:{let t=C(e,n);return!t||t.quotaLifecycle!==`active`?null:{status:`active`,...n,...t}}case`exhausted`:{let t=C(e,n);return!t||t.remainingUses!==0?null:{status:`exhausted`,...n,...t,remainingUses:0}}case`expired`:case`superseded`:case`authority_unavailable`:case`method_unavailable`:case`capability_unavailable`:{let t=C(e,n);return t?{status:e.status,...n,...t}:null}default:return null}}var E=class{relayerUrl;operationCredential;fetchImpl;constructor(e){if(this.relayerUrl=n(e.relayerUrl),!this.relayerUrl)throw Error(`Relayer URL is required`);this.operationCredential=r(e.operationCredential),this.fetchImpl=e.fetchImpl??s}async read(n){let r=await this.fetchImpl(`${this.relayerUrl}/wallet/session/status`,{...t({body:{walletSessionId:n.walletSessionId,quotaId:n.quotaId},headers:e(this.operationCredential)}),credentials:`omit`}),i=y(await r.json().catch(()=>null));if(!r.ok){let e=i.kind===`error`&&i.message?i.message:`Wallet Session status request failed with HTTP ${r.status}`;throw Error(e)}let a=T(i,n);if(!a)throw Error(`Wallet Session status response is invalid`);return a}};function D(e){return new E(e)}export{D as n,w as r,h as t};
|