@seams/wallet 0.21.0 → 0.22.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/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/TransactionReceipt.js +107 -43
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/mountConfirmationSurface.js +1 -1
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-receipt.js +36 -6
- package/dist/esm/core/ui/messages.js +9 -14
- package/dist/esm/react/components/AccountMenuButton/ProfileDropdown.js +23 -9
- package/dist/esm/react/components/AccountMenuButton/TransactionSettingsSection.css +376 -84
- package/dist/esm/react/components/AccountMenuButton/TransactionSettingsSection.js +87 -167
- package/dist/esm/react/components/AccountMenuButton/WalletRegionSection.js +11 -9
- package/dist/esm/react/components/AccountMenuButton/WalletSettingsLayout.css +76 -74
- package/dist/esm/react/components/AccountMenuButton/WalletSettingsLayout.js +23 -22
- package/dist/esm/react/components/AccountMenuButton/Web3AuthProfileButton.css +1 -5
- package/dist/esm/react/components/AccountMenuButton/icons/MapPinIcon.js +12 -0
- package/dist/esm/react/components/AccountMenuButton/index.js +2 -1
- package/dist/esm/react/styles/styles.css +452 -162
- package/dist/{public/sdk/ConfirmationDrawer-B7RCp58z.js → esm/sdk/ConfirmationDrawer-Ck33ZmU-.js} +1 -1
- package/dist/esm/sdk/adapters-CgJpSAxH.js +2 -0
- package/dist/esm/sdk/appearance-token-vars-BA3KQyEE.js +2 -0
- package/dist/esm/sdk/{export-viewer-host-CVdpEuY6.js → export-viewer-host-C9n-62Pi.js} +1 -1
- package/dist/esm/sdk/{exportKeypairOperation-gVCqLrDl.js → exportKeypairOperation-Du9HKB8f.js} +1 -1
- package/dist/esm/sdk/{host-Bz7mRJPZ.js → host-DoftJdVQ.js} +1 -1
- package/dist/esm/sdk/{localOnly-TXaYAZj-.js → localOnly-CvFSZFUy.js} +1 -1
- package/dist/esm/sdk/{mountExportPrivateKeySurface-DUnKOBQr.js → mountExportPrivateKeySurface-DdJHWwqY.js} +1 -1
- package/dist/esm/sdk/{mountRecoveryCodeBackupSurface-MGTl6FhG.js → mountRecoveryCodeBackupSurface-D3QFgMGE.js} +1 -1
- package/dist/{public/sdk/pendingWalletRecoveryCodeBackup-DWeemdJv.js → esm/sdk/pendingWalletRecoveryCodeBackup-LbstFwcY.js} +1 -1
- package/dist/esm/sdk/{registration-DVX_lnP7.js → registration-CIxJvbTo.js} +1 -1
- package/dist/esm/sdk/{registration-DeCUrUR9.js → registration-CeOmKyCG.js} +1 -1
- package/dist/esm/sdk/{runtime-auth-BAGyfscG.js → runtime-auth-C0V-5znH.js} +1 -1
- package/dist/{public/sdk/runtime-device-link-DKkMLVor.js → esm/sdk/runtime-device-link-B1jpHQSF.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-0TAVH1xg.js → esm/sdk/runtime-ecdsa-tempo-CDSZ3pxS.js} +1 -1
- package/dist/esm/sdk/{runtime-email-otp-DoHa8Hif.js → runtime-email-otp-DXuxFOjL.js} +1 -1
- package/dist/esm/sdk/{runtime-export-CAt17IFH.js → runtime-export-Ba12ChDI.js} +1 -1
- package/dist/esm/sdk/{runtime-near-BQX9Jk9Z.js → runtime-near-DRrdWzmr.js} +1 -1
- package/dist/esm/sdk/{runtime-preferences-BuKTIpv6.js → runtime-preferences-BWyhRaBA.js} +1 -1
- package/dist/esm/sdk/{runtime-recovery-DyxJKKNw.js → runtime-recovery-DlJlaZlf.js} +1 -1
- package/dist/esm/sdk/{runtime-recovery-codes-CWmt0FDB.js → runtime-recovery-codes-CuqYWqK7.js} +1 -1
- package/dist/esm/sdk/{shared-BVps1f3F.js → shared-B95wnpoD.js} +1 -1
- package/dist/esm/sdk/transaction-activity-CpDMkSPm.js +1 -0
- package/dist/esm/sdk/tx-confirm-ui.js +186 -71
- 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-ui.css +1 -1
- package/dist/{public/sdk/walletRecoveryAdminProof-CIoLawfC.js → esm/sdk/walletRecoveryAdminProof-CtH8_lph.js} +1 -1
- package/dist/public/headers.manifest.json +1 -1
- package/dist/{esm/sdk/ConfirmationDrawer-B7RCp58z.js → public/sdk/ConfirmationDrawer-Ck33ZmU-.js} +1 -1
- package/dist/public/sdk/adapters-CgJpSAxH.js +2 -0
- package/dist/public/sdk/appearance-token-vars-BA3KQyEE.js +2 -0
- package/dist/public/sdk/{export-viewer-host-CVdpEuY6.js → export-viewer-host-C9n-62Pi.js} +1 -1
- package/dist/public/sdk/{exportKeypairOperation-gVCqLrDl.js → exportKeypairOperation-Du9HKB8f.js} +1 -1
- package/dist/public/sdk/{host-Bz7mRJPZ.js → host-DoftJdVQ.js} +1 -1
- package/dist/public/sdk/{localOnly-TXaYAZj-.js → localOnly-CvFSZFUy.js} +1 -1
- package/dist/public/sdk/{mountExportPrivateKeySurface-DUnKOBQr.js → mountExportPrivateKeySurface-DdJHWwqY.js} +1 -1
- package/dist/public/sdk/{mountRecoveryCodeBackupSurface-MGTl6FhG.js → mountRecoveryCodeBackupSurface-D3QFgMGE.js} +1 -1
- package/dist/{esm/sdk/pendingWalletRecoveryCodeBackup-DWeemdJv.js → public/sdk/pendingWalletRecoveryCodeBackup-LbstFwcY.js} +1 -1
- package/dist/public/sdk/{registration-DVX_lnP7.js → registration-CIxJvbTo.js} +1 -1
- package/dist/public/sdk/{registration-DeCUrUR9.js → registration-CeOmKyCG.js} +1 -1
- package/dist/public/sdk/{runtime-auth-BAGyfscG.js → runtime-auth-C0V-5znH.js} +1 -1
- package/dist/{esm/sdk/runtime-device-link-DKkMLVor.js → public/sdk/runtime-device-link-B1jpHQSF.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-0TAVH1xg.js → public/sdk/runtime-ecdsa-tempo-CDSZ3pxS.js} +1 -1
- package/dist/public/sdk/{runtime-email-otp-DoHa8Hif.js → runtime-email-otp-DXuxFOjL.js} +1 -1
- package/dist/public/sdk/{runtime-export-CAt17IFH.js → runtime-export-Ba12ChDI.js} +1 -1
- package/dist/public/sdk/{runtime-near-BQX9Jk9Z.js → runtime-near-DRrdWzmr.js} +1 -1
- package/dist/public/sdk/{runtime-preferences-BuKTIpv6.js → runtime-preferences-BWyhRaBA.js} +1 -1
- package/dist/public/sdk/{runtime-recovery-DyxJKKNw.js → runtime-recovery-DlJlaZlf.js} +1 -1
- package/dist/public/sdk/{runtime-recovery-codes-CWmt0FDB.js → runtime-recovery-codes-CuqYWqK7.js} +1 -1
- package/dist/public/sdk/{shared-BVps1f3F.js → shared-B95wnpoD.js} +1 -1
- package/dist/public/sdk/transaction-activity-CpDMkSPm.js +1 -0
- package/dist/public/sdk/tx-confirm-ui.js +186 -71
- 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-ui.css +1 -1
- package/dist/{esm/sdk/walletRecoveryAdminProof-CIoLawfC.js → public/sdk/walletRecoveryAdminProof-CtH8_lph.js} +1 -1
- package/dist/public/wallet-assets.manifest.json +50 -50
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/controller.d.ts +2 -0
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/ui/transaction-activity.d.ts +2 -2
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/ui/transaction-receipt.d.ts +25 -6
- package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
- package/dist/types/wallet/src/react/components/AccountMenuButton/icons/MapPinIcon.d.ts +2 -0
- package/package.json +1 -1
- package/dist/esm/react/components/AccountMenuButton/SegmentedControl.js +0 -77
- package/dist/esm/sdk/adapters-La60hveX.js +0 -2
- package/dist/esm/sdk/appearance-token-vars-Bu6YUWmf.js +0 -2
- package/dist/esm/sdk/transaction-activity-D5f-Yn9t.js +0 -1
- package/dist/public/sdk/adapters-La60hveX.js +0 -2
- package/dist/public/sdk/appearance-token-vars-Bu6YUWmf.js +0 -2
- package/dist/public/sdk/transaction-activity-D5f-Yn9t.js +0 -1
- package/dist/types/wallet/src/react/components/AccountMenuButton/SegmentedControl.d.ts +0 -25
package/dist/public/sdk/{exportKeypairOperation-gVCqLrDl.js → exportKeypairOperation-Du9HKB8f.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./domainIds-C3fUa33Q.js";import{c as t}from"./chains-CPmd4s9f.js";import{t as n}from"./activeWalletSession-BtEHhe99.js";import{r}from"./secureRandomId-8LSc91aN.js";import"./walletDbName-BVZhb4xF.js";import"./signingSessionSeal-DqbjG8c8.js";import"./capabilityKinds-CqHVzVsJ.js";import{o as i}from"./canonicalPrimitives-D_1HyEuJ.js";import{i as a,t as o}from"./errors-CI1xdN0d.js";import{d as s,t as c}from"./accountIds-BzZs7YoX.js";import{c as l,o as u,s as ee,u as d}from"./ecdsaChainTarget-svSlzhze.js";import"./signerDomain-YEHkugWX.js";import"./presignatures-DGLNs29C.js";import"./walletCapabilityBindings-CKOK39sP.js";import{Nt as f,Pt as p,St as te,a as m,g as h,ln as ne,un as re,zt as g}from"./emailOtpEcdsaDerivationIdentity-DreNrM6n.js";import{i as ie}from"./walletAuthMethodRecord-Cv_MYpxt.js";import"./signerSlot-CpyIfl3J.js";import{a as ae,n as _,u as oe}from"./sdkSentEvents-BzMVO1AR.js";import{s as se}from"./types-BrEW276O.js";import{i as ce}from"./helpers-BXezXx19.js";import{C as le,D as v,b as ue,j as de,x as fe}from"./nearEd25519YaoSigningPreparation-BgCxoh9S.js";import{l as y,u as pe}from"./trace-CWTzEALZ.js";import{n as me,r as he,t as ge,v as _e}from"./ecdsaDerivationExport-DrFESeRP.js";import{t as ve}from"./challengeDelivery-C88JNwKf.js";import{i as ye}from"./walletSessionFailure-Ct412mDZ.js";import{i as be,n as xe,r as Se,s as Ce}from"./signingQueue-Cj9sCJLj.js";import{h as b,i as x,l as we,n as Te,s as S}from"./clientSessionPersistenceState-DFGHXoKK.js";import{t as C}from"./types-BNUuaUtl.js";import{i as w}from"./appearance-ZGVLwA4N.js";import{n as T,t as E}from"./export-viewer-host-CVdpEuY6.js";function D(e){return e.chainTarget.kind}function Ee(e){return e}function De(e){return!e||e.curve!==`ecdsa`||!e.chainTarget||!b(e)||!String(e.publicFacts.keyHandle||``).trim()?!1:e.source===`active_wallet_authority`?e.runtime.requiredCapability===`export_keys`&&e.state===`deferred`&&e.authorizationState===`authorization_required`:e.authorization?!0:e.state===`deferred`}function O(e){if(e.length!==2)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set must contain two parties`);let t=e[0],n=e[1];if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<=0||n<=0||t===n)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set is invalid`);return[t,n]}function k(t){let{exportLane:n,label:r}=t,i=n.capability,a=i.manifest.signer;if(a.walletId!==n.key.walletId||!a.scope.targetMemberships.some(e=>ee(e,n.chainTarget)))throw Error(`[SigningEngine][ecdsa-export] ${r} capability target mismatch`);if(!t.authMatches())throw Error(`[SigningEngine][ecdsa-export] ${r} capability auth mismatch`);if(!e(i.manifest.activation.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] ${r} material activation mismatch`);m({expected:n.publicFacts,actual:a.registeredPublicFacts,context:`canonical ${r} export lane`});let o=i.material.publicFacts;if(o.walletId!==a.walletId||String(o.keyHandle)!==String(n.publicFacts.keyHandle)||String(o.groupPublicKey33B64u)!==String(n.publicFacts.publicKeyB64u)||String(o.ethereumAddress)!==String(n.publicFacts.thresholdOwnerAddress)||o.participantIds.length!==n.publicFacts.participantIds.length||o.participantIds.some((e,t)=>e!==n.publicFacts.participantIds[t]))throw Error(`[SigningEngine][ecdsa-export] canonical ${r} export material mismatch`);let s=i.manifest.durableMaterial,c=s.runtimePolicyScope,l=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!c)throw Error(`[SigningEngine][ecdsa-export] ${r} runtime policy scope is missing`);if(!l)throw Error(`[SigningEngine][ecdsa-export] ${r} export relayer URL is missing`);return{durable:s,runtimePolicyScope:c,relayerUrl:l}}function Oe(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!f(r))throw Error(`[SigningEngine][ecdsa-export] Email OTP capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`Email OTP`,authMatches:()=>t.laneIdentity.auth.kind===`email_otp`&&t.laneIdentity.auth.providerSubjectId===r.factor.providerUserId});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,persistedMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o,authorization:{kind:`fresh_operation_authorization_required`,authority:r}}}function ke(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!p(r))throw Error(`[SigningEngine][ecdsa-export] passkey capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`passkey`,authMatches:()=>t.laneIdentity.auth.kind===`passkey`&&t.laneIdentity.auth.credentialIdB64u===r.factor.credentialIdB64u});return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,publicCapability:i.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o}}function Ae(t){let{exportLane:n,resolution:r}=t;if(n.laneIdentity.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(r.runtime.authBinding.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime authority mismatch`);if(n.laneIdentity.auth.providerSubjectId!==r.runtime.authBinding.providerSubjectId)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] Email OTP material activation mismatch`);let i=r.runtime.runtimePolicyScope;if(!i)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime policy scope is missing`);let a=be({authority:r.manifest.signer.authority,materialActivation:r.manifest.activation.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:n.chainTarget,publicFacts:n.publicFacts,runtimePolicyScope:i,persistedMaterial:a,normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl,authorization:{kind:`fresh_operation_authorization_required`,authority:r.runtime.authBinding.emailOtpAuthority}}}function je(t){let{exportLane:n}=t,r=n.runtime;if(r.requiredCapability!==`export_keys`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority lane lacks export_keys capability`);if(r.walletId!==n.key.walletId)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority wallet mismatch`);if(!e(r.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority material activation mismatch`);m({expected:n.publicFacts,actual:r.publicFacts,context:`active Wallet Authority ECDSA export lane`});let i=r.normalSigning,a=i.scope;if(a.wallet_id!==String(r.walletId)||a.ecdsa_threshold_key_id!==r.ecdsaThresholdKeyId||a.public_identity.threshold_public_key33_b64u!==r.publicFacts.publicKeyB64u||!e(ne(a.material_activation),r.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority normal-signing identity mismatch`);let o=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!o)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority export relayer URL is missing`);let s=O(r.publicFacts.participantIds);if(r.auth.kind===`passkey`){if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);if(r.factorAuthority.factor.credentialIdB64u!==r.auth.credentialIdB64u||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active passkey factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`passkey`}}if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);if(r.factorAuthority.factor.providerUserId!==r.auth.providerSubjectId||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_email_otp_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`email_otp`}}async function A(e,t){if(t.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority Email OTP material uses its holder runtime`);if(t.authMethod!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] fresh Email OTP export requires Email OTP lane`);let n=await e.resolveActiveEcdsaCapabilityRuntime({walletId:t.key.walletId,chainTarget:t.chainTarget});if(n.kind===`blocked`&&n.reason===`missing_material`)return Oe({deps:e,exportLane:t});if(n.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] Email OTP capability runtime unavailable: ${n.reason}`);return Ae({exportLane:t,resolution:n})}async function j(t,n){if(n.source===`active_wallet_authority`)return je({deps:t,exportLane:n});if(n.authMethod===`email_otp`)return await A(t,n);let r=await t.resolveActiveEcdsaCapabilityRuntime({walletId:n.key.walletId,chainTarget:n.chainTarget});if(r.kind===`blocked`&&r.reason===`missing_material`)return ke({deps:t,exportLane:n});if(r.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] passkey capability runtime unavailable: ${r.reason}`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] passkey material activation mismatch`);if(r.runtime.authBinding.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] passkey authority binding mismatch`);let i=r.manifest.signer.registeredPublicFacts;m({expected:n.publicFacts,actual:i,context:`canonical passkey export lane`});let a=r.runtime.runtimePolicyScope;if(!a)throw Error(`[SigningEngine][ecdsa-export] durable passkey export requires runtimePolicyScope`);return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:i,runtimePolicyScope:a,publicCapability:r.manifest.durableMaterial.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:be({authority:r.manifest.signer.authority,materialActivation:r.manifest.durableMaterial.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts}),normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl}}function Me(e){return r(e,32,`Email OTP export UI request IDs`)}function Ne(e){switch(e.kind){case`near_account`:return String(c(e.nearAccountId));case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return t}default:return e}}function Pe(e){switch(e.kind){case`near_account`:if(!String(e.walletId||``).trim())throw Error(`Email OTP NEAR export requires wallet identity`);return{kind:`near_wallet`,walletId:String(e.walletId).trim(),nearAccountId:String(c(e.nearAccountId))};case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return{kind:`evm_wallet`,walletId:t}}default:return e}}function Fe(e){return{challengeId:e.challenge.challengeId,...e.challenge.emailHint?{emailHint:e.challenge.emailHint}:{},title:`Enter email code to export`,body:`This one-time code authorizes private key export only.`,helperText:`Enter the 6-digit code sent to your email`,onResend:e.onResend}}async function M(e){let t=Ne(e.identity),n=async()=>{let t=await e.challengeSource.requestChallenge(),n=String(t.challengeId||``).trim();if(!n)throw Error(`Email OTP export challenge response did not include challengeId`);let r=String(t.emailHint||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include emailHint`);let i={challengeId:n,emailHint:r,delivery:t.delivery};return e.onChallenge?.(i),i},r=await n(),i=Fe({challenge:r,onResend:async()=>(r=await n(),r)}),a=Pe(e.identity),o=await e.confirmer.requestUserConfirmation({requestId:Me(`export-${e.curve}-email-otp-auth`),type:w.SIGN_INTENT_DIGEST,summary:{operation:`Export Private Key`,accountId:t,publicKey:e.publicKey,warning:`Enter the email code to export this key. Anyone with the private key can fully control the account.`},payload:{signingSubject:a,challengeB64u:r.challengeId,signingAuthPlan:{kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:i},emailOtpPrompt:i},intentDigest:`export-keys:${t}:${e.chain}:${e.curve}:email-otp`});if(!o.confirmed)throw Error(o.error||`User cancelled Email OTP export request`);let s=String(o.otpCode||``).replace(/\D/g,``).slice(0,6);if(s.length!==6)throw Error(`Email OTP export requires a 6-digit code`);return{challengeId:String(o.emailOtpChallengeId||r.challengeId).trim(),otpCode:s}}function N(e){throw Error(`[SigningEngine][export] unsupported authorization identity: ${String(e)}`)}function Ie(e){throw Error(`[SigningEngine][export] unsupported step-up method: ${String(e)}`)}function Le(e){let t=String(e.walletSessionUserId||``).trim();if(!t)throw Error(`[SigningEngine][export] missing export step-up authorization identity`);let n=String(e.publicKey||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export step-up authorization public key`);switch(e.curve){case`ecdsa`:return{walletSessionUserId:t,publicKey:n,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.chain};case`ed25519`:{let r={walletSessionUserId:t,publicKey:n,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:String(e.nearAccountId||``).trim(),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId||``).trim(),signerSlot:Number(e.signerSlot)};if(!r.nearAccountId||!r.nearEd25519SigningKeyId||!Number.isSafeInteger(r.signerSlot)||r.signerSlot<1)throw Error(`[SigningEngine][export] Ed25519 export authorization identity is invalid`);return r}default:return N(e)}}function Re(e){let t={kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:e.emailOtpPrompt},n=e.emailOtpPrompt.emailHint;switch(e.identity.curve){case`ecdsa`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain,...n?{emailHint:n}:{}};case`ed25519`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot,...n?{emailHint:n}:{}};default:return N(e.identity)}}function ze(e){let t={kind:C.PasskeyReauth,method:`passkey`};switch(e.identity.curve){case`ecdsa`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain};case`ed25519`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot};default:return N(e.identity)}}function P(e){let t=Le(e);switch(e.method){case`email_otp`:{if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled Email OTP export request`);let n=String(e.decision.otpCode||``).replace(/\D/g,``).slice(0,6);if(n.length!==6)throw Error(`Email OTP export requires a 6-digit code`);let r=String(e.decision.emailOtpChallengeId||e.emailOtpPrompt.challengeId||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include challengeId`);return Re({identity:t,emailOtpPrompt:e.emailOtpPrompt,challengeId:r,otpCode:n})}case`passkey`:if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled export request`);if(!e.decision.credential)throw Error(`[SigningEngine][export] missing WebAuthn credential for export authorization`);return ze({identity:t,credential:ce(e.decision.credential)});default:return Ie(e)}}function Be(e){switch(e.kind){case`ecdsa`:return{subject:`${String(e.walletSession.walletId)}:${u(e.chainTarget)}`,chain:e.chainTarget.kind,data:{curve:`ecdsa`,chain:e.chainTarget.kind,chainTarget:e.chainTarget}};case`ed25519`:return{subject:`${String(e.walletSession.walletId)}:near:${String(e.nearAccount.accountId)}`,chain:`near`,data:{curve:`ed25519`,chain:`near`,nearAccount:e.nearAccount}}}}function F(e,t){if(e)try{e(oe(t))}catch{}}function I(e){return r(e,32,`key export UI request IDs`)}function Ve(e,t){return`key-export:${e}:${t}:${I(`flow`)}`}async function He(e,t){let n=Be(e),r=Ve(n.subject,n.chain),i=e.walletSession.walletId,s=n.data;F(e.options.onEvent,{phase:_.STEP_01_STARTED,status:`running`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`none`},data:s});try{return await t({...e,flowId:r})}catch(t){let n=a(t);throw F(e.options.onEvent,{phase:n?_.CANCELLED:_.FAILED,status:n?`cancelled`:`failed`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`hide`},error:{message:o(t)||(n?`Key export cancelled`:`Key export failed`)},data:s}),t}}async function Ue(e,t){return await e.requestExportChallenge({kind:`wallet_login_challenge`,walletSession:t.walletSession,chain:t.chain})}function L(e,t){let n=e.kind===`email_otp_ed25519_export_auth`?e.walletId:e.walletSession.walletSessionUserId;F(e.onEvent,{phase:_.STEP_02_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,flowId:e.flowId,accountId:String(n),authMethod:`email_otp`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:t.emailHint,demoOtpCode:ve(t.delivery)}})}async function R(e,t){let n=t.walletSession.walletSessionUserId,r=await M({identity:{kind:`wallet_session`,walletId:n},chain:t.chain,publicKey:t.publicKey,curve:t.curve,challengeSource:{requestChallenge:async()=>await Ue(e,t)},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),i={challengeId:r.challengeId},a={confirmed:!0,otpCode:r.otpCode,emailOtpChallengeId:r.challengeId},o=P({method:`email_otp`,walletSessionUserId:n,chain:t.chain,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,emailOtpPrompt:i,decision:a});if(o.kind!==`email_otp`)throw Error(`[SigningEngine][export] Email OTP export returned the wrong step-up method`);return o}async function We(e,t){let n=await M({identity:{kind:`near_account`,walletId:t.walletId,nearAccountId:t.nearAccountId},chain:`near`,publicKey:t.publicKey,curve:`ed25519`,challengeSource:{requestChallenge:async()=>await e.requestExportChallenge({kind:`wallet_export_challenge`,walletId:t.walletId,chain:`near`})},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),r=P({method:`email_otp`,walletSessionUserId:t.walletId,publicKey:t.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,emailOtpPrompt:{challengeId:n.challengeId},decision:{confirmed:!0,otpCode:n.otpCode,emailOtpChallengeId:n.challengeId}});if(r.kind!==`email_otp`||r.curve!==`ed25519`)throw Error(`[SigningEngine][export] Ed25519 Email OTP export authorization changed kind`);return r}async function z(e,t){let n=t.state===`loading`,r=[{scheme:`ed25519`,label:`NEAR Ed25519 private key`,publicKey:t.publicKey,privateKey:n?``:t.privateKey}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-ed25519-yao-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.nearAccountId,publicKey:t.publicKey,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`near_wallet`,nearAccountId:t.nearAccountId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKey,keys:r,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:n,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`,loading:n}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}},intentDigest:`export-keys:${t.walletId}:near:${t.nearAccountId}:ed25519`})}async function B(e,t){let n=t.chainTarget.kind,r=String(t.walletSessionUserId||``).trim();if(!r)throw Error(`[SigningEngine][export] missing ECDSA export wallet session user id`);return await Ge(e,{walletSessionUserId:t.walletSessionUserId,intent:`ecdsa_export`,curve:`ecdsa`,chain:n,publicKey:t.publicKey,flowId:t.flowId,onEvent:t.onEvent,request:{requestId:I(`export-threshold-ecdsa-auth`),type:w.AUTHORIZE_KEY_EXPORT,summary:{operation:`Export Private Key`,accountId:r,publicKey:t.publicKey,warning:n===`tempo`?`Confirm to reveal your Tempo private key export.`:`Confirm to reveal your EVM private key export.`},payload:{subject:{kind:`evm_wallet`,walletId:r},credentialIdB64u:t.credentialIdB64u,publicKey:t.publicKey,...t.challengeB64u?{challengeB64u:t.challengeB64u}:{}},intentDigest:`export-keys:${r}:${u(t.chainTarget)}:secp256k1`}})}async function V(e,t){let n=t.chainTarget.kind,r=n===`tempo`?`Tempo`:`EVM`,i=t.state===`loading`,a=i?[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:``,address:t.ethereumAddress}]:[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:t.privateKeyHex,address:t.ethereumAddress}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-threshold-ecdsa-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.walletId,publicKey:t.publicKeyHex,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`evm_wallet`,walletId:t.walletId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKeyHex,keys:a,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:i,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:n,curve:`ecdsa`,loading:i}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`none`,overlay:`hide`},data:{chain:n,curve:`ecdsa`}})}},intentDigest:`export-keys:${t.walletId}:${u(t.chainTarget)}:secp256k1`})}async function Ge(e,t){let n=String(t.walletSessionUserId||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export account identity`);F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:t.intent,curve:t.curve}}),T();let r=await e.touchConfirm.requestUserConfirmation(t.request),i=P({method:`passkey`,walletSessionUserId:t.walletSessionUserId,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:t.chain,decision:r});if(i.kind!==`passkey`)throw Error(`[SigningEngine][export] passkey export returned the wrong step-up method`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`},data:{intent:t.intent,curve:t.curve}}),i}function Ke(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`}})}function qe(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`,...e.source?{source:e.source}:{}}})}async function Je(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.artifact.publicKeyHex||``).trim(),privateKeyHex:String(t.artifact.privateKeyHex||``).trim(),ethereumAddress:String(t.artifact.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function Ye(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.publicKey||``).trim(),ethereumAddress:String(t.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function H(t,n){let r=D(n.exportLane),i=I(`export-threshold-ecdsa-viewer-session`);Ke({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent});try{await Ye(t,{walletId:n.walletId,exportLane:n.exportLane,publicKey:n.exportPublicKey,ethereumAddress:n.exportLane.publicFacts.thresholdOwnerAddress,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent});let a=n.exportLane.laneIdentity.signer.materialActivation,o=await t.withThresholdEcdsaSigningQueue({queueKey:x({materialActivation:a}),walletId:n.exportLane.key.walletId,enabled:!0,task:async()=>{if(n.exportLane.source===`active_wallet_authority`){let e=n.activeRuntime;if(!e)throw Error(`[SigningEngine][ecdsa-export] active runtime is missing`);await et({ports:t.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e})}else if(n.exportLane.authMethod===`email_otp`){if(!e((await A(t.sessionStore,n.exportLane)).persistedMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}else{let r=await j(t.sessionStore,n.exportLane);if(r.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] prepared export authority changed`);if(!e(r.existingRoleLocalMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}return await n.prepareArtifact()}});return qe({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent}),E(i)&&await Je(t,{walletId:n.walletId,exportLane:n.exportLane,artifact:o,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent}),{accountId:String(n.walletId),exportedSchemes:[`secp256k1`]}}catch(e){throw T(),e}}function U(e){let t=e.laneIdentity.auth;if(t.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);return t}async function W(e){return i(t(e))}async function G(e){let t=u(e.chainTarget);return await Se({walletId:e.walletId,operationKind:`evm.export_key`,operationId:e.requestId,operationDigests:{laneDigest:await W({walletId:e.walletId,chainTarget:t,materialActivation:e.materialActivation,keyHandle:e.keyHandle}),intentDigest:await W({operation:`explicit_key_export`,requestId:e.requestId,walletId:e.walletId,chainTarget:t}),displayDigest:await W({operation:`Export Private Key`,publicKey:e.displayPublicKey,address:e.displayAddress})},materialActivation:e.materialActivation,normalSigningScope:e.operationRuntime.normalSigning.scope,keyHandle:e.keyHandle,relayerKeyId:e.operationRuntime.relayerKeyId,participantIds:[Number(e.operationRuntime.participantIds[0]),Number(e.operationRuntime.participantIds[1])],expiresAtMs:e.operationExpiresAtMs})}async function K(e){return await G({walletId:e.walletId,chainTarget:e.chainTarget,requestId:e.requestId,keyHandle:e.keyHandle,displayPublicKey:e.displayPublicKey,displayAddress:e.displayAddress,materialActivation:e.materialActivation,operationRuntime:e.operationRuntime,operationExpiresAtMs:e.operationExpiresAtMs})}async function Xe(t){let n=await j(t.deps.sessionStore,t.exportLane);if(n.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] passkey export authority changed`);if(!e(n.existingRoleLocalMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}async function Ze(t){if(!e((await A(t.deps.sessionStore,t.exportLane)).persistedMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}function Qe(e){if(!$e(e.expected,e.actual))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime was replaced after authorization`)}function $e(t,r){let i;switch(t.auth.kind){case`passkey`:i=r.auth.kind===`passkey`&&t.auth.rpId===r.auth.rpId&&t.auth.credentialIdB64u===r.auth.credentialIdB64u;break;case`email_otp`:i=r.auth.kind===`email_otp`&&t.auth.providerSubjectId===r.auth.providerSubjectId;break;default:return t.auth}return t.kind===r.kind&&t.walletId===r.walletId&&t.authorityId===r.authorityId&&t.walletAuthMethodId===r.walletAuthMethodId&&t.authorityDigestB64u===r.authorityDigestB64u&&t.factorAuthorityRef.kind===r.factorAuthorityRef.kind&&t.factorAuthorityRef.walletId===r.factorAuthorityRef.walletId&&t.factorAuthorityRef.authorityDigest===r.factorAuthorityRef.authorityDigest&&t.factorAuthorityRef.walletAuthMethodId===r.factorAuthorityRef.walletAuthMethodId&&t.authorityRevocationEpoch===r.authorityRevocationEpoch&&t.walletSessionId===r.walletSessionId&&t.requiredCapability===r.requiredCapability&&e(t.materialActivation,r.materialActivation)&&t.ecdsaThresholdKeyId===r.ecdsaThresholdKeyId&&t.relayerKeyId===r.relayerKeyId&&t.operationCredential.kind===r.operationCredential.kind&&t.operationCredential.token===r.operationCredential.token&&t.operationCredential.walletSessionId===r.operationCredential.walletSessionId&&n(t.session,r.session)&&ie(t.authMethod,r.authMethod)&&i&&g(t.factorAuthority,r.factorAuthority)&&t.holderRuntime.kind===r.holderRuntime.kind&&t.holderRuntime.walletId===r.holderRuntime.walletId&&t.holderRuntime.authorityId===r.holderRuntime.authorityId&&t.holderRuntime.walletAuthMethodId===r.holderRuntime.walletAuthMethodId&&g(t.holderRuntime.factorAuthority,r.holderRuntime.factorAuthority)&&e(t.holderRuntime.materialActivation,r.holderRuntime.materialActivation)&&t.holderRuntime.holderHandleId===r.holderRuntime.holderHandleId&&t.holderRuntime.ecdsaThresholdKeyId===r.holderRuntime.ecdsaThresholdKeyId&&te(t.normalSigning,r.normalSigning)}async function q(e){let t=await Ce({ports:e.ports,input:{walletId:e.expectedRuntime.walletId,requiredCapability:`export_keys`,materialActivation:e.expectedRuntime.materialActivation}});if(t.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime is ${t.reason}`);return Qe({expected:e.expectedRuntime,actual:t.runtime}),t.runtime}async function et(e){await q(e)}function J(e){let t=e.credential,n=String(t.rawId||t.id||``).trim();if(!n||n!==e.authority.factor.credentialIdB64u)throw Error(`[SigningEngine][ecdsa-export] passkey credential does not match authority`);return{kind:`passkey`,authority:e.authority,webauthn_authentication:{id:t.id,rawId:t.rawId,type:t.type,authenticatorAttachment:t.authenticatorAttachment??null,response:{clientDataJSON:t.response.clientDataJSON,authenticatorData:t.response.authenticatorData,signature:t.response.signature,userHandle:t.response.userHandle??null},clientExtensionResults:null}}}function Y(e){if(!f(e.authority))throw Error(`[SigningEngine][ecdsa-export] Email OTP material authority mismatch`);return{kind:`email_otp`,authority:e.authority,challenge_id:e.challengeId,otp_code:e.otpCode}}async function X(e){let t=await xe({relayerUrl:e.relayerUrl,transport:e.transport,request:{kind:`router_ab_ecdsa_operation_step_up_v1`,operation:e.prepared.operation,proof:e.proof}});if(t.operation_kind!==`evm.export_key`)throw Error(`[SigningEngine][ecdsa-export] operation step-up kind mismatch`);let n=t.authorization.evidence_set_digest,r=tt({proofKind:e.proof.kind,unseal:t.authorization.unseal});return{kind:`verified_step_up`,evidenceSetDigest:n,operation:e.prepared.operation,expiresAtMs:t.expires_at_ms,quotaUse:`none`,unseal:r,exportTopology:t.export_topology}}function tt(e){switch(e.proofKind){case`passkey`:if(e.unseal.kind!==`not_requested`)throw Error(`[SigningEngine][ecdsa-export] passkey step-up returned Email OTP unseal material`);return{kind:`not_requested`};case`email_otp`:if(e.unseal.kind!==`email_otp_grant`)throw Error(`[SigningEngine][ecdsa-export] Email OTP step-up did not return an unseal grant`);return{kind:`email_otp_grant`,grant:e.unseal.grant,challenge_id:e.unseal.challenge_id};default:{let t=e.proofKind;throw Error(`Unsupported ECDSA export step-up proof: ${String(t)}`)}}}async function nt(e,t){U(t.exportLane);let n=I(`tecdsa-export`),r=await K({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:n,keyHandle:t.material.existingRoleLocalMaterial.publicFacts.keyHandle,displayPublicKey:t.material.existingRoleLocalMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.existingRoleLocalMaterial.publicFacts.ethereumAddress,materialActivation:t.material.existingRoleLocalMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await B({touchConfirm:e.touchConfirm,theme:e.theme},{walletSessionUserId:t.walletId,credentialIdB64u:U(t.exportLane).credentialIdB64u,publicKey:t.exportPublicKey,chainTarget:t.exportLane.chainTarget,challengeB64u:r.challengeB64u,flowId:t.flowId,onEvent:t.onEvent});await Xe({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.existingRoleLocalMaterial.materialActivation});let a=t.exportLane.capability.authority;if(!p(a))throw Error(`[SigningEngine][ecdsa-export] exact Passkey capability authority changed`);let o=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:J({authority:a,credential:i.credential})});return{exportActivation:he({relayerUrl:t.material.relayerUrl,existingRoleLocalMaterial:t.material.existingRoleLocalMaterial,authorization:o}),credential:i.credential}}async function rt(e){let t=d({walletId:e.walletId,walletSessionUserId:e.walletId});return await e.deps.emailOtp.exportEcdsaKeyWithDurableAuthorization({walletSession:t,chainTarget:e.material.chainTarget,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode,publicFacts:e.material.publicFacts,runtimePolicyScope:e.material.runtimePolicyScope,authority:e.material.authorization.authority,persistedMaterial:e.persistedMaterial,explicitExportAuthorization:e.explicitExportAuthorization})}function Z(e){return{normalSigning:e.runtime.normalSigning,relayerKeyId:e.relayerKeyId,participantIds:e.participantIds}}function Q(e){return Math.min(Date.now()+5*6e4,e.session.expiresAtMs)}async function it(e){if(e.material.runtime.auth.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] active passkey runtime auth mismatch`);if(!p(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-passkey-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await B({touchConfirm:e.deps.touchConfirm,theme:e.deps.theme},{walletSessionUserId:e.walletId,credentialIdB64u:e.material.factorAuthority.factor.credentialIdB64u,publicKey:e.exportPublicKey,chainTarget:e.exportLane.chainTarget,challengeB64u:t.challengeB64u,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:J({authority:r.factorAuthority,credential:n.credential})})}}async function at(e){if(e.material.runtime.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] active Email OTP runtime auth mismatch`);if(!f(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-email-otp-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await R({touchConfirm:e.deps.touchConfirm,requestExportChallenge:e.deps.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:e.walletId,walletSessionUserId:e.walletId}),chain:D(e.exportLane),publicKey:e.exportPublicKey,curve:`ecdsa`,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:Y({authority:r.factorAuthority,challengeId:n.challengeId,otpCode:n.otpCode})})}}async function ot(e){switch(e.material.kind){case`active_wallet_authority_passkey_needs_authorization`:return await it({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});case`active_wallet_authority_email_otp_needs_authorization`:return await at({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});default:return st(e.material)}}function st(e){throw Error(`[SigningEngine][ecdsa-export] unsupported active wallet authority material: ${String(e)}`)}async function ct(e,t){let n=String(t.material.publicFacts.publicKeyB64u),r=await ot({deps:e,walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,activeRuntime:r.runtime,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await q({ports:e.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:r.runtime});return await ge({getSignerWorkerContext:e.getSignerWorkerContext},{runtime:n,operationAuthorization:r.authorization,relayerUrl:t.material.relayerUrl})}})}async function lt(e,t){let n=D(t.exportLane),r=await G({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:I(`tecdsa-email-otp-export`),keyHandle:t.material.persistedMaterial.publicFacts.keyHandle,displayPublicKey:t.material.persistedMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.persistedMaterial.publicFacts.ethereumAddress,materialActivation:t.material.persistedMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await R({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:t.walletId,walletSessionUserId:t.walletId}),chain:n,publicKey:String(t.material.publicFacts.publicKeyB64u),curve:`ecdsa`,flowId:t.flowId,onEvent:t.onEvent});await Ze({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.persistedMaterial.materialActivation});let a=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:Y({authority:t.material.authorization.authority,challengeId:i.challengeId,otpCode:i.otpCode})});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:String(t.material.publicFacts.publicKeyB64u),options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:rt.bind(void 0,{deps:e,walletId:t.walletId,material:t.material,authorization:i,persistedMaterial:t.material.persistedMaterial,explicitExportAuthorization:a})})}async function ut(e,t){if(t.exportLane.authMethod!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);let n=String(t.material.publicFacts.publicKeyB64u),r=await nt(e,{walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await e.provisionPasskeyEcdsaExplicitExportSession(r.exportActivation);return await me({getSignerWorkerContext:e.getSignerWorkerContext},{walletSessionUserId:t.walletId,exportProvision:n,factorAuthorization:{kind:`passkey`,passkeyCredentialIdB64u:String(r.credential.rawId||r.credential.id),credential:r.credential}})}})}function $(e){let t=e.source===`canonical_capability`?e.authorization:null;return{authMethod:S(e),curve:e.curve,chain:e.chainTarget.kind,chainTarget:e.chainTarget,state:e.state,source:e.source,...t?{remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}:{},updatedAtMs:e.updatedAtMs,evmFamilyKeyFingerprint:h({walletId:e.key.walletId,publicFacts:e.publicFacts})}}function dt(e,t){return String(e.key.walletId)===t.walletId?String(h({walletId:e.key.walletId,publicFacts:e.publicFacts})):``}function ft(e){if(!e.candidates.length)throw y(`evm-family`,{stage:`key_export.exact_lane_no_candidate`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: no_candidate`);for(let t of e.candidates)if(!dt(t,e.ecdsaContext))return pt(e);if(e.candidates.length!==1)return pt(e);let[t]=e.candidates;return pe(`evm-family`,{stage:`key_export.exact_lane_selected`,context:e.context,reason:`single_exact_candidate`,selectedLane:$(t),candidateCount:e.candidates.length}),t}function pt(e){throw y(`evm-family`,{stage:`key_export.exact_lane_ambiguous_material`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: ambiguous_material`)}function mt(e){return fe({signer:ue({walletId:e.lane.key.walletId,chainTarget:e.chainTarget||e.lane.chainTarget,keyHandle:e.lane.publicFacts.keyHandle,key:e.lane.key,materialActivation:e.lane.materialActivation}),auth:e.lane.auth})}function ht(e){return e.source===`active_wallet_authority`||e.state===`ready`?{kind:`loaded_worker_material`}:S(e)===`email_otp`?{kind:`material_pending`,reason:`email_otp_route_auth`}:{kind:`sealed_worker_material`}}function gt(e){if(e.lane.source===`active_wallet_authority`)return{chainTarget:e.chainTarget,authMethod:S(e.lane),material:{kind:`loaded_worker_material`},state:`deferred`};let t=S(e.lane),n=ht(e.lane);switch(e.lane.state){case`expired`:case`exhausted`:throw Error(`[SigningEngine][ecdsa-export] expired export lane requires durable public reauth authority`);case`ready`:case`deferred`:return{chainTarget:e.chainTarget,authMethod:t,material:n,state:e.lane.state}}}async function _t(e){let t=e.lane,n=mt({lane:t}),r=gt({lane:t,chainTarget:e.chainTarget});return t.source===`active_wallet_authority`?{curve:`ecdsa`,laneIdentity:n,source:`active_wallet_authority`,authorizationState:`authorization_required`,key:t.key,publicFacts:t.publicFacts,runtime:t.runtime,chainTarget:e.chainTarget,authMethod:S(t),material:{kind:`loaded_worker_material`},state:`deferred`}:t.authorization?{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorized`,authorization:t.authorization,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}:{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorization_required`,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}}function vt(e){return v(e.laneIdentity)===v(e.identity)}async function yt(e){return mt({lane:e})}function bt(e){return we(e.availableLanes,e.chainTarget).filter(e=>De(e))}async function xt(e,t){let n=bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:t.walletId,ecdsaChainTargets:[t.signingTarget]}),chainTarget:t.signingTarget}),r=[];for(let e of n)vt({laneIdentity:await yt(e),identity:t.laneIdentity})&&r.push(e);let i=ft({context:`ecdsa-export`,candidates:r,ecdsaContext:{walletId:t.walletId}});return await _t({lane:i,chainTarget:i.chainTarget})}async function St(e,t){switch(t.kind){case`ecdsa`:return await Ct(e,t);case`ed25519`:return await Dt(e,t)}}async function Ct(e,t){let n=String(l(t.walletSession.walletId));return{kind:`ecdsa`,laneIdentity:await yt(ft({context:`ecdsa-export-resolve`,candidates:bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[t.chainTarget]}),chainTarget:t.chainTarget}),ecdsaContext:{walletId:n}}))}}function wt(e){let t=e.lane.source===`durable_sealed_record`||e.lane.source===`public_capability_reference`;return String(e.lane.walletId)===e.walletId&&String(e.lane.nearAccountId)===e.nearAccountId&&t}function Tt(e){return le({signer:de({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:e.auth,thresholdSessionId:e.thresholdSessionId})}function Et(e){return[e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,se(e.auth)].map(e=>String(e)).join(`|`)}async function Dt(e,t){let n=String(l(t.walletSession.walletId)),r=String(t.nearAccount.accountId),i=await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[]}),a=i.lanes.ed25519.near;if(!b(a)||a.curve!==`ed25519`||!wt({lane:a,walletId:n,nearAccountId:r}))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: no_candidate`);let o=i.candidates.ed25519.near.filter(e=>b(e)&&e.curve===`ed25519`&&wt({lane:e,walletId:n,nearAccountId:r})),s=Et(a);if(o.some(e=>Et(e)!==s))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: ambiguous_material`);return{kind:`ed25519`,laneIdentity:Tt(a),materialActivation:a.materialActivation}}async function Ot(e,t){let n=await xt(e,{walletId:t.walletId,signingTarget:t.signingTarget,laneIdentity:t.laneIdentity});switch(n.material.kind){case`loaded_worker_material`:case`material_pending`:case`sealed_worker_material`:return n}throw n.material,Error(`[SigningEngine][ecdsa-export] unsupported material availability`)}function kt(e){return e.capability.materialActivation}function At(e){return e.material.materialActivation}function jt(e){return e.auth.kind===`passkey`}function Mt(e){if(!jt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires a passkey Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Nt(e){return e.auth.kind===`email_otp`}function Pt(e){if(!Nt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires an Email OTP Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Ft(e){let t=e.selected.signer,n=e.context.material;return String(t.account.wallet.walletId)===String(n.walletId)&&String(t.account.nearAccountId)===String(n.nearAccountId)&&String(t.nearEd25519SigningKeyId)===String(n.nearEd25519SigningKeyId)&&t.signerSlot===n.signerSlot&&String(e.selected.auth.rpId)===e.context.rpId&&e.selected.auth.credentialIdB64u===n.credentialIdB64u}function It(t){if(!Ft({selected:t.selectedLaneIdentity,context:t.context}))throw Error(`[SigningEngine][ed25519-export] durable Yao context identity mismatch`);let n=t.context.material;if(!e(t.selectedMaterialActivation,t.context.selectedLaneMaterialActivation))throw Error(`[SigningEngine][ed25519-export] durable Yao context activation mismatch`);let r=t.context.authorization.operationCredential.token;if(!r)throw Error(`[SigningEngine][ed25519-export] active Wallet Session authorization is unavailable`);let i=n.capability.lifecycle;return{laneIdentity:t.selectedLaneIdentity,relayerUrl:t.context.relayerUrl,walletSessionToken:r,walletCustodyEnvelope:t.context.walletCustodyEnvelope,capability:{materialActivation:n.capability.materialActivation,scope:{lifecycle_id:i.lifecycleId,root_share_epoch:i.rootShareEpoch,account_id:i.accountId,threshold_session_id:i.thresholdSessionId,signer_set_id:i.signerSetId,signing_worker_id:i.signingWorkerId,material_activation:re(n.capability.materialActivation)},applicationBinding:n.capability.applicationBinding,participantIds:n.capability.participantIds,registeredPublicKey:n.capability.registeredPublicKey,stateEpoch:n.capability.stateEpoch,activeCapabilityBinding:n.capability.activeCapabilityBinding,runtimePolicyScope:n.capability.runtimePolicyScope}}}async function Lt(e,t){let n=Mt(t),r=await e.resolvePasskeyExportContext({laneIdentity:n,materialActivation:t.materialActivation});switch(r.kind){case`ready`:return It({context:r.context,selectedLaneIdentity:n,selectedMaterialActivation:t.materialActivation});case`capability_recovery_required`:throw Error(`[SigningEngine][ed25519-export] passkey material recovery did not publish durable context`)}throw Error(`[SigningEngine][ed25519-export] unsupported passkey export context state`)}async function Rt(t,n){let r=Pt(n),i=await t.emailOtp.resolveExportContext({laneIdentity:r,materialActivation:n.materialActivation});if(!e(n.materialActivation,i.material.materialActivation)&&i.material.kind!==`sealed_export_root`)throw Error(`[SigningEngine][ed25519-export] Email OTP Yao context activation mismatch`);return{context:i,laneIdentity:r}}function zt(e){let t=e.resolved.laneIdentity.signer;return{artifactKind:_e,walletId:String(e.input.walletId),nearAccountId:String(e.input.nearAccountId),relayerUrl:e.resolved.relayerUrl,authorization:{kind:`opaque_wallet_session`,walletSessionToken:e.resolved.walletSessionToken},flowId:e.input.flowId,viewerSessionId:e.viewerSessionId,exactLane:{nearEd25519SigningKeyId:String(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,credentialIdB64u:e.resolved.laneIdentity.auth.credentialIdB64u,materialActivation:kt(e.resolved)},walletCustodyEnvelope:e.resolved.walletCustodyEnvelope,capability:e.resolved.capability,variant:e.input.options.variant,theme:e.input.options.theme??e.theme}}function Bt(e,t){let n=String(e.walletId);F(e.onEvent,{phase:t===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:t===`opened`?`waiting_for_user`:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`key_export_viewer`,overlay:t===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`}}),t===`closed`&&F(e.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}async function Vt(e,t){switch(t.laneIdentity.auth.kind){case`passkey`:break;case`email_otp`:return await Ht(e,t);default:throw t.laneIdentity.auth,Error(`[SigningEngine][ed25519-export] unsupported lane authorization method`)}let n=Lt(e,t),r=e.touchConfirm.initialize(),[i]=await Promise.all([n,r]),a=String(t.walletId),o=I(`export-ed25519-yao-viewer-session`),s=Bt.bind(void 0,{flowId:t.flowId,walletId:t.walletId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let c=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:kt(i)}),nearAccountId:t.nearAccountId,enabled:!0,task:()=>e.passkeyMpcExport.exportPrivateKeysWithUi(zt({resolved:i,viewerSessionId:o,input:t,theme:e.theme}),{onViewerLifecycle:s})});if(c.kind!==`completed`)throw Error(c.error);if(c.exportedSchemes.length!==1||c.exportedSchemes[0]!==`ed25519`)throw Error(`[SigningEngine][ed25519-export] secure export failed`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`none`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}async function Ht(e,t){let n=await Rt(e,t),r=`ed25519:${s(Uint8Array.from(n.context.material.capability.registeredPublicKey))}`,i=await We({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`email_otp_ed25519_export_auth`,walletId:t.walletId,nearAccountId:String(t.nearAccountId),nearEd25519SigningKeyId:String(n.laneIdentity.signer.nearEd25519SigningKeyId),signerSlot:n.laneIdentity.signer.signerSlot,publicKey:r,curve:`ed25519`,chain:`near`,flowId:t.flowId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let a=I(`export-ed25519-yao-viewer-session`);try{await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:r,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent});let o=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:At(n.context)}),nearAccountId:t.nearAccountId,enabled:n.context.material.kind===`active_capability`,task:()=>e.emailOtp.exportSeedWithFreshAuthorization({challengeId:i.challengeId,otpCode:i.otpCode,exportContext:n.context})});return F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),E(a)&&await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:o.publicKey,privateKey:o.privateKey,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}catch(e){throw T(),e}}function Ut(e){switch(e.kind){case`active`:case`expired`:return e;case`missing`:case`unavailable`:case`invalid`:return null;default:return e}}async function Wt(e){await e.deps.sessionLifecycle.invalidateExpiredAuthorization({state:e.state,source:e.source})}async function Gt(e){let t=await e.deps.sessionLifecycle.readAuthorization(e.request);return t.kind===`expired`&&await Wt({deps:e.deps,state:t,source:ae.operationPreflight}),t}function Kt(e){let t=Ut(e.preflightState);return t?Te({source:e.source,expiresAtMs:t.expiresAtMs,detectedAtMs:e.detectedAtMs}):null}async function qt(e,t){let n=l(t.walletSession.walletId),r=await Ot(e.laneSelection,{walletId:n,signingTarget:Ee(t.chainTarget),laneIdentity:t.laneIdentity}),i=await j(e.ecdsa.sessionStore,r);if(r.source===`active_wallet_authority`){if(i.source!==`active_wallet_authority`)throw Error(`[SigningEngine][ecdsa-export] active lane material source changed`);return{kind:`active_wallet_authority`,exportLane:r,exportMaterial:i}}if(i.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] canonical lane material source changed`);return{kind:`canonical_capability`,exportLane:r,exportMaterial:i}}function Jt(e){if(!(!e||e.source!==`canonical_capability`||!e.authorization))return e.authorization.operationCredential.walletSessionId}function Yt(e){let t=e.exportLane?.publicFacts,n=e.exportLane?h({walletId:e.exportLane.key.walletId,publicFacts:e.exportLane.publicFacts}):void 0;try{console.warn(`[SigningEngine][ecdsa-export][failure]`,{operationId:e.flowId,authMethod:e.exportLane?.authMethod,...n?{evmFamilyKeyFingerprint:n}:{},...t?{keyHandle:String(t.keyHandle)}:{},chainTargetKey:u(e.input.chainTarget),...Jt(e.exportLane)?{walletSessionId:Jt(e.exportLane)}:{},materialActivationId:e.exportLane?.laneIdentity.signer.materialActivation.activationId,freshAuthRetrySideEffectState:`not_applicable`,error:e.error instanceof Error?e.error.message:String(e.error||`unknown error`)})}catch{}}async function Xt(e,t,n){let r=l(t.walletSession.walletId);if(n.kind===`active_wallet_authority`)return await ct(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_email_otp_route_auth_ready`)return await lt(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_passkey_needs_authorization`)return await ut(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});throw n.exportMaterial,Error(`[SigningEngine][ecdsa-export] unsupported export material`)}async function Zt(e,t,n){let[r]=await Promise.all([qt(e,t),e.ecdsa.touchConfirm.initialize()]);if(r.exportLane.authorizationState===`authorization_required`)try{return await Xt(e,t,r)}catch(e){throw Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:e}),e}let i={kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization},a=await Gt({deps:e,request:{kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization,nowMs:Date.now()}});try{return await Xt(e,t,r)}catch(o){Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:o});let s=ye(o);if(n.kind===`fresh_auth_retry`||s?.kind!==`expired`)throw o;let c=Kt({source:i,preflightState:a,detectedAtMs:Date.now()});if(!c)throw o;return await Wt({deps:e,state:c,source:ae.serverRejection}),await Zt(e,t,{kind:`fresh_auth_retry`})}}async function Qt(e,t){return await Vt(e.ed25519Yao,{walletId:t.walletSession.walletId,nearAccountId:t.nearAccount.accountId,laneIdentity:t.laneIdentity,materialActivation:t.materialActivation,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent})}async function $t(e,t){return await He(t,async t=>{switch(t.kind){case`ecdsa`:return await Zt(e,t,{kind:`initial`});case`ed25519`:return await Qt(e,t)}})}async function en(e,t){return await St(e.laneSelection,t)}export{$t as exportKeypairWithUI,en as resolveExactKeyExportLane};
|
|
1
|
+
import{r as e}from"./domainIds-C3fUa33Q.js";import{c as t}from"./chains-CPmd4s9f.js";import{t as n}from"./activeWalletSession-BtEHhe99.js";import{r}from"./secureRandomId-8LSc91aN.js";import"./walletDbName-BVZhb4xF.js";import"./signingSessionSeal-DqbjG8c8.js";import"./capabilityKinds-CqHVzVsJ.js";import{o as i}from"./canonicalPrimitives-D_1HyEuJ.js";import{i as a,t as o}from"./errors-CI1xdN0d.js";import{d as s,t as c}from"./accountIds-BzZs7YoX.js";import{c as l,o as u,s as ee,u as d}from"./ecdsaChainTarget-svSlzhze.js";import"./signerDomain-YEHkugWX.js";import"./presignatures-DGLNs29C.js";import"./walletCapabilityBindings-CKOK39sP.js";import{Nt as f,Pt as p,St as te,a as m,g as h,ln as ne,un as re,zt as g}from"./emailOtpEcdsaDerivationIdentity-DreNrM6n.js";import{i as ie}from"./walletAuthMethodRecord-Cv_MYpxt.js";import"./signerSlot-CpyIfl3J.js";import{a as ae,n as _,u as oe}from"./sdkSentEvents-BzMVO1AR.js";import{s as se}from"./types-BrEW276O.js";import{i as ce}from"./helpers-BXezXx19.js";import{C as le,D as v,b as ue,j as de,x as fe}from"./nearEd25519YaoSigningPreparation-BgCxoh9S.js";import{l as y,u as pe}from"./trace-CWTzEALZ.js";import{n as me,r as he,t as ge,v as _e}from"./ecdsaDerivationExport-DrFESeRP.js";import{t as ve}from"./challengeDelivery-C88JNwKf.js";import{i as ye}from"./walletSessionFailure-Ct412mDZ.js";import{i as be,n as xe,r as Se,s as Ce}from"./signingQueue-Cj9sCJLj.js";import{h as b,i as x,l as we,n as Te,s as S}from"./clientSessionPersistenceState-DFGHXoKK.js";import{t as C}from"./types-BNUuaUtl.js";import{i as w}from"./appearance-ZGVLwA4N.js";import{n as T,t as E}from"./export-viewer-host-C9n-62Pi.js";function D(e){return e.chainTarget.kind}function Ee(e){return e}function De(e){return!e||e.curve!==`ecdsa`||!e.chainTarget||!b(e)||!String(e.publicFacts.keyHandle||``).trim()?!1:e.source===`active_wallet_authority`?e.runtime.requiredCapability===`export_keys`&&e.state===`deferred`&&e.authorizationState===`authorization_required`:e.authorization?!0:e.state===`deferred`}function O(e){if(e.length!==2)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set must contain two parties`);let t=e[0],n=e[1];if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<=0||n<=0||t===n)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set is invalid`);return[t,n]}function k(t){let{exportLane:n,label:r}=t,i=n.capability,a=i.manifest.signer;if(a.walletId!==n.key.walletId||!a.scope.targetMemberships.some(e=>ee(e,n.chainTarget)))throw Error(`[SigningEngine][ecdsa-export] ${r} capability target mismatch`);if(!t.authMatches())throw Error(`[SigningEngine][ecdsa-export] ${r} capability auth mismatch`);if(!e(i.manifest.activation.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] ${r} material activation mismatch`);m({expected:n.publicFacts,actual:a.registeredPublicFacts,context:`canonical ${r} export lane`});let o=i.material.publicFacts;if(o.walletId!==a.walletId||String(o.keyHandle)!==String(n.publicFacts.keyHandle)||String(o.groupPublicKey33B64u)!==String(n.publicFacts.publicKeyB64u)||String(o.ethereumAddress)!==String(n.publicFacts.thresholdOwnerAddress)||o.participantIds.length!==n.publicFacts.participantIds.length||o.participantIds.some((e,t)=>e!==n.publicFacts.participantIds[t]))throw Error(`[SigningEngine][ecdsa-export] canonical ${r} export material mismatch`);let s=i.manifest.durableMaterial,c=s.runtimePolicyScope,l=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!c)throw Error(`[SigningEngine][ecdsa-export] ${r} runtime policy scope is missing`);if(!l)throw Error(`[SigningEngine][ecdsa-export] ${r} export relayer URL is missing`);return{durable:s,runtimePolicyScope:c,relayerUrl:l}}function Oe(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!f(r))throw Error(`[SigningEngine][ecdsa-export] Email OTP capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`Email OTP`,authMatches:()=>t.laneIdentity.auth.kind===`email_otp`&&t.laneIdentity.auth.providerSubjectId===r.factor.providerUserId});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,persistedMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o,authorization:{kind:`fresh_operation_authorization_required`,authority:r}}}function ke(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!p(r))throw Error(`[SigningEngine][ecdsa-export] passkey capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`passkey`,authMatches:()=>t.laneIdentity.auth.kind===`passkey`&&t.laneIdentity.auth.credentialIdB64u===r.factor.credentialIdB64u});return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,publicCapability:i.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o}}function Ae(t){let{exportLane:n,resolution:r}=t;if(n.laneIdentity.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(r.runtime.authBinding.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime authority mismatch`);if(n.laneIdentity.auth.providerSubjectId!==r.runtime.authBinding.providerSubjectId)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] Email OTP material activation mismatch`);let i=r.runtime.runtimePolicyScope;if(!i)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime policy scope is missing`);let a=be({authority:r.manifest.signer.authority,materialActivation:r.manifest.activation.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:n.chainTarget,publicFacts:n.publicFacts,runtimePolicyScope:i,persistedMaterial:a,normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl,authorization:{kind:`fresh_operation_authorization_required`,authority:r.runtime.authBinding.emailOtpAuthority}}}function je(t){let{exportLane:n}=t,r=n.runtime;if(r.requiredCapability!==`export_keys`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority lane lacks export_keys capability`);if(r.walletId!==n.key.walletId)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority wallet mismatch`);if(!e(r.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority material activation mismatch`);m({expected:n.publicFacts,actual:r.publicFacts,context:`active Wallet Authority ECDSA export lane`});let i=r.normalSigning,a=i.scope;if(a.wallet_id!==String(r.walletId)||a.ecdsa_threshold_key_id!==r.ecdsaThresholdKeyId||a.public_identity.threshold_public_key33_b64u!==r.publicFacts.publicKeyB64u||!e(ne(a.material_activation),r.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority normal-signing identity mismatch`);let o=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!o)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority export relayer URL is missing`);let s=O(r.publicFacts.participantIds);if(r.auth.kind===`passkey`){if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);if(r.factorAuthority.factor.credentialIdB64u!==r.auth.credentialIdB64u||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active passkey factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`passkey`}}if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);if(r.factorAuthority.factor.providerUserId!==r.auth.providerSubjectId||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_email_otp_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`email_otp`}}async function A(e,t){if(t.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority Email OTP material uses its holder runtime`);if(t.authMethod!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] fresh Email OTP export requires Email OTP lane`);let n=await e.resolveActiveEcdsaCapabilityRuntime({walletId:t.key.walletId,chainTarget:t.chainTarget});if(n.kind===`blocked`&&n.reason===`missing_material`)return Oe({deps:e,exportLane:t});if(n.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] Email OTP capability runtime unavailable: ${n.reason}`);return Ae({exportLane:t,resolution:n})}async function j(t,n){if(n.source===`active_wallet_authority`)return je({deps:t,exportLane:n});if(n.authMethod===`email_otp`)return await A(t,n);let r=await t.resolveActiveEcdsaCapabilityRuntime({walletId:n.key.walletId,chainTarget:n.chainTarget});if(r.kind===`blocked`&&r.reason===`missing_material`)return ke({deps:t,exportLane:n});if(r.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] passkey capability runtime unavailable: ${r.reason}`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] passkey material activation mismatch`);if(r.runtime.authBinding.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] passkey authority binding mismatch`);let i=r.manifest.signer.registeredPublicFacts;m({expected:n.publicFacts,actual:i,context:`canonical passkey export lane`});let a=r.runtime.runtimePolicyScope;if(!a)throw Error(`[SigningEngine][ecdsa-export] durable passkey export requires runtimePolicyScope`);return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:i,runtimePolicyScope:a,publicCapability:r.manifest.durableMaterial.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:be({authority:r.manifest.signer.authority,materialActivation:r.manifest.durableMaterial.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts}),normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl}}function Me(e){return r(e,32,`Email OTP export UI request IDs`)}function Ne(e){switch(e.kind){case`near_account`:return String(c(e.nearAccountId));case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return t}default:return e}}function Pe(e){switch(e.kind){case`near_account`:if(!String(e.walletId||``).trim())throw Error(`Email OTP NEAR export requires wallet identity`);return{kind:`near_wallet`,walletId:String(e.walletId).trim(),nearAccountId:String(c(e.nearAccountId))};case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return{kind:`evm_wallet`,walletId:t}}default:return e}}function Fe(e){return{challengeId:e.challenge.challengeId,...e.challenge.emailHint?{emailHint:e.challenge.emailHint}:{},title:`Enter email code to export`,body:`This one-time code authorizes private key export only.`,helperText:`Enter the 6-digit code sent to your email`,onResend:e.onResend}}async function M(e){let t=Ne(e.identity),n=async()=>{let t=await e.challengeSource.requestChallenge(),n=String(t.challengeId||``).trim();if(!n)throw Error(`Email OTP export challenge response did not include challengeId`);let r=String(t.emailHint||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include emailHint`);let i={challengeId:n,emailHint:r,delivery:t.delivery};return e.onChallenge?.(i),i},r=await n(),i=Fe({challenge:r,onResend:async()=>(r=await n(),r)}),a=Pe(e.identity),o=await e.confirmer.requestUserConfirmation({requestId:Me(`export-${e.curve}-email-otp-auth`),type:w.SIGN_INTENT_DIGEST,summary:{operation:`Export Private Key`,accountId:t,publicKey:e.publicKey,warning:`Enter the email code to export this key. Anyone with the private key can fully control the account.`},payload:{signingSubject:a,challengeB64u:r.challengeId,signingAuthPlan:{kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:i},emailOtpPrompt:i},intentDigest:`export-keys:${t}:${e.chain}:${e.curve}:email-otp`});if(!o.confirmed)throw Error(o.error||`User cancelled Email OTP export request`);let s=String(o.otpCode||``).replace(/\D/g,``).slice(0,6);if(s.length!==6)throw Error(`Email OTP export requires a 6-digit code`);return{challengeId:String(o.emailOtpChallengeId||r.challengeId).trim(),otpCode:s}}function N(e){throw Error(`[SigningEngine][export] unsupported authorization identity: ${String(e)}`)}function Ie(e){throw Error(`[SigningEngine][export] unsupported step-up method: ${String(e)}`)}function Le(e){let t=String(e.walletSessionUserId||``).trim();if(!t)throw Error(`[SigningEngine][export] missing export step-up authorization identity`);let n=String(e.publicKey||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export step-up authorization public key`);switch(e.curve){case`ecdsa`:return{walletSessionUserId:t,publicKey:n,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.chain};case`ed25519`:{let r={walletSessionUserId:t,publicKey:n,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:String(e.nearAccountId||``).trim(),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId||``).trim(),signerSlot:Number(e.signerSlot)};if(!r.nearAccountId||!r.nearEd25519SigningKeyId||!Number.isSafeInteger(r.signerSlot)||r.signerSlot<1)throw Error(`[SigningEngine][export] Ed25519 export authorization identity is invalid`);return r}default:return N(e)}}function Re(e){let t={kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:e.emailOtpPrompt},n=e.emailOtpPrompt.emailHint;switch(e.identity.curve){case`ecdsa`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain,...n?{emailHint:n}:{}};case`ed25519`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot,...n?{emailHint:n}:{}};default:return N(e.identity)}}function ze(e){let t={kind:C.PasskeyReauth,method:`passkey`};switch(e.identity.curve){case`ecdsa`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain};case`ed25519`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot};default:return N(e.identity)}}function P(e){let t=Le(e);switch(e.method){case`email_otp`:{if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled Email OTP export request`);let n=String(e.decision.otpCode||``).replace(/\D/g,``).slice(0,6);if(n.length!==6)throw Error(`Email OTP export requires a 6-digit code`);let r=String(e.decision.emailOtpChallengeId||e.emailOtpPrompt.challengeId||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include challengeId`);return Re({identity:t,emailOtpPrompt:e.emailOtpPrompt,challengeId:r,otpCode:n})}case`passkey`:if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled export request`);if(!e.decision.credential)throw Error(`[SigningEngine][export] missing WebAuthn credential for export authorization`);return ze({identity:t,credential:ce(e.decision.credential)});default:return Ie(e)}}function Be(e){switch(e.kind){case`ecdsa`:return{subject:`${String(e.walletSession.walletId)}:${u(e.chainTarget)}`,chain:e.chainTarget.kind,data:{curve:`ecdsa`,chain:e.chainTarget.kind,chainTarget:e.chainTarget}};case`ed25519`:return{subject:`${String(e.walletSession.walletId)}:near:${String(e.nearAccount.accountId)}`,chain:`near`,data:{curve:`ed25519`,chain:`near`,nearAccount:e.nearAccount}}}}function F(e,t){if(e)try{e(oe(t))}catch{}}function I(e){return r(e,32,`key export UI request IDs`)}function Ve(e,t){return`key-export:${e}:${t}:${I(`flow`)}`}async function He(e,t){let n=Be(e),r=Ve(n.subject,n.chain),i=e.walletSession.walletId,s=n.data;F(e.options.onEvent,{phase:_.STEP_01_STARTED,status:`running`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`none`},data:s});try{return await t({...e,flowId:r})}catch(t){let n=a(t);throw F(e.options.onEvent,{phase:n?_.CANCELLED:_.FAILED,status:n?`cancelled`:`failed`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`hide`},error:{message:o(t)||(n?`Key export cancelled`:`Key export failed`)},data:s}),t}}async function Ue(e,t){return await e.requestExportChallenge({kind:`wallet_login_challenge`,walletSession:t.walletSession,chain:t.chain})}function L(e,t){let n=e.kind===`email_otp_ed25519_export_auth`?e.walletId:e.walletSession.walletSessionUserId;F(e.onEvent,{phase:_.STEP_02_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,flowId:e.flowId,accountId:String(n),authMethod:`email_otp`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:t.emailHint,demoOtpCode:ve(t.delivery)}})}async function R(e,t){let n=t.walletSession.walletSessionUserId,r=await M({identity:{kind:`wallet_session`,walletId:n},chain:t.chain,publicKey:t.publicKey,curve:t.curve,challengeSource:{requestChallenge:async()=>await Ue(e,t)},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),i={challengeId:r.challengeId},a={confirmed:!0,otpCode:r.otpCode,emailOtpChallengeId:r.challengeId},o=P({method:`email_otp`,walletSessionUserId:n,chain:t.chain,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,emailOtpPrompt:i,decision:a});if(o.kind!==`email_otp`)throw Error(`[SigningEngine][export] Email OTP export returned the wrong step-up method`);return o}async function We(e,t){let n=await M({identity:{kind:`near_account`,walletId:t.walletId,nearAccountId:t.nearAccountId},chain:`near`,publicKey:t.publicKey,curve:`ed25519`,challengeSource:{requestChallenge:async()=>await e.requestExportChallenge({kind:`wallet_export_challenge`,walletId:t.walletId,chain:`near`})},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),r=P({method:`email_otp`,walletSessionUserId:t.walletId,publicKey:t.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,emailOtpPrompt:{challengeId:n.challengeId},decision:{confirmed:!0,otpCode:n.otpCode,emailOtpChallengeId:n.challengeId}});if(r.kind!==`email_otp`||r.curve!==`ed25519`)throw Error(`[SigningEngine][export] Ed25519 Email OTP export authorization changed kind`);return r}async function z(e,t){let n=t.state===`loading`,r=[{scheme:`ed25519`,label:`NEAR Ed25519 private key`,publicKey:t.publicKey,privateKey:n?``:t.privateKey}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-ed25519-yao-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.nearAccountId,publicKey:t.publicKey,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`near_wallet`,nearAccountId:t.nearAccountId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKey,keys:r,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:n,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`,loading:n}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}},intentDigest:`export-keys:${t.walletId}:near:${t.nearAccountId}:ed25519`})}async function B(e,t){let n=t.chainTarget.kind,r=String(t.walletSessionUserId||``).trim();if(!r)throw Error(`[SigningEngine][export] missing ECDSA export wallet session user id`);return await Ge(e,{walletSessionUserId:t.walletSessionUserId,intent:`ecdsa_export`,curve:`ecdsa`,chain:n,publicKey:t.publicKey,flowId:t.flowId,onEvent:t.onEvent,request:{requestId:I(`export-threshold-ecdsa-auth`),type:w.AUTHORIZE_KEY_EXPORT,summary:{operation:`Export Private Key`,accountId:r,publicKey:t.publicKey,warning:n===`tempo`?`Confirm to reveal your Tempo private key export.`:`Confirm to reveal your EVM private key export.`},payload:{subject:{kind:`evm_wallet`,walletId:r},credentialIdB64u:t.credentialIdB64u,publicKey:t.publicKey,...t.challengeB64u?{challengeB64u:t.challengeB64u}:{}},intentDigest:`export-keys:${r}:${u(t.chainTarget)}:secp256k1`}})}async function V(e,t){let n=t.chainTarget.kind,r=n===`tempo`?`Tempo`:`EVM`,i=t.state===`loading`,a=i?[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:``,address:t.ethereumAddress}]:[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:t.privateKeyHex,address:t.ethereumAddress}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-threshold-ecdsa-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.walletId,publicKey:t.publicKeyHex,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`evm_wallet`,walletId:t.walletId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKeyHex,keys:a,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:i,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:n,curve:`ecdsa`,loading:i}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`none`,overlay:`hide`},data:{chain:n,curve:`ecdsa`}})}},intentDigest:`export-keys:${t.walletId}:${u(t.chainTarget)}:secp256k1`})}async function Ge(e,t){let n=String(t.walletSessionUserId||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export account identity`);F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:t.intent,curve:t.curve}}),T();let r=await e.touchConfirm.requestUserConfirmation(t.request),i=P({method:`passkey`,walletSessionUserId:t.walletSessionUserId,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:t.chain,decision:r});if(i.kind!==`passkey`)throw Error(`[SigningEngine][export] passkey export returned the wrong step-up method`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`},data:{intent:t.intent,curve:t.curve}}),i}function Ke(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`}})}function qe(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`,...e.source?{source:e.source}:{}}})}async function Je(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.artifact.publicKeyHex||``).trim(),privateKeyHex:String(t.artifact.privateKeyHex||``).trim(),ethereumAddress:String(t.artifact.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function Ye(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.publicKey||``).trim(),ethereumAddress:String(t.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function H(t,n){let r=D(n.exportLane),i=I(`export-threshold-ecdsa-viewer-session`);Ke({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent});try{await Ye(t,{walletId:n.walletId,exportLane:n.exportLane,publicKey:n.exportPublicKey,ethereumAddress:n.exportLane.publicFacts.thresholdOwnerAddress,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent});let a=n.exportLane.laneIdentity.signer.materialActivation,o=await t.withThresholdEcdsaSigningQueue({queueKey:x({materialActivation:a}),walletId:n.exportLane.key.walletId,enabled:!0,task:async()=>{if(n.exportLane.source===`active_wallet_authority`){let e=n.activeRuntime;if(!e)throw Error(`[SigningEngine][ecdsa-export] active runtime is missing`);await et({ports:t.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e})}else if(n.exportLane.authMethod===`email_otp`){if(!e((await A(t.sessionStore,n.exportLane)).persistedMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}else{let r=await j(t.sessionStore,n.exportLane);if(r.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] prepared export authority changed`);if(!e(r.existingRoleLocalMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}return await n.prepareArtifact()}});return qe({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent}),E(i)&&await Je(t,{walletId:n.walletId,exportLane:n.exportLane,artifact:o,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent}),{accountId:String(n.walletId),exportedSchemes:[`secp256k1`]}}catch(e){throw T(),e}}function U(e){let t=e.laneIdentity.auth;if(t.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);return t}async function W(e){return i(t(e))}async function G(e){let t=u(e.chainTarget);return await Se({walletId:e.walletId,operationKind:`evm.export_key`,operationId:e.requestId,operationDigests:{laneDigest:await W({walletId:e.walletId,chainTarget:t,materialActivation:e.materialActivation,keyHandle:e.keyHandle}),intentDigest:await W({operation:`explicit_key_export`,requestId:e.requestId,walletId:e.walletId,chainTarget:t}),displayDigest:await W({operation:`Export Private Key`,publicKey:e.displayPublicKey,address:e.displayAddress})},materialActivation:e.materialActivation,normalSigningScope:e.operationRuntime.normalSigning.scope,keyHandle:e.keyHandle,relayerKeyId:e.operationRuntime.relayerKeyId,participantIds:[Number(e.operationRuntime.participantIds[0]),Number(e.operationRuntime.participantIds[1])],expiresAtMs:e.operationExpiresAtMs})}async function K(e){return await G({walletId:e.walletId,chainTarget:e.chainTarget,requestId:e.requestId,keyHandle:e.keyHandle,displayPublicKey:e.displayPublicKey,displayAddress:e.displayAddress,materialActivation:e.materialActivation,operationRuntime:e.operationRuntime,operationExpiresAtMs:e.operationExpiresAtMs})}async function Xe(t){let n=await j(t.deps.sessionStore,t.exportLane);if(n.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] passkey export authority changed`);if(!e(n.existingRoleLocalMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}async function Ze(t){if(!e((await A(t.deps.sessionStore,t.exportLane)).persistedMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}function Qe(e){if(!$e(e.expected,e.actual))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime was replaced after authorization`)}function $e(t,r){let i;switch(t.auth.kind){case`passkey`:i=r.auth.kind===`passkey`&&t.auth.rpId===r.auth.rpId&&t.auth.credentialIdB64u===r.auth.credentialIdB64u;break;case`email_otp`:i=r.auth.kind===`email_otp`&&t.auth.providerSubjectId===r.auth.providerSubjectId;break;default:return t.auth}return t.kind===r.kind&&t.walletId===r.walletId&&t.authorityId===r.authorityId&&t.walletAuthMethodId===r.walletAuthMethodId&&t.authorityDigestB64u===r.authorityDigestB64u&&t.factorAuthorityRef.kind===r.factorAuthorityRef.kind&&t.factorAuthorityRef.walletId===r.factorAuthorityRef.walletId&&t.factorAuthorityRef.authorityDigest===r.factorAuthorityRef.authorityDigest&&t.factorAuthorityRef.walletAuthMethodId===r.factorAuthorityRef.walletAuthMethodId&&t.authorityRevocationEpoch===r.authorityRevocationEpoch&&t.walletSessionId===r.walletSessionId&&t.requiredCapability===r.requiredCapability&&e(t.materialActivation,r.materialActivation)&&t.ecdsaThresholdKeyId===r.ecdsaThresholdKeyId&&t.relayerKeyId===r.relayerKeyId&&t.operationCredential.kind===r.operationCredential.kind&&t.operationCredential.token===r.operationCredential.token&&t.operationCredential.walletSessionId===r.operationCredential.walletSessionId&&n(t.session,r.session)&&ie(t.authMethod,r.authMethod)&&i&&g(t.factorAuthority,r.factorAuthority)&&t.holderRuntime.kind===r.holderRuntime.kind&&t.holderRuntime.walletId===r.holderRuntime.walletId&&t.holderRuntime.authorityId===r.holderRuntime.authorityId&&t.holderRuntime.walletAuthMethodId===r.holderRuntime.walletAuthMethodId&&g(t.holderRuntime.factorAuthority,r.holderRuntime.factorAuthority)&&e(t.holderRuntime.materialActivation,r.holderRuntime.materialActivation)&&t.holderRuntime.holderHandleId===r.holderRuntime.holderHandleId&&t.holderRuntime.ecdsaThresholdKeyId===r.holderRuntime.ecdsaThresholdKeyId&&te(t.normalSigning,r.normalSigning)}async function q(e){let t=await Ce({ports:e.ports,input:{walletId:e.expectedRuntime.walletId,requiredCapability:`export_keys`,materialActivation:e.expectedRuntime.materialActivation}});if(t.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime is ${t.reason}`);return Qe({expected:e.expectedRuntime,actual:t.runtime}),t.runtime}async function et(e){await q(e)}function J(e){let t=e.credential,n=String(t.rawId||t.id||``).trim();if(!n||n!==e.authority.factor.credentialIdB64u)throw Error(`[SigningEngine][ecdsa-export] passkey credential does not match authority`);return{kind:`passkey`,authority:e.authority,webauthn_authentication:{id:t.id,rawId:t.rawId,type:t.type,authenticatorAttachment:t.authenticatorAttachment??null,response:{clientDataJSON:t.response.clientDataJSON,authenticatorData:t.response.authenticatorData,signature:t.response.signature,userHandle:t.response.userHandle??null},clientExtensionResults:null}}}function Y(e){if(!f(e.authority))throw Error(`[SigningEngine][ecdsa-export] Email OTP material authority mismatch`);return{kind:`email_otp`,authority:e.authority,challenge_id:e.challengeId,otp_code:e.otpCode}}async function X(e){let t=await xe({relayerUrl:e.relayerUrl,transport:e.transport,request:{kind:`router_ab_ecdsa_operation_step_up_v1`,operation:e.prepared.operation,proof:e.proof}});if(t.operation_kind!==`evm.export_key`)throw Error(`[SigningEngine][ecdsa-export] operation step-up kind mismatch`);let n=t.authorization.evidence_set_digest,r=tt({proofKind:e.proof.kind,unseal:t.authorization.unseal});return{kind:`verified_step_up`,evidenceSetDigest:n,operation:e.prepared.operation,expiresAtMs:t.expires_at_ms,quotaUse:`none`,unseal:r,exportTopology:t.export_topology}}function tt(e){switch(e.proofKind){case`passkey`:if(e.unseal.kind!==`not_requested`)throw Error(`[SigningEngine][ecdsa-export] passkey step-up returned Email OTP unseal material`);return{kind:`not_requested`};case`email_otp`:if(e.unseal.kind!==`email_otp_grant`)throw Error(`[SigningEngine][ecdsa-export] Email OTP step-up did not return an unseal grant`);return{kind:`email_otp_grant`,grant:e.unseal.grant,challenge_id:e.unseal.challenge_id};default:{let t=e.proofKind;throw Error(`Unsupported ECDSA export step-up proof: ${String(t)}`)}}}async function nt(e,t){U(t.exportLane);let n=I(`tecdsa-export`),r=await K({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:n,keyHandle:t.material.existingRoleLocalMaterial.publicFacts.keyHandle,displayPublicKey:t.material.existingRoleLocalMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.existingRoleLocalMaterial.publicFacts.ethereumAddress,materialActivation:t.material.existingRoleLocalMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await B({touchConfirm:e.touchConfirm,theme:e.theme},{walletSessionUserId:t.walletId,credentialIdB64u:U(t.exportLane).credentialIdB64u,publicKey:t.exportPublicKey,chainTarget:t.exportLane.chainTarget,challengeB64u:r.challengeB64u,flowId:t.flowId,onEvent:t.onEvent});await Xe({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.existingRoleLocalMaterial.materialActivation});let a=t.exportLane.capability.authority;if(!p(a))throw Error(`[SigningEngine][ecdsa-export] exact Passkey capability authority changed`);let o=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:J({authority:a,credential:i.credential})});return{exportActivation:he({relayerUrl:t.material.relayerUrl,existingRoleLocalMaterial:t.material.existingRoleLocalMaterial,authorization:o}),credential:i.credential}}async function rt(e){let t=d({walletId:e.walletId,walletSessionUserId:e.walletId});return await e.deps.emailOtp.exportEcdsaKeyWithDurableAuthorization({walletSession:t,chainTarget:e.material.chainTarget,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode,publicFacts:e.material.publicFacts,runtimePolicyScope:e.material.runtimePolicyScope,authority:e.material.authorization.authority,persistedMaterial:e.persistedMaterial,explicitExportAuthorization:e.explicitExportAuthorization})}function Z(e){return{normalSigning:e.runtime.normalSigning,relayerKeyId:e.relayerKeyId,participantIds:e.participantIds}}function Q(e){return Math.min(Date.now()+5*6e4,e.session.expiresAtMs)}async function it(e){if(e.material.runtime.auth.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] active passkey runtime auth mismatch`);if(!p(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-passkey-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await B({touchConfirm:e.deps.touchConfirm,theme:e.deps.theme},{walletSessionUserId:e.walletId,credentialIdB64u:e.material.factorAuthority.factor.credentialIdB64u,publicKey:e.exportPublicKey,chainTarget:e.exportLane.chainTarget,challengeB64u:t.challengeB64u,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:J({authority:r.factorAuthority,credential:n.credential})})}}async function at(e){if(e.material.runtime.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] active Email OTP runtime auth mismatch`);if(!f(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-email-otp-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await R({touchConfirm:e.deps.touchConfirm,requestExportChallenge:e.deps.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:e.walletId,walletSessionUserId:e.walletId}),chain:D(e.exportLane),publicKey:e.exportPublicKey,curve:`ecdsa`,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:Y({authority:r.factorAuthority,challengeId:n.challengeId,otpCode:n.otpCode})})}}async function ot(e){switch(e.material.kind){case`active_wallet_authority_passkey_needs_authorization`:return await it({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});case`active_wallet_authority_email_otp_needs_authorization`:return await at({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});default:return st(e.material)}}function st(e){throw Error(`[SigningEngine][ecdsa-export] unsupported active wallet authority material: ${String(e)}`)}async function ct(e,t){let n=String(t.material.publicFacts.publicKeyB64u),r=await ot({deps:e,walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,activeRuntime:r.runtime,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await q({ports:e.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:r.runtime});return await ge({getSignerWorkerContext:e.getSignerWorkerContext},{runtime:n,operationAuthorization:r.authorization,relayerUrl:t.material.relayerUrl})}})}async function lt(e,t){let n=D(t.exportLane),r=await G({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:I(`tecdsa-email-otp-export`),keyHandle:t.material.persistedMaterial.publicFacts.keyHandle,displayPublicKey:t.material.persistedMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.persistedMaterial.publicFacts.ethereumAddress,materialActivation:t.material.persistedMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await R({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:t.walletId,walletSessionUserId:t.walletId}),chain:n,publicKey:String(t.material.publicFacts.publicKeyB64u),curve:`ecdsa`,flowId:t.flowId,onEvent:t.onEvent});await Ze({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.persistedMaterial.materialActivation});let a=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:Y({authority:t.material.authorization.authority,challengeId:i.challengeId,otpCode:i.otpCode})});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:String(t.material.publicFacts.publicKeyB64u),options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:rt.bind(void 0,{deps:e,walletId:t.walletId,material:t.material,authorization:i,persistedMaterial:t.material.persistedMaterial,explicitExportAuthorization:a})})}async function ut(e,t){if(t.exportLane.authMethod!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);let n=String(t.material.publicFacts.publicKeyB64u),r=await nt(e,{walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await e.provisionPasskeyEcdsaExplicitExportSession(r.exportActivation);return await me({getSignerWorkerContext:e.getSignerWorkerContext},{walletSessionUserId:t.walletId,exportProvision:n,factorAuthorization:{kind:`passkey`,passkeyCredentialIdB64u:String(r.credential.rawId||r.credential.id),credential:r.credential}})}})}function $(e){let t=e.source===`canonical_capability`?e.authorization:null;return{authMethod:S(e),curve:e.curve,chain:e.chainTarget.kind,chainTarget:e.chainTarget,state:e.state,source:e.source,...t?{remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}:{},updatedAtMs:e.updatedAtMs,evmFamilyKeyFingerprint:h({walletId:e.key.walletId,publicFacts:e.publicFacts})}}function dt(e,t){return String(e.key.walletId)===t.walletId?String(h({walletId:e.key.walletId,publicFacts:e.publicFacts})):``}function ft(e){if(!e.candidates.length)throw y(`evm-family`,{stage:`key_export.exact_lane_no_candidate`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: no_candidate`);for(let t of e.candidates)if(!dt(t,e.ecdsaContext))return pt(e);if(e.candidates.length!==1)return pt(e);let[t]=e.candidates;return pe(`evm-family`,{stage:`key_export.exact_lane_selected`,context:e.context,reason:`single_exact_candidate`,selectedLane:$(t),candidateCount:e.candidates.length}),t}function pt(e){throw y(`evm-family`,{stage:`key_export.exact_lane_ambiguous_material`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: ambiguous_material`)}function mt(e){return fe({signer:ue({walletId:e.lane.key.walletId,chainTarget:e.chainTarget||e.lane.chainTarget,keyHandle:e.lane.publicFacts.keyHandle,key:e.lane.key,materialActivation:e.lane.materialActivation}),auth:e.lane.auth})}function ht(e){return e.source===`active_wallet_authority`||e.state===`ready`?{kind:`loaded_worker_material`}:S(e)===`email_otp`?{kind:`material_pending`,reason:`email_otp_route_auth`}:{kind:`sealed_worker_material`}}function gt(e){if(e.lane.source===`active_wallet_authority`)return{chainTarget:e.chainTarget,authMethod:S(e.lane),material:{kind:`loaded_worker_material`},state:`deferred`};let t=S(e.lane),n=ht(e.lane);switch(e.lane.state){case`expired`:case`exhausted`:throw Error(`[SigningEngine][ecdsa-export] expired export lane requires durable public reauth authority`);case`ready`:case`deferred`:return{chainTarget:e.chainTarget,authMethod:t,material:n,state:e.lane.state}}}async function _t(e){let t=e.lane,n=mt({lane:t}),r=gt({lane:t,chainTarget:e.chainTarget});return t.source===`active_wallet_authority`?{curve:`ecdsa`,laneIdentity:n,source:`active_wallet_authority`,authorizationState:`authorization_required`,key:t.key,publicFacts:t.publicFacts,runtime:t.runtime,chainTarget:e.chainTarget,authMethod:S(t),material:{kind:`loaded_worker_material`},state:`deferred`}:t.authorization?{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorized`,authorization:t.authorization,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}:{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorization_required`,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}}function vt(e){return v(e.laneIdentity)===v(e.identity)}async function yt(e){return mt({lane:e})}function bt(e){return we(e.availableLanes,e.chainTarget).filter(e=>De(e))}async function xt(e,t){let n=bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:t.walletId,ecdsaChainTargets:[t.signingTarget]}),chainTarget:t.signingTarget}),r=[];for(let e of n)vt({laneIdentity:await yt(e),identity:t.laneIdentity})&&r.push(e);let i=ft({context:`ecdsa-export`,candidates:r,ecdsaContext:{walletId:t.walletId}});return await _t({lane:i,chainTarget:i.chainTarget})}async function St(e,t){switch(t.kind){case`ecdsa`:return await Ct(e,t);case`ed25519`:return await Dt(e,t)}}async function Ct(e,t){let n=String(l(t.walletSession.walletId));return{kind:`ecdsa`,laneIdentity:await yt(ft({context:`ecdsa-export-resolve`,candidates:bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[t.chainTarget]}),chainTarget:t.chainTarget}),ecdsaContext:{walletId:n}}))}}function wt(e){let t=e.lane.source===`durable_sealed_record`||e.lane.source===`public_capability_reference`;return String(e.lane.walletId)===e.walletId&&String(e.lane.nearAccountId)===e.nearAccountId&&t}function Tt(e){return le({signer:de({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:e.auth,thresholdSessionId:e.thresholdSessionId})}function Et(e){return[e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,se(e.auth)].map(e=>String(e)).join(`|`)}async function Dt(e,t){let n=String(l(t.walletSession.walletId)),r=String(t.nearAccount.accountId),i=await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[]}),a=i.lanes.ed25519.near;if(!b(a)||a.curve!==`ed25519`||!wt({lane:a,walletId:n,nearAccountId:r}))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: no_candidate`);let o=i.candidates.ed25519.near.filter(e=>b(e)&&e.curve===`ed25519`&&wt({lane:e,walletId:n,nearAccountId:r})),s=Et(a);if(o.some(e=>Et(e)!==s))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: ambiguous_material`);return{kind:`ed25519`,laneIdentity:Tt(a),materialActivation:a.materialActivation}}async function Ot(e,t){let n=await xt(e,{walletId:t.walletId,signingTarget:t.signingTarget,laneIdentity:t.laneIdentity});switch(n.material.kind){case`loaded_worker_material`:case`material_pending`:case`sealed_worker_material`:return n}throw n.material,Error(`[SigningEngine][ecdsa-export] unsupported material availability`)}function kt(e){return e.capability.materialActivation}function At(e){return e.material.materialActivation}function jt(e){return e.auth.kind===`passkey`}function Mt(e){if(!jt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires a passkey Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Nt(e){return e.auth.kind===`email_otp`}function Pt(e){if(!Nt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires an Email OTP Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Ft(e){let t=e.selected.signer,n=e.context.material;return String(t.account.wallet.walletId)===String(n.walletId)&&String(t.account.nearAccountId)===String(n.nearAccountId)&&String(t.nearEd25519SigningKeyId)===String(n.nearEd25519SigningKeyId)&&t.signerSlot===n.signerSlot&&String(e.selected.auth.rpId)===e.context.rpId&&e.selected.auth.credentialIdB64u===n.credentialIdB64u}function It(t){if(!Ft({selected:t.selectedLaneIdentity,context:t.context}))throw Error(`[SigningEngine][ed25519-export] durable Yao context identity mismatch`);let n=t.context.material;if(!e(t.selectedMaterialActivation,t.context.selectedLaneMaterialActivation))throw Error(`[SigningEngine][ed25519-export] durable Yao context activation mismatch`);let r=t.context.authorization.operationCredential.token;if(!r)throw Error(`[SigningEngine][ed25519-export] active Wallet Session authorization is unavailable`);let i=n.capability.lifecycle;return{laneIdentity:t.selectedLaneIdentity,relayerUrl:t.context.relayerUrl,walletSessionToken:r,walletCustodyEnvelope:t.context.walletCustodyEnvelope,capability:{materialActivation:n.capability.materialActivation,scope:{lifecycle_id:i.lifecycleId,root_share_epoch:i.rootShareEpoch,account_id:i.accountId,threshold_session_id:i.thresholdSessionId,signer_set_id:i.signerSetId,signing_worker_id:i.signingWorkerId,material_activation:re(n.capability.materialActivation)},applicationBinding:n.capability.applicationBinding,participantIds:n.capability.participantIds,registeredPublicKey:n.capability.registeredPublicKey,stateEpoch:n.capability.stateEpoch,activeCapabilityBinding:n.capability.activeCapabilityBinding,runtimePolicyScope:n.capability.runtimePolicyScope}}}async function Lt(e,t){let n=Mt(t),r=await e.resolvePasskeyExportContext({laneIdentity:n,materialActivation:t.materialActivation});switch(r.kind){case`ready`:return It({context:r.context,selectedLaneIdentity:n,selectedMaterialActivation:t.materialActivation});case`capability_recovery_required`:throw Error(`[SigningEngine][ed25519-export] passkey material recovery did not publish durable context`)}throw Error(`[SigningEngine][ed25519-export] unsupported passkey export context state`)}async function Rt(t,n){let r=Pt(n),i=await t.emailOtp.resolveExportContext({laneIdentity:r,materialActivation:n.materialActivation});if(!e(n.materialActivation,i.material.materialActivation)&&i.material.kind!==`sealed_export_root`)throw Error(`[SigningEngine][ed25519-export] Email OTP Yao context activation mismatch`);return{context:i,laneIdentity:r}}function zt(e){let t=e.resolved.laneIdentity.signer;return{artifactKind:_e,walletId:String(e.input.walletId),nearAccountId:String(e.input.nearAccountId),relayerUrl:e.resolved.relayerUrl,authorization:{kind:`opaque_wallet_session`,walletSessionToken:e.resolved.walletSessionToken},flowId:e.input.flowId,viewerSessionId:e.viewerSessionId,exactLane:{nearEd25519SigningKeyId:String(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,credentialIdB64u:e.resolved.laneIdentity.auth.credentialIdB64u,materialActivation:kt(e.resolved)},walletCustodyEnvelope:e.resolved.walletCustodyEnvelope,capability:e.resolved.capability,variant:e.input.options.variant,theme:e.input.options.theme??e.theme}}function Bt(e,t){let n=String(e.walletId);F(e.onEvent,{phase:t===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:t===`opened`?`waiting_for_user`:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`key_export_viewer`,overlay:t===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`}}),t===`closed`&&F(e.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}async function Vt(e,t){switch(t.laneIdentity.auth.kind){case`passkey`:break;case`email_otp`:return await Ht(e,t);default:throw t.laneIdentity.auth,Error(`[SigningEngine][ed25519-export] unsupported lane authorization method`)}let n=Lt(e,t),r=e.touchConfirm.initialize(),[i]=await Promise.all([n,r]),a=String(t.walletId),o=I(`export-ed25519-yao-viewer-session`),s=Bt.bind(void 0,{flowId:t.flowId,walletId:t.walletId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let c=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:kt(i)}),nearAccountId:t.nearAccountId,enabled:!0,task:()=>e.passkeyMpcExport.exportPrivateKeysWithUi(zt({resolved:i,viewerSessionId:o,input:t,theme:e.theme}),{onViewerLifecycle:s})});if(c.kind!==`completed`)throw Error(c.error);if(c.exportedSchemes.length!==1||c.exportedSchemes[0]!==`ed25519`)throw Error(`[SigningEngine][ed25519-export] secure export failed`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`none`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}async function Ht(e,t){let n=await Rt(e,t),r=`ed25519:${s(Uint8Array.from(n.context.material.capability.registeredPublicKey))}`,i=await We({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`email_otp_ed25519_export_auth`,walletId:t.walletId,nearAccountId:String(t.nearAccountId),nearEd25519SigningKeyId:String(n.laneIdentity.signer.nearEd25519SigningKeyId),signerSlot:n.laneIdentity.signer.signerSlot,publicKey:r,curve:`ed25519`,chain:`near`,flowId:t.flowId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let a=I(`export-ed25519-yao-viewer-session`);try{await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:r,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent});let o=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:At(n.context)}),nearAccountId:t.nearAccountId,enabled:n.context.material.kind===`active_capability`,task:()=>e.emailOtp.exportSeedWithFreshAuthorization({challengeId:i.challengeId,otpCode:i.otpCode,exportContext:n.context})});return F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),E(a)&&await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:o.publicKey,privateKey:o.privateKey,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}catch(e){throw T(),e}}function Ut(e){switch(e.kind){case`active`:case`expired`:return e;case`missing`:case`unavailable`:case`invalid`:return null;default:return e}}async function Wt(e){await e.deps.sessionLifecycle.invalidateExpiredAuthorization({state:e.state,source:e.source})}async function Gt(e){let t=await e.deps.sessionLifecycle.readAuthorization(e.request);return t.kind===`expired`&&await Wt({deps:e.deps,state:t,source:ae.operationPreflight}),t}function Kt(e){let t=Ut(e.preflightState);return t?Te({source:e.source,expiresAtMs:t.expiresAtMs,detectedAtMs:e.detectedAtMs}):null}async function qt(e,t){let n=l(t.walletSession.walletId),r=await Ot(e.laneSelection,{walletId:n,signingTarget:Ee(t.chainTarget),laneIdentity:t.laneIdentity}),i=await j(e.ecdsa.sessionStore,r);if(r.source===`active_wallet_authority`){if(i.source!==`active_wallet_authority`)throw Error(`[SigningEngine][ecdsa-export] active lane material source changed`);return{kind:`active_wallet_authority`,exportLane:r,exportMaterial:i}}if(i.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] canonical lane material source changed`);return{kind:`canonical_capability`,exportLane:r,exportMaterial:i}}function Jt(e){if(!(!e||e.source!==`canonical_capability`||!e.authorization))return e.authorization.operationCredential.walletSessionId}function Yt(e){let t=e.exportLane?.publicFacts,n=e.exportLane?h({walletId:e.exportLane.key.walletId,publicFacts:e.exportLane.publicFacts}):void 0;try{console.warn(`[SigningEngine][ecdsa-export][failure]`,{operationId:e.flowId,authMethod:e.exportLane?.authMethod,...n?{evmFamilyKeyFingerprint:n}:{},...t?{keyHandle:String(t.keyHandle)}:{},chainTargetKey:u(e.input.chainTarget),...Jt(e.exportLane)?{walletSessionId:Jt(e.exportLane)}:{},materialActivationId:e.exportLane?.laneIdentity.signer.materialActivation.activationId,freshAuthRetrySideEffectState:`not_applicable`,error:e.error instanceof Error?e.error.message:String(e.error||`unknown error`)})}catch{}}async function Xt(e,t,n){let r=l(t.walletSession.walletId);if(n.kind===`active_wallet_authority`)return await ct(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_email_otp_route_auth_ready`)return await lt(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_passkey_needs_authorization`)return await ut(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});throw n.exportMaterial,Error(`[SigningEngine][ecdsa-export] unsupported export material`)}async function Zt(e,t,n){let[r]=await Promise.all([qt(e,t),e.ecdsa.touchConfirm.initialize()]);if(r.exportLane.authorizationState===`authorization_required`)try{return await Xt(e,t,r)}catch(e){throw Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:e}),e}let i={kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization},a=await Gt({deps:e,request:{kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization,nowMs:Date.now()}});try{return await Xt(e,t,r)}catch(o){Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:o});let s=ye(o);if(n.kind===`fresh_auth_retry`||s?.kind!==`expired`)throw o;let c=Kt({source:i,preflightState:a,detectedAtMs:Date.now()});if(!c)throw o;return await Wt({deps:e,state:c,source:ae.serverRejection}),await Zt(e,t,{kind:`fresh_auth_retry`})}}async function Qt(e,t){return await Vt(e.ed25519Yao,{walletId:t.walletSession.walletId,nearAccountId:t.nearAccount.accountId,laneIdentity:t.laneIdentity,materialActivation:t.materialActivation,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent})}async function $t(e,t){return await He(t,async t=>{switch(t.kind){case`ecdsa`:return await Zt(e,t,{kind:`initial`});case`ed25519`:return await Qt(e,t)}})}async function en(e,t){return await St(e.laneSelection,t)}export{$t as exportKeypairWithUI,en as resolveExactKeyExportLane};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,S as t}from"./chains-CPmd4s9f.js";import{n}from"./walletRegistrationSetupPrewarm-CQow9u8m.js";import{t as r}from"./walletDbName-BVZhb4xF.js";import{_ as i,b as a,c as o,d as s,g as c,i as l,m as u,n as d,r as f,t as p,u as m,v as ee,y as te}from"./sessionObservationRevision-abErAhd6.js";import{a as h,c as g,i as _,l as v,n as y,o as ne,s as re,t as ie,u as ae}from"./transactionReviewAdmission-CNNho8IG.js";import{t as b}from"./events-1dzC4Ocx.js";import{t as x}from"./walletIframeIdentity-DJ0KOBHg.js";import{t as S}from"./errors-CI1xdN0d.js";import{t as C}from"./signer-worker-Bh_5foqX.js";function w(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function T(){w(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),oe(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&c(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;u()||i(r)}function oe(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const E={};let D=null,O=null;function se(e){return e.request.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?e.request.payload?.authorization?.kind===`email_otp`?k(e.kind):(D??=import(`./runtime-recovery-codes-CWmt0FDB.js`),D):k(e.kind)}function ce(){k(`auth`).catch(le)}function le(){}function k(e){let t=E[e];if(t)return t;let n=M(e);return E[e]=n,n.catch(A.bind(null,e,n)),n}function A(e,t){E[e]===t&&delete E[e]}async function j(){D??=import(`./runtime-recovery-codes-CWmt0FDB.js`),O??=Promise.all([D,import(`./mountRecoveryCodeBackupSurface-MGTl6FhG.js`)]).then(()=>void 0),await O}function M(e){switch(e){case`auth`:return import(`./runtime-auth-BAGyfscG.js`);case`near`:return import(`./runtime-near-BQX9Jk9Z.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-0TAVH1xg.js`);case`email_otp`:return import(`./runtime-email-otp-DoHa8Hif.js`);case`recovery`:return import(`./runtime-recovery-DyxJKKNw.js`);case`export`:return import(`./runtime-export-CAt17IFH.js`);case`device_link`:return import(`./runtime-device-link-DKkMLVor.js`);case`preferences`:return import(`./runtime-preferences-BuKTIpv6.js`)}return N(e)}function N(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function P(e){switch(e.type){case`PM_GET_RECENT_UNLOCKS`:case`PM_GET_CONFIRMATION_CONFIG`:return!0;case`PM_GET_EXACT_WALLET_SESSION_STATE`:{let t=e.request.payload;if(!t||typeof t!=`object`)return!1;let n=Reflect.get(t,`authenticationRead`),r=Reflect.get(t,`wallet`);return(n===`restore`||n===`current`)&&!!r&&typeof r==`object`&&Reflect.get(r,`kind`)===`current`}default:return!1}}function F(e){switch(e.type){case`PM_GET_EXACT_WALLET_SESSION_STATE`:return{revision:p(),walletId:null,state:{kind:`wallet_locked`},session:d()};case`PM_GET_RECENT_UNLOCKS`:return{walletIds:[],accountIds:[],accounts:[],lastUsedAccount:null};case`PM_GET_CONFIRMATION_CONFIG`:return{walletId:null,confirmationConfig:C,revision:0}}}let I=null;function L(){return I??=z().finally(R),I}function R(){I=null}async function z(){try{return typeof indexedDB>`u`||typeof indexedDB.databases!=`function`?!1:(await indexedDB.databases()).some(B)?await V():!0}catch{return!1}}function B(e){return e.name===r}function V(){return new Promise(e=>{let t=indexedDB.open(r);t.onupgradeneeded=()=>t.transaction?.abort(),t.onerror=()=>e(!1),t.onsuccess=()=>{let n=t.result;n.onversionchange=()=>n.close(),H(n).then(t=>{n.close(),e(t===0)},()=>{n.close(),e(!1)})}})}function H(e){let t=Array.from(e.objectStoreNames);return t.length===0?Promise.resolve(0):new Promise((n,r)=>{let i=e.transaction(t,`readonly`),a=0;for(let e of t){let t=i.objectStore(e).count();t.onsuccess=()=>{a+=t.result}}i.oncomplete=()=>n(a),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}function U(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function W(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function G(e){try{return x(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function ue(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_PREPARE_WALLET_RUNTIME`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(s(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(o(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(m(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return U(e)}function de(e){return e.kind!==`boot`}let K=!1;const fe=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function q(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function pe(t){return!e(t)||!q(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!q(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function me(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function J(){let e=new Set,t=document.querySelectorAll(`meta[name="seams-wallet-relayer-origin"]`);for(let n of t){let t=n.getAttribute(`content`)?.trim()??``,r;try{r=new URL(t)}catch{throw Error(`Invalid wallet relayer origin policy`)}let i=r.hostname===`localhost`||r.hostname.endsWith(`.localhost`)||r.hostname===`127.0.0.1`||r.hostname===`[::1]`;if(r.origin!==t||r.protocol!==`https:`&&!(r.protocol===`http:`&&i))throw Error(`Invalid wallet relayer origin policy`);e.add(t)}if(e.size===0)throw Error(`Wallet relayer origin policy is missing`);return e}function he(e){let t;try{t=new URL(e).origin}catch{throw Error(`Wallet relayer URL is invalid`)}if(!J().has(t))throw Error(`Wallet relayer origin is not approved by the wallet host`)}function Y(e){try{e.close()}catch{}}function ge(e,t){if(t===`16.0.0`)return!1;let n={expectedProtocolVersion:l,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${l}, received ${t??`missing`}`,details:n}})}catch{}return Y(e),!0}function X(e,t){return!t||t.has(e)}function Z(e,t,n,r){e.executionGeneration===t&&n(r)}function Q(e,t,n,r){return e.executionGeneration!==t||n(r)}function $(e={}){if(K)return;K=!0,T(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&j().catch(()=>void 0);let r=new Set,i=new Set,o=!1,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},u=e=>{e&&r.add(e)},d=e=>!!e&&(r.has(e)||_(e)?.cancelled===!0),f=e=>{e&&r.delete(e)},p=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},m=e=>!e||!d(e)?!1:_(e)?.cancelled?!0:(p(e),f(e),!0),x=()=>{for(let e of fe){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(b.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},C=async r=>{let l=r.data;if(!l||!t(l))return;let b=l.requestId,C=s.executionGeneration,w=Z.bind(null,s,C,c),T=null;try{if(`transactionReview`in l){if(l.type!==`PM_SIGN_AND_SEND_TX`&&l.type!==`PM_SIGN_TEMPO`)throw new h(`review_invalid_input`,`Review is unsupported for this request`);let e=g(l.transactionReview);if(e.requestId!==b)throw new h(`review_invalid_input`,`Review request identity mismatch`);let t=l.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new h(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);T=new ie(e,l.type===`PM_SIGN_TEMPO`&&l.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>w({type:`TRANSACTION_REVIEW_STATE`,requestId:b,payload:e}),e=>w({type:`ERROR`,requestId:b,payload:{code:e instanceof h?e.code:`cancelled`,message:e.message}}))}(l.type===`PM_LOCK`||l.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&y(new h(`review_identity_changed`,`The wallet session changed`));let t=ue(l);if(!de(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:b});return;case`PM_PREPARE_WALLET_RUNTIME`:X(`auth`,e.supportedRuntimeRouteKinds)&&ce(),c({type:`PONG`,requestId:b});return;case`PM_SET_CONFIG`:{let e=ee(s.configuration,te(t.request.payload));he(e.config.network.relayer.url);let r=a(s.configuration.kind===`configured`?s.configuration.config:null)!==a(e.config);if(s.configuration=e,r){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of i)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});i.clear()}s.onConfigurationChanged?.(),r&&(y(new h(`review_identity_changed`,`Wallet execution configuration changed`)),x()),c({type:`PONG`,requestId:b});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=re(t.request.payload);e&&_(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=g(r),i=_(t.requestId);if(t.requestId===e&&i&&v(t,i.metadata)){let e=new h(ae(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{ne(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:b});return}let i=e?_(e):void 0;if(i){i.cancel(new h(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:b});return}u(e),x(),e&&p(e),c({type:`PONG`,requestId:b});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-D5f-Yn9t.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-D5f-Yn9t.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!X(t.kind,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:b,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}if(b&&i.add(b),!o&&P(t)&&await L()&&!o){if(C!==s.executionGeneration||m(b))return;w({type:`PM_RESULT`,requestId:b,payload:{ok:!0,result:F(t)}});return}o=!0;let r=await se(t);if(C!==s.executionGeneration)return;await r.handleWalletHostRuntimeRequest({transactionReview:T,state:s,executionGeneration:C,req:t.request,post:Z.bind(null,s,C,c),isCancelled:Q.bind(null,s,C,d),respondIfCancelled:Q.bind(null,s,C,m)})}catch(e){if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`||T?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-CqHi6ji6.js`);if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=S(e),i=t.resolveWalletBoundaryErrorCode({requestType:l.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:l.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(l.type);c({type:`ERROR`,requestId:b,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(l.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{b&&(i.delete(b),f(b)),T?.finish()}};window.addEventListener(`message`,e=>{let t=pe(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!me(e.origin)){Y(n);return}if(!ge(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=C,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:l}})}}})}try{$()}catch(e){console.error(`[WalletHost] init failed`,e)}export{$ as t};
|
|
1
|
+
import{C as e,S as t}from"./chains-CPmd4s9f.js";import{n}from"./walletRegistrationSetupPrewarm-CQow9u8m.js";import{t as r}from"./walletDbName-BVZhb4xF.js";import{_ as i,b as a,c as o,d as s,g as c,i as l,m as u,n as d,r as f,t as p,u as m,v as ee,y as te}from"./sessionObservationRevision-abErAhd6.js";import{a as h,c as g,i as _,l as v,n as y,o as ne,s as re,t as ie,u as ae}from"./transactionReviewAdmission-CNNho8IG.js";import{t as b}from"./events-1dzC4Ocx.js";import{t as x}from"./walletIframeIdentity-DJ0KOBHg.js";import{t as S}from"./errors-CI1xdN0d.js";import{t as C}from"./signer-worker-Bh_5foqX.js";function w(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function T(){w(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),oe(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&c(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;u()||i(r)}function oe(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const E={};let D=null,O=null;function se(e){return e.request.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?e.request.payload?.authorization?.kind===`email_otp`?k(e.kind):(D??=import(`./runtime-recovery-codes-CuqYWqK7.js`),D):k(e.kind)}function ce(){k(`auth`).catch(le)}function le(){}function k(e){let t=E[e];if(t)return t;let n=M(e);return E[e]=n,n.catch(A.bind(null,e,n)),n}function A(e,t){E[e]===t&&delete E[e]}async function j(){D??=import(`./runtime-recovery-codes-CuqYWqK7.js`),O??=Promise.all([D,import(`./mountRecoveryCodeBackupSurface-D3QFgMGE.js`)]).then(()=>void 0),await O}function M(e){switch(e){case`auth`:return import(`./runtime-auth-C0V-5znH.js`);case`near`:return import(`./runtime-near-DRrdWzmr.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-CDSZ3pxS.js`);case`email_otp`:return import(`./runtime-email-otp-DXuxFOjL.js`);case`recovery`:return import(`./runtime-recovery-DlJlaZlf.js`);case`export`:return import(`./runtime-export-Ba12ChDI.js`);case`device_link`:return import(`./runtime-device-link-B1jpHQSF.js`);case`preferences`:return import(`./runtime-preferences-BWyhRaBA.js`)}return N(e)}function N(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function P(e){switch(e.type){case`PM_GET_RECENT_UNLOCKS`:case`PM_GET_CONFIRMATION_CONFIG`:return!0;case`PM_GET_EXACT_WALLET_SESSION_STATE`:{let t=e.request.payload;if(!t||typeof t!=`object`)return!1;let n=Reflect.get(t,`authenticationRead`),r=Reflect.get(t,`wallet`);return(n===`restore`||n===`current`)&&!!r&&typeof r==`object`&&Reflect.get(r,`kind`)===`current`}default:return!1}}function F(e){switch(e.type){case`PM_GET_EXACT_WALLET_SESSION_STATE`:return{revision:p(),walletId:null,state:{kind:`wallet_locked`},session:d()};case`PM_GET_RECENT_UNLOCKS`:return{walletIds:[],accountIds:[],accounts:[],lastUsedAccount:null};case`PM_GET_CONFIRMATION_CONFIG`:return{walletId:null,confirmationConfig:C,revision:0}}}let I=null;function L(){return I??=z().finally(R),I}function R(){I=null}async function z(){try{return typeof indexedDB>`u`||typeof indexedDB.databases!=`function`?!1:(await indexedDB.databases()).some(B)?await V():!0}catch{return!1}}function B(e){return e.name===r}function V(){return new Promise(e=>{let t=indexedDB.open(r);t.onupgradeneeded=()=>t.transaction?.abort(),t.onerror=()=>e(!1),t.onsuccess=()=>{let n=t.result;n.onversionchange=()=>n.close(),H(n).then(t=>{n.close(),e(t===0)},()=>{n.close(),e(!1)})}})}function H(e){let t=Array.from(e.objectStoreNames);return t.length===0?Promise.resolve(0):new Promise((n,r)=>{let i=e.transaction(t,`readonly`),a=0;for(let e of t){let t=i.objectStore(e).count();t.onsuccess=()=>{a+=t.result}}i.oncomplete=()=>n(a),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}function U(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function W(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function G(e){try{return x(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function ue(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_PREPARE_WALLET_RUNTIME`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(s(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(o(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(m(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return U(e)}function de(e){return e.kind!==`boot`}let K=!1;const fe=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function q(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function pe(t){return!e(t)||!q(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!q(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function me(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function J(){let e=new Set,t=document.querySelectorAll(`meta[name="seams-wallet-relayer-origin"]`);for(let n of t){let t=n.getAttribute(`content`)?.trim()??``,r;try{r=new URL(t)}catch{throw Error(`Invalid wallet relayer origin policy`)}let i=r.hostname===`localhost`||r.hostname.endsWith(`.localhost`)||r.hostname===`127.0.0.1`||r.hostname===`[::1]`;if(r.origin!==t||r.protocol!==`https:`&&!(r.protocol===`http:`&&i))throw Error(`Invalid wallet relayer origin policy`);e.add(t)}if(e.size===0)throw Error(`Wallet relayer origin policy is missing`);return e}function he(e){let t;try{t=new URL(e).origin}catch{throw Error(`Wallet relayer URL is invalid`)}if(!J().has(t))throw Error(`Wallet relayer origin is not approved by the wallet host`)}function Y(e){try{e.close()}catch{}}function ge(e,t){if(t===`16.0.0`)return!1;let n={expectedProtocolVersion:l,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${l}, received ${t??`missing`}`,details:n}})}catch{}return Y(e),!0}function X(e,t){return!t||t.has(e)}function Z(e,t,n,r){e.executionGeneration===t&&n(r)}function Q(e,t,n,r){return e.executionGeneration!==t||n(r)}function $(e={}){if(K)return;K=!0,T(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&j().catch(()=>void 0);let r=new Set,i=new Set,o=!1,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},u=e=>{e&&r.add(e)},d=e=>!!e&&(r.has(e)||_(e)?.cancelled===!0),f=e=>{e&&r.delete(e)},p=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},m=e=>!e||!d(e)?!1:_(e)?.cancelled?!0:(p(e),f(e),!0),x=()=>{for(let e of fe){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(b.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},C=async r=>{let l=r.data;if(!l||!t(l))return;let b=l.requestId,C=s.executionGeneration,w=Z.bind(null,s,C,c),T=null;try{if(`transactionReview`in l){if(l.type!==`PM_SIGN_AND_SEND_TX`&&l.type!==`PM_SIGN_TEMPO`)throw new h(`review_invalid_input`,`Review is unsupported for this request`);let e=g(l.transactionReview);if(e.requestId!==b)throw new h(`review_invalid_input`,`Review request identity mismatch`);let t=l.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new h(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);T=new ie(e,l.type===`PM_SIGN_TEMPO`&&l.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>w({type:`TRANSACTION_REVIEW_STATE`,requestId:b,payload:e}),e=>w({type:`ERROR`,requestId:b,payload:{code:e instanceof h?e.code:`cancelled`,message:e.message}}))}(l.type===`PM_LOCK`||l.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&y(new h(`review_identity_changed`,`The wallet session changed`));let t=ue(l);if(!de(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:b});return;case`PM_PREPARE_WALLET_RUNTIME`:X(`auth`,e.supportedRuntimeRouteKinds)&&ce(),c({type:`PONG`,requestId:b});return;case`PM_SET_CONFIG`:{let e=ee(s.configuration,te(t.request.payload));he(e.config.network.relayer.url);let r=a(s.configuration.kind===`configured`?s.configuration.config:null)!==a(e.config);if(s.configuration=e,r){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of i)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});i.clear()}s.onConfigurationChanged?.(),r&&(y(new h(`review_identity_changed`,`Wallet execution configuration changed`)),x()),c({type:`PONG`,requestId:b});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=re(t.request.payload);e&&_(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=g(r),i=_(t.requestId);if(t.requestId===e&&i&&v(t,i.metadata)){let e=new h(ae(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{ne(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:b});return}let i=e?_(e):void 0;if(i){i.cancel(new h(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:b});return}u(e),x(),e&&p(e),c({type:`PONG`,requestId:b});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-CpDMkSPm.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-CpDMkSPm.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!X(t.kind,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:b,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}if(b&&i.add(b),!o&&P(t)&&await L()&&!o){if(C!==s.executionGeneration||m(b))return;w({type:`PM_RESULT`,requestId:b,payload:{ok:!0,result:F(t)}});return}o=!0;let r=await se(t);if(C!==s.executionGeneration)return;await r.handleWalletHostRuntimeRequest({transactionReview:T,state:s,executionGeneration:C,req:t.request,post:Z.bind(null,s,C,c),isCancelled:Q.bind(null,s,C,d),respondIfCancelled:Q.bind(null,s,C,m)})}catch(e){if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`||T?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-CqHi6ji6.js`);if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=S(e),i=t.resolveWalletBoundaryErrorCode({requestType:l.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:l.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(l.type);c({type:`ERROR`,requestId:b,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(l.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{b&&(i.delete(b),f(b)),T?.finish()}};window.addEventListener(`message`,e=>{let t=pe(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!me(e.origin)){Y(n);return}if(!ge(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=C,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:l}})}}})}try{$()}catch(e){console.error(`[WalletHost] init failed`,e)}export{$ as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e}from"./base64-BmKR3UqU.js";import"./capabilityKinds-CqHVzVsJ.js";import{t}from"./errors-CI1xdN0d.js";import"./accountIds-BzZs7YoX.js";import"./signerDomain-YEHkugWX.js";import{D as n,c as r,f as i,n as a,t as o,u as s,y as c}from"./adapters-
|
|
1
|
+
import{i as e}from"./base64-BmKR3UqU.js";import"./capabilityKinds-CqHVzVsJ.js";import{t}from"./errors-CI1xdN0d.js";import"./accountIds-BzZs7YoX.js";import"./signerDomain-YEHkugWX.js";import{D as n,c as r,f as i,n as a,t as o,u as s,y as c}from"./adapters-CgJpSAxH.js";import{n as l,r as u}from"./collectAuthenticationCredentialForChallengeB64u-CSwy9csE.js";import{i as d,t as f}from"./appearance-ZGVLwA4N.js";import"./appearance-token-vars-BA3KQyEE.js";import{n as p,r as m}from"./export-viewer-host-C9n-62Pi.js";function h(){return e(crypto.getRandomValues(new Uint8Array(32)).buffer)}function g(e){switch(e.kind){case`near_wallet`:return e.nearAccountId;case`evm_wallet`:return e.walletId;default:{let t=e;throw Error(`Unsupported local key export subject: ${String(t)}`)}}}async function _(e,t,n,r){await m({theme:t.theme||r||`dark`,variant:t.variant||(n.uiMode===`drawer`?`drawer`:`modal`),accountId:g(t.subject),sessionId:t.viewerSessionId,publicKey:t.publicKey,privateKey:t.privateKey,keys:Array.isArray(t.keys)?t.keys:void 0,guidance:t.guidance,appearance:f({getAppearance:e.getAppearance,requestedMode:t.theme}),loading:t.loading===!0,errorMessage:t.errorMessage,onLifecycle:t.onLifecycle,surfaceMeasurementBinding:e.surfaceMeasurementBinding})}function v(e){try{return{rpId:e.security.getRpId()}}catch{return{}}}async function y(e){switch(e.payload.subject.kind){case`near_wallet`:return await l({touchIdPrompt:e.ctx.touchIdPrompt,nearAccountId:e.payload.subject.nearAccountId,credentialIdB64u:e.payload.credentialIdB64u,challengeB64u:e.challengeB64u,includeSecondPrfOutput:!0});case`evm_wallet`:return await u({touchIdPrompt:e.ctx.touchIdPrompt,walletId:e.payload.subject.walletId,credentialIdB64u:e.payload.credentialIdB64u,challengeB64u:e.challengeB64u,includeSecondPrfOutput:!0});default:{let t=e.payload.subject;throw Error(`Unsupported local key export subject: ${String(t)}`)}}}async function b(e,l,u,f){let{confirmationConfig:m,transactionSummary:g,theme:b}=f,x=a(e),S=o({adapters:x,worker:u,request:l,confirmationConfig:m,transactionSummary:g,theme:b,surface:{kind:`mount_new`}});if(l.type===d.SHOW_SECURE_PRIVATE_KEY_UI)try{await _(e,l.payload,m,b),S.confirmAndCloseModal({requestId:l.requestId,intentDigest:c(l),confirmed:!0});return}catch(e){return S.confirmAndCloseModal({requestId:l.requestId,intentDigest:c(l),confirmed:!1,error:t(e)||`Failed to render export UI`})}if(l.type===d.AUTHORIZE_KEY_EXPORT){p();let a=r()?n():m,o=String(l.payload?.challengeB64u||``).trim()||h();if(a.kind!==`silent`){try{let e=g.operation,t=g.warning;g.title||=e||`Export Private Key`,g.body||=t||`Confirm to authenticate with your passkey.`}catch{}let e=v(x),{confirmed:t,error:n}=await S.promptUser({securityContext:e});if(!t)return S.confirmAndCloseModal({requestId:l.requestId,intentDigest:c(l),confirmed:!1,error:n})}try{let t=await y({ctx:e,payload:l.payload,challengeB64u:o});return S.confirmAndCloseModal({requestId:l.requestId,intentDigest:c(l),confirmed:!0,credential:t})}catch(e){let n=i(e);return S.confirmAndCloseModal({requestId:l.requestId,intentDigest:c(l),confirmed:!1,error:n?s.cancelled:t(e)||s.collectCredentialsFailed})}}}export{b as handleLocalOnlyFlow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./events-1dzC4Ocx.js";import{a as t,c as n,d as r,f as i,h as a,l as o,m as s,n as c,o as l,p as u,s as d,t as f,u as p}from"./appearance-token-vars-Bu6YUWmf.js";import{i as m,n as h,r as g,t as _}from"./ConfirmationDrawer-B7RCp58z.js";function v(e){throw Error(`Unexpected private key reveal state: ${String(e)}`)}function y(e){switch(e){case`secp256k1`:return{prefix:`0x`,alphabet:`0123456789abcdef`,slotCount:64};case`ed25519`:return{prefix:`ed25519:`,alphabet:`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,slotCount:88};default:return v(e)}}function b(e){return e[Math.floor(Math.random()*e.length)]??e[0]??`x`}function x(e,t){return e+Math.random()*(t-e)}function S(e,t,n){let r=[];for(let i=0;i<e.slotCount;i+=1)r.push({glyph:t?`x`:b(e.alphabet),nextChangeAtMs:t?1/0:n+i*37%90});return r}function C(e,t,n,r){let i=y(t);return{kind:`spinning`,entryKey:e,prefix:i.prefix,alphabet:i.alphabet,slots:S(i,n,r)}}function w(e){if(!e)return``;let t=(e.startsWith(`ed25519:`)?8:0)+6,n=Math.max(t,e.length-6);return`${e.slice(0,t)}${`x`.repeat(n-t)}${e.slice(n)}`}function T(e,t,n){let r=t.startsWith(e.prefix)?e.prefix:``,i=Array.from(t.slice(r.length)),a=i.length===e.slots.length?e.slots:i.map((t,r)=>({glyph:b(e.alphabet),nextChangeAtMs:n+r*37%90}));return{kind:`settling`,entryKey:e.entryKey,prefix:r,alphabet:e.alphabet,slots:a,targetSlots:i,lockedSlots:0,startedAtMs:n}}function E(e,t){let n=Math.max(1,e.targetSlots.length-1),r=0;for(let i=0;i<e.targetSlots.length;i+=1){let a=i/n*700;t>=e.startedAtMs+a+300&&(r+=1)}return r}function D(e,t,n){let r=t/Math.max(1,e.targetSlots.length-1)*700,i=e.startedAtMs+r;return Math.max(0,Math.min(1,(n-i)/300))}function O(e,t,n){let r=null;for(let i=0;i<e.length;i+=1){let a=e[i];!a||n<a.nextChangeAtMs||(r===null&&(r=[...e]),r[i]={glyph:b(t),nextChangeAtMs:n+x(90,150)})}return r??e}function k(e,t,n){let r=null;for(let i=0;i<e.slots.length;i+=1){let a=e.slots[i];if(!a)continue;if(i<t){let t=e.targetSlots[i]??a.glyph;if(a.glyph===t&&a.nextChangeAtMs===1/0)continue;r===null&&(r=[...e.slots]),r[i]={glyph:t,nextChangeAtMs:1/0};continue}if(n<a.nextChangeAtMs)continue;let o=D(e,i,n)*90;r===null&&(r=[...e.slots]),r[i]={glyph:b(e.alphabet),nextChangeAtMs:n+x(90+o,150+o)}}return r??e.slots}function A(e,t){if(e.kind===`spinning`){let n=O(e.slots,e.alphabet,t);return n===e.slots?e:{...e,slots:n}}if(e.kind===`settling`){let n=E(e,t);if(n>=e.targetSlots.length)return{kind:`settled`,entryKey:e.entryKey};let r=k(e,n,t);return r===e.slots&&n===e.lockedSlots?e:{...e,slots:r,lockedSlots:n}}return v(e)}function j({model:e,onClose:t}){let n=d(),i=e.kind===`failed`?[]:e.entries,a=i.length===0||i.some(M);return o(`div`,{class:`seams-export-key-viewer`,"data-seams-drawer-no-drag":!0,onPointerDown:P,onMouseDown:P,onTouchStart:P,children:o(`div`,{class:`content`,children:[o(`div`,{class:`seams-export-header`,children:[o(`h2`,{class:`title`,children:o(l,{message:`Exported Keys`})}),t&&o(`button`,{type:`button`,class:`seams-export-modal-close`,"aria-label":r(n,`Close exported keys`),onClick:t,children:`×`})]}),e.kind===`failed`&&o(`div`,{class:`error-banner`,role:`alert`,children:o(l,{copy:e.message})}),o(`div`,{class:`fields`,children:[a&&o(`div`,{class:`field`,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Near Account ID`})}),o(`div`,{class:`field-value`,children:o(`span`,{class:`value`,children:e.accountId||`—`})})]}),i.length>0?i.map(N):o(`div`,{class:`field`,children:o(`div`,{class:`field-value`,children:o(`span`,{class:`muted`,children:e.kind===`loading`?o(l,{message:`Preparing private key…`}):o(l,{message:`No keys available`})})})})]}),e.guidance&&o(F,{guidance:e.guidance}),o(`div`,{class:`warning`,children:o(l,{message:`Warning: your private keys grant full control of your account and funds. Keep it in a secret place.`})})]})})}function M(e){return e.scheme===`ed25519`}function N(e){return o(L,{entry:e},e.id)}function P(e){e.stopPropagation()}function F({guidance:e}){return o(`div`,{class:`warning`,children:[o(`strong`,{children:o(l,{copy:e.title||`Next Steps`})}),e.body&&o(`div`,{children:o(l,{copy:e.body})}),e.steps?.length?o(`ol`,{children:e.steps.map(I)}):null]})}function I(e,t){return o(`li`,{children:o(l,{copy:e})},t)}var L=class extends i{static contextType=t;state={reveal:null,publicCopied:!1,privateCopied:!1};root=u();frame=null;timers=new Map;generation=0;copyLifetime=new AbortController;active=!1;componentDidMount(){this.active=!0,this.reset(this.props.entry)}componentWillReceiveProps(e){R(this.props.entry,e.entry)||this.reset(e.entry)}componentDidUpdate(){this.schedule()}componentWillUnmount(){this.active=!1,this.clearPending(),this.state.reveal=null}clearPending(){this.generation+=1,this.copyLifetime.abort();let e=this.root.current?.ownerDocument.defaultView;this.frame!==null&&e?.cancelAnimationFrame(this.frame),this.frame=null;for(let t of this.timers.values())e?.clearTimeout(t);this.timers.clear()}reset(e){this.clearPending(),this.copyLifetime=new AbortController;let t=this.root.current.ownerDocument.defaultView,n=t.matchMedia(`(prefers-reduced-motion: reduce)`).matches,r=t.performance.now(),i=null;switch(e.material.kind){case`loading`:i=C(e.id,e.scheme,n,r);break;case`ready`:i=n?{kind:`settled`,entryKey:e.id}:T(C(e.id,e.scheme,!1,r),w(e.material.value),r);break;case`unavailable`:break;default:H(e.material)}this.setState({reveal:i,publicCopied:!1,privateCopied:!1})}schedule(){let e=this.state.reveal;if(!this.active||this.frame!==null||!e||e.kind===`settled`)return;let t=this.root.current.ownerDocument.defaultView;t.matchMedia(`(prefers-reduced-motion: reduce)`).matches||(this.frame=t.requestAnimationFrame(this.tick))}tick=e=>{this.frame=null;let t=this.state.reveal;if(!this.active||!t||t.kind===`settled`)return;let n=A(t,e);n!==t&&this.setState({reveal:n}),this.schedule()};copyPublic=()=>{this.copy(`public`)};copyPrivate=()=>{this.copy(`private`)};clearPublic=()=>{this.timers.delete(`public`),this.active&&this.setState({publicCopied:!1})};clearPrivate=()=>{this.timers.delete(`private`),this.active&&this.setState({privateCopied:!1})};async copy(e){let t=this.props.entry;if(!this.active||e===`private`&&(t.material.kind!==`ready`||this.state.reveal?.kind!==`settled`))return;let n=t.publicKey;if(e===`private`){if(t.material.kind!==`ready`)return;n=t.material.value}if(!n)return;let r=this.generation,i=this.root.current,a=i.ownerDocument.defaultView;if(a.focus(),!await m(i,n,this.copyLifetime.signal).catch(z)||!this.active||r!==this.generation)return;let o=this.timers.get(e);o!==void 0&&a.clearTimeout(o),e===`public`?this.setState({publicCopied:!0}):this.setState({privateCopied:!0}),this.timers.set(e,a.setTimeout(e===`public`?this.clearPublic:this.clearPrivate,3e3))}render(){let e=this.props.entry,t=e.material.kind===`ready`&&this.state.reveal?.kind===`settled`;return o(`div`,{class:`key-card`,ref:this.root,children:[o(`div`,{class:`key-title`,children:o(l,{copy:e.label})}),e.address&&o(`div`,{class:`field`,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Address`})}),o(`div`,{class:`field-value`,children:o(`span`,{class:`value`,children:e.address})})]}),e.scheme===`ed25519`&&o(`button`,{type:`button`,class:`field copy-field${this.state.publicCopied?` copied`:``}`,"aria-label":p(this.context,this.state.publicCopied?`Public key copied`:`Copy public key`),disabled:!e.publicKey,onClick:this.copyPublic,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Public Key`})}),o(`div`,{class:`field-value`,children:[o(`span`,{class:`value`,children:e.publicKey||`—`}),o(g,{})]})]}),o(`button`,{type:`button`,class:`field copy-field${this.state.privateCopied?` copied`:``}`,"aria-label":p(this.context,this.state.privateCopied?`Private key copied`:`Copy private key`),disabled:!t,onClick:this.copyPrivate,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Private Key`})}),o(`div`,{class:`field-value`,children:[o(`span`,{class:`value private-key`,children:o(B,{material:e.material,reveal:this.state.reveal})}),o(g,{})]})]})]})}};function R(e,t){return e.id===t.id&&e.scheme===t.scheme&&e.publicKey===t.publicKey&&e.material.kind===t.material.kind&&e.material.value===t.material.value}function z(){return!1}function B({material:e,reveal:t}){return t&&t.kind!==`settled`?o(a,{children:[o(`span`,{class:`private-key-reel`,"aria-hidden":`true`,children:[o(`span`,{class:`reel-prefix`,children:t.prefix}),V(t)]}),o(`span`,{class:`seams-sr-only`,role:`status`,children:o(l,{message:`Decrypting private key`})})]}):e.kind===`ready`?o(a,{children:[o(`span`,{children:w(e.value)}),o(`span`,{class:`seams-sr-only`,role:`status`,children:o(l,{message:`Private key ready`})})]}):o(`span`,{class:`muted`,children:`—`})}function V(e){let t=e.kind===`settling`?e.lockedSlots:0,n=[];for(let r=0;r<e.slots.length;r+=1)n.push(o(`span`,{class:`reel-slot${r<t?` settled`:``}`,children:e.slots[r].glyph},r));return n}function H(e){throw Error(`Unexpected export key material: ${String(e)}`)}let U=0;var W=class{element;styles;context;state;constructor(t){this.styles=c(t.parent.ownerDocument),this.context=t.context,this.state={kind:`mounted`,onClosed:t.onClosed},this.element=t.parent.ownerDocument.createElement(`div`),this.element.id=`seams-export-surface-${++U}`,this.element.className=`seams-wallet-ui seams-export-surface`,this.element.dataset.seamsExportSurface=t.context,this.element.addEventListener(e.TX_CONFIRMER_CANCEL,this.handleCancel),t.parent.appendChild(this.element);try{this.update(t.model)}catch(e){throw this.remove(),e}}update(e){if(this.state.kind!==`disposed`){if(this.element.lang=e.appearance.locale??`en`,this.element.dataset.theme=e.appearance.theme.mode,this.element.dataset.seamsExportVariant=e.variant,this.styles.setDynamicRule(this.element.id,f(this.element.id,e.appearance)),e.variant===`modal`){s(n(e.appearance.locale??`en`,o(h,{context:this.context,label:`Exported Keys`,onCancel:this.dispose,children:o(j,{model:e.content,onClose:this.dispose})})),this.element);return}s(n(e.appearance.locale??`en`,o(_,{context:this.context,label:`Exported Keys`,dismissOnBackdrop:!1,styles:this.styles,state:{kind:`open`,interaction:`ready`},onCancel:this.dispose,children:o(j,{model:e.content})})),this.element)}}dispose=()=>{if(this.state.kind===`disposed`)return;let e=this.state.onClosed;this.remove(),e()};handleCancel=()=>{this.dispose()};remove(){this.state={kind:`disposed`},this.element.removeEventListener(e.TX_CONFIRMER_CANCEL,this.handleCancel),s(null,this.element),this.styles.deleteDynamicRule(this.element.id),this.element.remove()}};function G(e){return new W(e)}export{G as mountExportPrivateKeySurface};
|
|
1
|
+
import{t as e}from"./events-1dzC4Ocx.js";import{a as t,c as n,d as r,f as i,h as a,l as o,m as s,n as c,o as l,p as u,s as d,t as f,u as p}from"./appearance-token-vars-BA3KQyEE.js";import{i as m,n as h,r as g,t as _}from"./ConfirmationDrawer-Ck33ZmU-.js";function v(e){throw Error(`Unexpected private key reveal state: ${String(e)}`)}function y(e){switch(e){case`secp256k1`:return{prefix:`0x`,alphabet:`0123456789abcdef`,slotCount:64};case`ed25519`:return{prefix:`ed25519:`,alphabet:`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,slotCount:88};default:return v(e)}}function b(e){return e[Math.floor(Math.random()*e.length)]??e[0]??`x`}function x(e,t){return e+Math.random()*(t-e)}function S(e,t,n){let r=[];for(let i=0;i<e.slotCount;i+=1)r.push({glyph:t?`x`:b(e.alphabet),nextChangeAtMs:t?1/0:n+i*37%90});return r}function C(e,t,n,r){let i=y(t);return{kind:`spinning`,entryKey:e,prefix:i.prefix,alphabet:i.alphabet,slots:S(i,n,r)}}function w(e){if(!e)return``;let t=(e.startsWith(`ed25519:`)?8:0)+6,n=Math.max(t,e.length-6);return`${e.slice(0,t)}${`x`.repeat(n-t)}${e.slice(n)}`}function T(e,t,n){let r=t.startsWith(e.prefix)?e.prefix:``,i=Array.from(t.slice(r.length)),a=i.length===e.slots.length?e.slots:i.map((t,r)=>({glyph:b(e.alphabet),nextChangeAtMs:n+r*37%90}));return{kind:`settling`,entryKey:e.entryKey,prefix:r,alphabet:e.alphabet,slots:a,targetSlots:i,lockedSlots:0,startedAtMs:n}}function E(e,t){let n=Math.max(1,e.targetSlots.length-1),r=0;for(let i=0;i<e.targetSlots.length;i+=1){let a=i/n*700;t>=e.startedAtMs+a+300&&(r+=1)}return r}function D(e,t,n){let r=t/Math.max(1,e.targetSlots.length-1)*700,i=e.startedAtMs+r;return Math.max(0,Math.min(1,(n-i)/300))}function O(e,t,n){let r=null;for(let i=0;i<e.length;i+=1){let a=e[i];!a||n<a.nextChangeAtMs||(r===null&&(r=[...e]),r[i]={glyph:b(t),nextChangeAtMs:n+x(90,150)})}return r??e}function k(e,t,n){let r=null;for(let i=0;i<e.slots.length;i+=1){let a=e.slots[i];if(!a)continue;if(i<t){let t=e.targetSlots[i]??a.glyph;if(a.glyph===t&&a.nextChangeAtMs===1/0)continue;r===null&&(r=[...e.slots]),r[i]={glyph:t,nextChangeAtMs:1/0};continue}if(n<a.nextChangeAtMs)continue;let o=D(e,i,n)*90;r===null&&(r=[...e.slots]),r[i]={glyph:b(e.alphabet),nextChangeAtMs:n+x(90+o,150+o)}}return r??e.slots}function A(e,t){if(e.kind===`spinning`){let n=O(e.slots,e.alphabet,t);return n===e.slots?e:{...e,slots:n}}if(e.kind===`settling`){let n=E(e,t);if(n>=e.targetSlots.length)return{kind:`settled`,entryKey:e.entryKey};let r=k(e,n,t);return r===e.slots&&n===e.lockedSlots?e:{...e,slots:r,lockedSlots:n}}return v(e)}function j({model:e,onClose:t}){let n=d(),i=e.kind===`failed`?[]:e.entries,a=i.length===0||i.some(M);return o(`div`,{class:`seams-export-key-viewer`,"data-seams-drawer-no-drag":!0,onPointerDown:P,onMouseDown:P,onTouchStart:P,children:o(`div`,{class:`content`,children:[o(`div`,{class:`seams-export-header`,children:[o(`h2`,{class:`title`,children:o(l,{message:`Exported Keys`})}),t&&o(`button`,{type:`button`,class:`seams-export-modal-close`,"aria-label":r(n,`Close exported keys`),onClick:t,children:`×`})]}),e.kind===`failed`&&o(`div`,{class:`error-banner`,role:`alert`,children:o(l,{copy:e.message})}),o(`div`,{class:`fields`,children:[a&&o(`div`,{class:`field`,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Near Account ID`})}),o(`div`,{class:`field-value`,children:o(`span`,{class:`value`,children:e.accountId||`—`})})]}),i.length>0?i.map(N):o(`div`,{class:`field`,children:o(`div`,{class:`field-value`,children:o(`span`,{class:`muted`,children:e.kind===`loading`?o(l,{message:`Preparing private key…`}):o(l,{message:`No keys available`})})})})]}),e.guidance&&o(F,{guidance:e.guidance}),o(`div`,{class:`warning`,children:o(l,{message:`Warning: your private keys grant full control of your account and funds. Keep it in a secret place.`})})]})})}function M(e){return e.scheme===`ed25519`}function N(e){return o(L,{entry:e},e.id)}function P(e){e.stopPropagation()}function F({guidance:e}){return o(`div`,{class:`warning`,children:[o(`strong`,{children:o(l,{copy:e.title||`Next Steps`})}),e.body&&o(`div`,{children:o(l,{copy:e.body})}),e.steps?.length?o(`ol`,{children:e.steps.map(I)}):null]})}function I(e,t){return o(`li`,{children:o(l,{copy:e})},t)}var L=class extends i{static contextType=t;state={reveal:null,publicCopied:!1,privateCopied:!1};root=u();frame=null;timers=new Map;generation=0;copyLifetime=new AbortController;active=!1;componentDidMount(){this.active=!0,this.reset(this.props.entry)}componentWillReceiveProps(e){R(this.props.entry,e.entry)||this.reset(e.entry)}componentDidUpdate(){this.schedule()}componentWillUnmount(){this.active=!1,this.clearPending(),this.state.reveal=null}clearPending(){this.generation+=1,this.copyLifetime.abort();let e=this.root.current?.ownerDocument.defaultView;this.frame!==null&&e?.cancelAnimationFrame(this.frame),this.frame=null;for(let t of this.timers.values())e?.clearTimeout(t);this.timers.clear()}reset(e){this.clearPending(),this.copyLifetime=new AbortController;let t=this.root.current.ownerDocument.defaultView,n=t.matchMedia(`(prefers-reduced-motion: reduce)`).matches,r=t.performance.now(),i=null;switch(e.material.kind){case`loading`:i=C(e.id,e.scheme,n,r);break;case`ready`:i=n?{kind:`settled`,entryKey:e.id}:T(C(e.id,e.scheme,!1,r),w(e.material.value),r);break;case`unavailable`:break;default:H(e.material)}this.setState({reveal:i,publicCopied:!1,privateCopied:!1})}schedule(){let e=this.state.reveal;if(!this.active||this.frame!==null||!e||e.kind===`settled`)return;let t=this.root.current.ownerDocument.defaultView;t.matchMedia(`(prefers-reduced-motion: reduce)`).matches||(this.frame=t.requestAnimationFrame(this.tick))}tick=e=>{this.frame=null;let t=this.state.reveal;if(!this.active||!t||t.kind===`settled`)return;let n=A(t,e);n!==t&&this.setState({reveal:n}),this.schedule()};copyPublic=()=>{this.copy(`public`)};copyPrivate=()=>{this.copy(`private`)};clearPublic=()=>{this.timers.delete(`public`),this.active&&this.setState({publicCopied:!1})};clearPrivate=()=>{this.timers.delete(`private`),this.active&&this.setState({privateCopied:!1})};async copy(e){let t=this.props.entry;if(!this.active||e===`private`&&(t.material.kind!==`ready`||this.state.reveal?.kind!==`settled`))return;let n=t.publicKey;if(e===`private`){if(t.material.kind!==`ready`)return;n=t.material.value}if(!n)return;let r=this.generation,i=this.root.current,a=i.ownerDocument.defaultView;if(a.focus(),!await m(i,n,this.copyLifetime.signal).catch(z)||!this.active||r!==this.generation)return;let o=this.timers.get(e);o!==void 0&&a.clearTimeout(o),e===`public`?this.setState({publicCopied:!0}):this.setState({privateCopied:!0}),this.timers.set(e,a.setTimeout(e===`public`?this.clearPublic:this.clearPrivate,3e3))}render(){let e=this.props.entry,t=e.material.kind===`ready`&&this.state.reveal?.kind===`settled`;return o(`div`,{class:`key-card`,ref:this.root,children:[o(`div`,{class:`key-title`,children:o(l,{copy:e.label})}),e.address&&o(`div`,{class:`field`,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Address`})}),o(`div`,{class:`field-value`,children:o(`span`,{class:`value`,children:e.address})})]}),e.scheme===`ed25519`&&o(`button`,{type:`button`,class:`field copy-field${this.state.publicCopied?` copied`:``}`,"aria-label":p(this.context,this.state.publicCopied?`Public key copied`:`Copy public key`),disabled:!e.publicKey,onClick:this.copyPublic,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Public Key`})}),o(`div`,{class:`field-value`,children:[o(`span`,{class:`value`,children:e.publicKey||`—`}),o(g,{})]})]}),o(`button`,{type:`button`,class:`field copy-field${this.state.privateCopied?` copied`:``}`,"aria-label":p(this.context,this.state.privateCopied?`Private key copied`:`Copy private key`),disabled:!t,onClick:this.copyPrivate,children:[o(`div`,{class:`field-label`,children:o(l,{message:`Private Key`})}),o(`div`,{class:`field-value`,children:[o(`span`,{class:`value private-key`,children:o(B,{material:e.material,reveal:this.state.reveal})}),o(g,{})]})]})]})}};function R(e,t){return e.id===t.id&&e.scheme===t.scheme&&e.publicKey===t.publicKey&&e.material.kind===t.material.kind&&e.material.value===t.material.value}function z(){return!1}function B({material:e,reveal:t}){return t&&t.kind!==`settled`?o(a,{children:[o(`span`,{class:`private-key-reel`,"aria-hidden":`true`,children:[o(`span`,{class:`reel-prefix`,children:t.prefix}),V(t)]}),o(`span`,{class:`seams-sr-only`,role:`status`,children:o(l,{message:`Decrypting private key`})})]}):e.kind===`ready`?o(a,{children:[o(`span`,{children:w(e.value)}),o(`span`,{class:`seams-sr-only`,role:`status`,children:o(l,{message:`Private key ready`})})]}):o(`span`,{class:`muted`,children:`—`})}function V(e){let t=e.kind===`settling`?e.lockedSlots:0,n=[];for(let r=0;r<e.slots.length;r+=1)n.push(o(`span`,{class:`reel-slot${r<t?` settled`:``}`,children:e.slots[r].glyph},r));return n}function H(e){throw Error(`Unexpected export key material: ${String(e)}`)}let U=0;var W=class{element;styles;context;state;constructor(t){this.styles=c(t.parent.ownerDocument),this.context=t.context,this.state={kind:`mounted`,onClosed:t.onClosed},this.element=t.parent.ownerDocument.createElement(`div`),this.element.id=`seams-export-surface-${++U}`,this.element.className=`seams-wallet-ui seams-export-surface`,this.element.dataset.seamsExportSurface=t.context,this.element.addEventListener(e.TX_CONFIRMER_CANCEL,this.handleCancel),t.parent.appendChild(this.element);try{this.update(t.model)}catch(e){throw this.remove(),e}}update(e){if(this.state.kind!==`disposed`){if(this.element.lang=e.appearance.locale??`en`,this.element.dataset.theme=e.appearance.theme.mode,this.element.dataset.seamsExportVariant=e.variant,this.styles.setDynamicRule(this.element.id,f(this.element.id,e.appearance)),e.variant===`modal`){s(n(e.appearance.locale??`en`,o(h,{context:this.context,label:`Exported Keys`,onCancel:this.dispose,children:o(j,{model:e.content,onClose:this.dispose})})),this.element);return}s(n(e.appearance.locale??`en`,o(_,{context:this.context,label:`Exported Keys`,dismissOnBackdrop:!1,styles:this.styles,state:{kind:`open`,interaction:`ready`},onCancel:this.dispose,children:o(j,{model:e.content})})),this.element)}}dispose=()=>{if(this.state.kind===`disposed`)return;let e=this.state.onClosed;this.remove(),e()};handleCancel=()=>{this.dispose()};remove(){this.state={kind:`disposed`},this.element.removeEventListener(e.TX_CONFIRMER_CANCEL,this.handleCancel),s(null,this.element),this.styles.deleteDynamicRule(this.element.id),this.element.remove()}};function G(e){return new W(e)}export{G as mountExportPrivateKeySurface};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,f as r,h as i,l as a,m as o,n as s,o as c,p as l,t as u}from"./appearance-token-vars-
|
|
1
|
+
import{a as e,c as t,d as n,f as r,h as i,l as a,m as o,n as s,o as c,p as l,t as u}from"./appearance-token-vars-BA3KQyEE.js";function d(e){throw Error(`Unhandled recovery-code state: ${String(e)}`)}function f(e,t){return e instanceof Error&&e.message.trim()?e.message:t}function p(e){switch(e.kind){case`direct_backup`:return{kind:`recovery_codes`,request:e.request};case`account_menu`:return{kind:`summary`,walletId:e.walletId,loadState:{kind:`loading`},actionError:null};default:return d(e)}}function m(e){return{viewState:p(e),acknowledged:!1,statusMessage:``,copied:!1}}function h(e){switch(e.kind){case`summary`:case`opening`:case`recovery_codes`:return e.kind;default:return d(e)}}function g(e){switch(e.kind){case`ready`:return e.pendingLocalBackup||e.backupOutstanding?`Backup needed`:`Backed up`;case`no_recovery_set`:return`No recovery set`;case`unauthorized`:return`Authorization required`;case`transport_failed`:return`Could not load`;default:return d(e)}}function _(e){return e.kind===`loaded`&&e.status.kind===`ready`&&e.status.pendingLocalBackup}function v(e){if(e.kind===`error`)return e.message;if(e.kind!==`loaded`)return null;switch(e.status.kind){case`unauthorized`:case`transport_failed`:return e.status.message;case`ready`:case`no_recovery_set`:return null;default:return d(e.status)}}function y(e){switch(e.kind){case`loading`:return`Loading`;case`error`:return`Could not load`;case`loaded`:return g(e.status);default:return d(e)}}function b(e){switch(e.kind){case`loading`:return`Checking your codes…`;case`error`:return`Status unavailable`;case`loaded`:return e.status.kind===`ready`?`${e.status.activeCodeCount} of ${e.status.totalCodeCount} codes left`:`Status unavailable`;default:return d(e)}}function x(e){return e.trim().replace(/[^A-Za-z0-9_.-]/g,`_`)||`wallet`}function S(e,t){let n=[`Seams wallet recovery codes`,``,`Wallet: ${e}`,``,`Save these codes somewhere private. Each code can be used once.`,``];for(let[e,r]of t.entries())n.push(`${String(e+1).padStart(2,`0`)} ${r}`);return`${n.join(`
|
|
2
2
|
`)}\n`}function C(e,t){return t?`Finish backup`:e.continuation===`registration_may_defer`?`Back up later`:`Close`}function w(e,t){return a(`li`,{class:`recovery-code-item`,children:[a(`span`,{class:`recovery-code-index`,children:t+1}),a(`span`,{class:`recovery-code-value`,children:e})]},`${t}-${e}`)}var T=class extends r{static contextType=e;state=m(this.props.experience);root=l();active=!1;loadGeneration=0;copiedResetTimer=null;focusFrame=null;componentDidMount(){this.active=!0,this.loadGeneration+=1,this.notifyStage(),this.beginAccountStatus(this.props.experience,this.loadGeneration)}componentWillReceiveProps(e){e.experience!==this.props.experience&&(this.loadGeneration+=1,this.clearFocusFrame(),this.clearCopiedFlash(),this.setState(m(e.experience)),this.beginAccountStatus(e.experience,this.loadGeneration))}componentDidUpdate(e,t){h(t.viewState)!==h(this.state.viewState)&&this.notifyStage(),t.viewState.kind!==`recovery_codes`&&this.state.viewState.kind===`recovery_codes`&&this.focusTitleAfterRender()}componentWillUnmount(){this.active=!1,this.loadGeneration+=1,this.clearFocusFrame(),this.clearCopiedFlash()}render(){let e=this.state.viewState,t=h(e),n=e.kind===`recovery_codes`?this.renderRecoveryCodes(e.request):this.renderSummary(e);return a(`div`,{ref:this.root,class:`seams-recovery-code-backup-viewer`,"data-seams-recovery-entry":this.props.experience.kind,"data-seams-recovery-stage":t,children:n})}notifyStage(){this.props.onStageChange(h(this.state.viewState))}beginAccountStatus(e,t){e.kind===`account_menu`&&this.loadSummaryStatus(e,t)}async loadSummaryStatus(e,t){try{let n=await e.loadStatus();this.updateSummaryLoadState(t,{kind:`loaded`,status:n})}catch(e){this.updateSummaryLoadState(t,{kind:`error`,message:f(e,`Could not load recovery-code status`)})}}updateSummaryLoadState(e,t){if(!this.active||e!==this.loadGeneration)return;let n=this.state.viewState;n.kind!==`summary`&&n.kind!==`opening`||this.setState({viewState:{...n,loadState:t}})}retryStatus=()=>{let e=this.props.experience;if(e.kind!==`account_menu`)return;let t=this.state.viewState;if(t.kind!==`summary`)return;let n=++this.loadGeneration;this.setState({viewState:{...t,loadState:{kind:`loading`},actionError:null}}),this.loadSummaryStatus(e,n)};openRecoveryCodes=async()=>{let e=this.props.experience,t=this.state.viewState;if(e.kind!==`account_menu`||t.kind!==`summary`)return;if(t.loadState.kind!==`loaded`||t.loadState.status.kind!==`ready`){this.setState({viewState:{...t,actionError:`Verify recovery-code status before opening saved codes.`}});return}let n=t.loadState.status.issuedAtMs,r=this.loadGeneration;this.setState({viewState:{...t,kind:`opening`,actionError:null}});try{let i=await e.loadPendingBackup();if(!this.active||r!==this.loadGeneration)return;if(!i){this.setState({viewState:{...t,actionError:`Recovery codes are no longer available on this device.`}});return}if(i.continuation!==`pending_backup_must_finish`||i.issuedAtMs!==n){this.setState({viewState:{...t,actionError:`These saved codes belong to a different recovery set. Check status again.`}});return}this.setState({viewState:{kind:`recovery_codes`,request:i}})}catch(e){if(!this.active||r!==this.loadGeneration)return;this.setState({viewState:{...t,actionError:f(e,`Could not open recovery codes`)}})}};closeSummary=()=>{this.props.onClose({kind:`dismissed`})};closeRecoveryCodes=()=>{let e=this.state.viewState;e.kind===`recovery_codes`&&this.props.onClose({kind:`recovery_codes`,acknowledged:this.state.acknowledged,request:e.request})};onAcknowledgementChange=e=>{e.currentTarget instanceof HTMLInputElement&&this.setState({acknowledged:e.currentTarget.checked})};download=()=>{let e=this.state.viewState;if(e.kind!==`recovery_codes`)return;let t=this.root.current?.ownerDocument.defaultView;if(!t)return;let{walletId:n,recoveryCodes:r}=e.request;try{let e=t.URL.createObjectURL(new t.Blob([S(n,r)],{type:`text/plain;charset=utf-8`})),i=t.document.createElement(`a`);i.href=e,i.download=`seams-wallet-recovery-codes-${x(n)}.txt`;try{i.click()}finally{t.setTimeout(()=>t.URL.revokeObjectURL(e),0)}this.setState({statusMessage:`Recovery codes downloaded.`})}catch{this.setState({statusMessage:`Unable to download the codes. Copy them or try again.`})}};copy=async()=>{let e=this.state.viewState;if(e.kind!==`recovery_codes`||!this.active)return;let{walletId:t,recoveryCodes:n}=e.request,r=this.loadGeneration;try{if(await navigator.clipboard.writeText(S(t,n)),!this.active||r!==this.loadGeneration)return;this.setState({statusMessage:`Recovery codes copied.`}),this.flashCopied()}catch{if(!this.active||r!==this.loadGeneration)return;this.setState({statusMessage:`Unable to copy the codes. Download them or try again.`})}};flashCopied(){let e=this.root.current?.ownerDocument.defaultView;e&&(this.copiedResetTimer!==null&&e.clearTimeout(this.copiedResetTimer),this.setState({copied:!0}),this.copiedResetTimer=e.setTimeout(()=>{this.copiedResetTimer=null,this.active&&this.setState({copied:!1})},1800))}clearCopiedFlash(){let e=this.root.current?.ownerDocument.defaultView;e&&this.copiedResetTimer!==null&&e.clearTimeout(this.copiedResetTimer),this.copiedResetTimer=null}clearFocusFrame(){let e=this.root.current?.ownerDocument.defaultView;e&&this.focusFrame!==null&&e.cancelAnimationFrame(this.focusFrame),this.focusFrame=null}focusTitleAfterRender(){let e=this.root.current?.ownerDocument.defaultView;e&&(this.clearFocusFrame(),this.focusFrame=e.requestAnimationFrame(()=>{this.focusFrame=null,this.active&&this.root.current?.querySelector(`.recovery-backup-title`)?.focus()}))}renderSummary(e){let t=v(e.loadState),r=_(e.loadState),o=e.kind===`opening`;return a(i,{children:[a(`button`,{type:`button`,class:`recovery-summary-close`,"aria-label":n(this.context,`Close recovery codes`),onClick:this.closeSummary,children:a(`svg`,{"aria-hidden":`true`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,children:a(`path`,{d:`M6 6l12 12M18 6 6 18`})})}),a(`h1`,{id:`seams-wallet-recovery-title`,class:`recovery-backup-title`,tabIndex:-1,children:a(c,{message:`Wallet recovery codes`})}),a(`p`,{id:`seams-wallet-recovery-description`,class:`recovery-backup-description`,children:a(c,{message:`View and save the recovery codes retained by this wallet after registration.`})}),a(`div`,{class:`recovery-summary-body`,children:[a(`h2`,{class:`recovery-summary-section-label`,children:a(c,{message:`Security`})}),a(`div`,{class:`recovery-summary-item`,children:[a(`span`,{class:`recovery-summary-item-icon`,"aria-hidden":`true`,children:a(E,{})}),a(`span`,{class:`recovery-summary-item-text`,children:[a(`span`,{class:`recovery-summary-item-title`,children:a(c,{message:`Recovery codes`})}),a(`span`,{class:`recovery-summary-item-detail`,children:a(c,{copy:b(e.loadState)})})]}),a(`span`,{class:`recovery-summary-badge`,children:a(c,{copy:y(e.loadState)})})]}),a(`div`,{class:`recovery-summary-item`,children:[a(`span`,{class:`recovery-summary-item-icon`,"aria-hidden":`true`,children:a(D,{})}),a(`span`,{class:`recovery-summary-item-text`,children:[a(`span`,{class:`recovery-summary-item-title`,children:a(c,{message:`Wallet`})}),a(`span`,{class:`recovery-summary-item-detail`,children:e.walletId})]})]}),r&&a(`button`,{type:`button`,class:`recovery-backup-button secondary recovery-summary-open`,disabled:o,onClick:this.openRecoveryCodes,children:o?a(i,{children:[a(c,{message:`Opening recovery codes`}),a(`span`,{class:`recovery-summary-ellipsis`,"aria-hidden":`true`,children:[a(`span`,{children:`.`}),a(`span`,{children:`.`}),a(`span`,{children:`.`})]})]}):a(c,{message:`View recovery codes`})}),a(`p`,{class:`recovery-summary-live-status`,role:`status`,"aria-live":`polite`,children:e.loadState.kind===`loading`?a(c,{message:`Loading recovery-code status…`}):``}),t&&a(`p`,{class:`recovery-summary-error`,role:`alert`,children:a(c,{copy:t})}),e.actionError&&a(`p`,{class:`recovery-summary-error`,role:`alert`,children:a(c,{copy:e.actionError})}),e.loadState.kind===`error`&&a(`button`,{type:`button`,class:`recovery-backup-button secondary`,onClick:this.retryStatus,children:a(c,{message:`Retry status`})})]})]})}renderRecoveryCodes(e){let t=e.continuation===`registration_may_defer`?`Each code can recover your wallet once. Save them now, or back them up later from Recovery Codes.`:`Each code can recover your wallet once. Keep them somewhere private.`;return a(i,{children:[a(`h1`,{id:`seams-wallet-recovery-title`,class:`recovery-backup-title`,tabIndex:-1,children:a(c,{message:`Save your recovery codes`})}),a(`p`,{id:`seams-wallet-recovery-description`,class:`recovery-backup-description`,children:a(c,{copy:t})}),a(`div`,{class:`recovery-code-sheet`,children:[a(`div`,{class:`recovery-code-sheet-heading`,children:[a(`span`,{children:a(c,{message:`Recovery codes`})}),a(`span`,{children:a(c,{message:`{value0} single-use codes`,values:{value0:e.recoveryCodes.length}})})]}),a(`ol`,{class:`recovery-code-list`,children:e.recoveryCodes.map(w)})]}),a(`div`,{class:`recovery-backup-actions`,children:[a(`button`,{type:`button`,class:`recovery-backup-button primary`,onClick:this.download,children:a(c,{message:`Download codes`})}),a(`button`,{type:`button`,class:`recovery-backup-button secondary recovery-backup-copy${this.state.copied?` copied`:``}`,onClick:this.copy,children:[a(O,{}),a(c,{message:`Copy codes`})]})]}),a(`div`,{class:`recovery-backup-footer`,children:[a(`label`,{class:`recovery-backup-acknowledgement`,children:[a(`input`,{type:`checkbox`,"data-seams-wallet-recovery-backup-acknowledgement":!0,checked:this.state.acknowledged,onChange:this.onAcknowledgementChange}),a(`span`,{children:[a(c,{message:`I saved these recovery codes somewhere safe.`}),a(`small`,{children:a(c,{message:`They won’t be shown again after you finish.`})})]})]}),a(`button`,{type:`button`,class:`recovery-backup-button ${this.state.acknowledged?`primary`:`secondary`}`,"data-seams-wallet-recovery-backup-close":!0,onClick:this.closeRecoveryCodes,children:a(c,{copy:C(e,this.state.acknowledged)})})]}),a(`p`,{class:`recovery-backup-status`,role:`status`,children:a(c,{copy:this.state.statusMessage})})]})}};function E(){return a(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,children:[a(`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`}),a(`path`,{d:`m9 12 2 2 4-4`})]})}function D(){return a(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,children:[a(`path`,{d:`M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1`}),a(`path`,{d:`M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4`})]})}function O(){return a(`span`,{class:`copy-icon`,"aria-hidden":`true`,children:[a(`span`,{class:`copy-icon-check`,children:a(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,children:a(`path`,{d:`M20 6 9 17l-5-5`})})}),a(`span`,{class:`copy-icon-copy`,children:a(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,children:[a(`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`}),a(`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`})]})})]})}let k=0;var A=class{element;dialog;document;input;state=`mounted`;constructor(e){this.input=e,this.document=e.parent.ownerDocument,this.element=this.document.createElement(`div`),this.element.id=`seams-recovery-surface-${++k}`,this.element.className=`seams-wallet-ui seams-recovery-code-backup-host`,this.element.lang=e.appearance?.locale??`en`,this.element.dataset.seamsRecoverySurface=e.surface,e.appearance&&(this.element.dataset.theme=e.appearance.theme.mode,s(this.document).setDynamicRule(this.element.id,u(this.element.id,e.appearance))),this.dialog=this.document.createElement(`dialog`),this.dialog.className=`seams-host-themed-dialog`,this.dialog.tabIndex=-1,this.dialog.setAttribute(`data-seams-wallet-recovery-backup-dialog`,``),this.dialog.dataset.seamsRecoverySurface=e.surface,this.dialog.setAttribute(`aria-labelledby`,`seams-wallet-recovery-title`),this.dialog.setAttribute(`aria-describedby`,`seams-wallet-recovery-description`),this.dialog.addEventListener(`cancel`,this.handleCancel),this.element.appendChild(this.dialog),e.parent.appendChild(this.element);try{this.render(e.experience),this.dialog.showModal(),this.focusTitle(),e.onShown(this.dialog)}catch(e){throw this.dispose(),e}}update(e){this.state!==`disposed`&&this.render(e)}dispose(){this.state!==`disposed`&&(this.state=`disposed`,this.dialog.removeEventListener(`cancel`,this.handleCancel),o(null,this.dialog),this.dialog.open&&this.dialog.close(),s(this.document).deleteDynamicRule(this.element.id),this.element.remove())}render(e){this.state!==`disposed`&&(this.element.dataset.seamsRecoveryEntry=e.kind,o(t(this.input.appearance?.locale??`en`,a(T,{experience:e,onClose:this.input.onClose,onStageChange:this.handleStageChange})),this.dialog))}handleCancel=e=>{e.preventDefault(),this.input.onCancel()};handleStageChange=e=>{this.state!==`disposed`&&(this.dialog.dataset.seamsRecoveryStage=e)};focusTitle(){this.dialog.querySelector(`.recovery-backup-title`)?.focus()}};function j(e){return new A(e)}export{j as mountRecoveryCodeBackupSurface};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./secureRandomId-8LSc91aN.js";import{a as t,n}from"./presignatures-DGLNs29C.js";import{P as r}from"./wallet-recovery-BEui57xM.js";import{l as i}from"./helpers-BXezXx19.js";import{t as a}from"./surface-measurement-reporter-F-fVB7d3.js";function o(e){return String(i(e)||``).trim()}function s(e,t){let n=o(e);if(!n)throw Error(`${t} requires PRF.first output from the passkey credential`);return n}function c(e){return String(e?.rawId||e?.id||``).trim()}const l=`Recovery-code backup was cancelled before acknowledgement`;async function u(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let r=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(l);let i=await import(`./mountRecoveryCodeBackupSurface-
|
|
1
|
+
import{r as e}from"./secureRandomId-8LSc91aN.js";import{a as t,n}from"./presignatures-DGLNs29C.js";import{P as r}from"./wallet-recovery-BEui57xM.js";import{l as i}from"./helpers-BXezXx19.js";import{t as a}from"./surface-measurement-reporter-F-fVB7d3.js";function o(e){return String(i(e)||``).trim()}function s(e,t){let n=o(e);if(!n)throw Error(`${t} requires PRF.first output from the passkey credential`);return n}function c(e){return String(e?.rawId||e?.id||``).trim()}const l=`Recovery-code backup was cancelled before acknowledgement`;async function u(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let r=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(l);let i=await import(`./mountRecoveryCodeBackupSurface-D3QFgMGE.js`);if(n.shouldCancel?.())throw Error(l);let o=null,s=null,c=!1;return await new Promise((u,d)=>{let f=()=>{o?.disconnect(),o=null,s?.dispose(),s=null,r?.focus()},m=e=>{c||(c=!0,f(),e instanceof Error?d(e):u(e))},h=t=>{switch(t.kind){case`dismissed`:m(Error(l));return;case`recovery_codes`:if(t.acknowledged){if(e.kind===`account_menu`){if(t.request.continuation!==`pending_backup_must_finish`){m(Error(`Displayed recovery codes have no committed issuance`));return}m({kind:`account_menu_backed_up`,issuedAtMs:t.request.issuedAtMs});return}m({kind:`registration_backed_up`});return}if(e.kind===`direct_backup`&&e.request.continuation===`registration_may_defer`){m({kind:`deferred`});return}m(Error(l));return}};try{s=i.mountRecoveryCodeBackupSurface({parent:document.body,appearance:n.appearance,experience:e,surface:t.kind===`wallet_iframe`?`wallet-iframe`:`standalone`,onClose:h,onCancel:()=>m(Error(l)),onShown:e=>{c||t.kind!==`wallet_iframe`||(o=a({kind:`request_scroll_surface`,requestId:t.requestId,element:e,postMeasurement:p.bind(null,e,t.postMeasurement)}))}})}catch(e){m(e instanceof Error?e:Error(String(e)))}})}async function d(e,t={kind:`disabled`}){switch((await u({kind:`direct_backup`,request:e},t)).kind){case`registration_backed_up`:return{kind:`wallet_recovery_codes_backed_up_v1`};case`deferred`:return{kind:`wallet_recovery_code_backup_deferred_v1`};case`account_menu_backed_up`:throw Error(`Registration backup returned an account-menu issuance`)}}async function f(e,t={kind:`disabled`},n={}){let r=await u({kind:`account_menu`,...e},t,n);if(r.kind!==`account_menu_backed_up`)throw Error(`Account-menu backup did not acknowledge committed recovery codes`);return{kind:`wallet_recovery_codes_backed_up_v1`,issuedAtMs:r.issuedAtMs}}function p(e,t,n){if(n.kind!==`measured_v1`)throw Error(`Recovery codes require a request surface measurement`);t({kind:`measured_v1`,requestId:n.requestId,sequence:n.sequence,widthCssPx:e.dataset.seamsRecoveryStage===`recovery_codes`?688:480,heightCssPx:n.heightCssPx})}const m=`wallet_recovery_codes_v1`,h=[`record_version`,`wallet_id`,`enrollment_id`,`recovery_codes_issued_at_ms`,`status`,`key`,`iv`,`ciphertext`],g=[`record_version`,`wallet_id`,`enrollment_id`,`aad_issued_at_ms`,`pending_backup_id`,`status`,`key`,`iv`,`ciphertext`],_=[...g,`recovery_codes_issued_at_ms`];function v(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&!e.extractable&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function y(e,t){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}function b(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=new Map(Object.entries(e)),r=n.get(`record_version`)===1&&n.get(`status`)===`pending`&&y(n,h),i=n.get(`record_version`)===2&&n.get(`status`)===`awaiting_commit`&&y(n,g),a=n.get(`record_version`)===2&&n.get(`status`)===`ready`&&y(n,_);if(!r&&!i&&!a)return null;let o=n.get(r?`recovery_codes_issued_at_ms`:`aad_issued_at_ms`),s=r?Number(o):o,c=n.get(`key`),l=n.get(`iv`),u=n.get(`ciphertext`);if(n.get(`wallet_id`)!==t||n.get(`enrollment_id`)!==m||typeof s!=`number`||!Number.isSafeInteger(s)||s<=0||!v(c)||!(l instanceof Uint8Array)||l.byteLength!==12||!(u instanceof Uint8Array)||u.byteLength===0)return null;if(r)return{kind:`legacy_unbound`,aadIssuedAtMs:s,key:c,iv:l,ciphertext:u};let d=n.get(`pending_backup_id`);if(typeof d!=`string`||!d.trim())return null;if(a){let e=n.get(`recovery_codes_issued_at_ms`);return!Number.isSafeInteger(e)||typeof e!=`number`||e<=0?null:{kind:`ready`,aadIssuedAtMs:s,pendingBackupId:d,issuedAtMs:e,key:c,iv:l,ciphertext:u}}return{kind:`awaiting_commit`,aadIssuedAtMs:s,pendingBackupId:d,key:c,iv:l,ciphertext:u}}function x(e,t){return new TextEncoder().encode(JSON.stringify({kind:m,walletId:e,issuedAtMs:t}))}function S(e){return[e,m]}async function C(e,n){await n.store(t.pendingWalletRecoveryCodeBackups).put(e)}async function w(e,n,r){let i=r.store(t.pendingWalletRecoveryCodeBackups),a=b(await i.get(S(e.walletId)),e.walletId);if(a?.kind!==`awaiting_commit`||a.pendingBackupId!==e.pendingBackupId)throw Error(`Pending recovery-code backup reference does not match an unbound backup`);let o={record_version:2,wallet_id:e.walletId,enrollment_id:m,aad_issued_at_ms:a.aadIssuedAtMs,pending_backup_id:a.pendingBackupId,recovery_codes_issued_at_ms:n,status:`ready`,key:a.key,iv:a.iv,ciphertext:a.ciphertext};await i.put(o)}async function T(e,n,r){let i=r.store(t.pendingWalletRecoveryCodeBackups),a=b(await i.get(S(e)),e);a?.kind===`ready`&&a.issuedAtMs===n&&await i.delete(S(e))}const E=new class{async write(i){let a=i.walletId.trim();if(!a)throw Error(`Pending recovery-code backup requires a wallet`);let o=r(i.recoveryCodes.map(String)),s=e(`pending-recovery-backup`,32,`pending recovery-code backup references`),c=Date.now();if(!Number.isSafeInteger(c)||c<=0)throw Error(`Pending recovery-code backup encryption time is invalid`);let l=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),u=crypto.getRandomValues(new Uint8Array(12)),d=x(a,c),f=new TextEncoder().encode(JSON.stringify(o)),p=null;try{let e=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:u,additionalData:d},l,f));p=e;let r={record_version:2,wallet_id:a,enrollment_id:m,aad_issued_at_ms:c,pending_backup_id:s,status:`awaiting_commit`,key:l,iv:u,ciphertext:e};return await n.runTransaction([t.pendingWalletRecoveryCodeBackups],`readwrite`,C.bind(null,r)),{walletId:a,pendingBackupId:s}}finally{d.fill(0),f.fill(0),p?.fill(0)}}async read(e){let i=e.trim();if(!i)return null;let a=b(await(await n.getDB()).get(t.pendingWalletRecoveryCodeBackups,S(i)),i);if(!a)return null;let o=x(i,a.aadIssuedAtMs),s=null;try{s=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.iv.slice(),additionalData:o},a.key,a.ciphertext.slice()));let e=JSON.parse(new TextDecoder().decode(s));if(!Array.isArray(e))throw Error(`Pending recovery-code backup is invalid`);let t=r(e.map(String));return a.kind===`ready`?{kind:`ready`,walletId:i,recoveryCodes:t,issuedAtMs:a.issuedAtMs}:{kind:`awaiting_commit`,walletId:i,recoveryCodes:t}}finally{o.fill(0),s?.fill(0)}}async has(e){let r=e.trim();return r?b(await(await n.getDB()).get(t.pendingWalletRecoveryCodeBackups,S(r)),r)!==null:!1}async bindIssuedAtMs(e,r){if(!e.walletId||e.walletId!==e.walletId.trim()||!e.pendingBackupId||e.pendingBackupId!==e.pendingBackupId.trim()||!Number.isSafeInteger(r)||r<=0)throw Error(`Pending recovery-code backup identity is invalid`);await n.runTransaction([t.pendingWalletRecoveryCodeBackups],`readwrite`,w.bind(null,e,r))}async deleteIssuedAtMs(e,r){let i=e.trim();if(!i||!Number.isSafeInteger(r)||r<=0)throw Error(`Pending recovery-code backup identity is invalid`);await n.runTransaction([t.pendingWalletRecoveryCodeBackups],`readwrite`,T.bind(null,i,r))}};export{o as a,c as i,d as n,s as o,f as r,E as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-dVx5-UGu.js";import{o as t}from"./errors-CI1xdN0d.js";import{c as n,r}from"./helpers-BXezXx19.js";import{t as i}from"./webauthnPromptCoordinator-CBkTiMP0.js";import{a}from"./intentDigest--FZ63NBy.js";import{T as o,b as s,f as c,n as l,t as u,u as d,y as f}from"./adapters-
|
|
1
|
+
import{n as e}from"./chunk-dVx5-UGu.js";import{o as t}from"./errors-CI1xdN0d.js";import{c as n,r}from"./helpers-BXezXx19.js";import{t as i}from"./webauthnPromptCoordinator-CBkTiMP0.js";import{a}from"./intentDigest--FZ63NBy.js";import{T as o,b as s,f as c,n as l,t as u,u as d,y as f}from"./adapters-CgJpSAxH.js";var p=e({handleRegistrationFlow:()=>_});function m(e){return Math.max(0,Math.round(performance.now()-e))}function h(e){return{kind:`passkey_registration_confirm_display_v1`,intendedUserName:e.walletId,accountId:e.walletId,rpId:e.rpId,signerSlot:e.signerSlot}}function g(e){let t={walletId:e.walletId,intendedUserName:e.walletId,prompt:e.prompt};return e.recoveryRegistration?{...t,kind:`wallet_recovery`,recoveryRegistration:e.recoveryRegistration}:e.addAuthMethodRegistration?{...t,kind:`wallet_add_auth_method`,registration:e.addAuthMethodRegistration}:{...t,kind:`wallet_registration`,challengeB64u:e.challengeB64u,signerSlot:e.signerSlot}}async function _(e,p,_,v){let{confirmationConfig:y,transactionSummary:b,theme:x,surface:S}=v,C=performance.now(),w=0,T=0,E=0,D=0,O=0,k=0,A=0,j=0,M=0,N=0,P=0,F=0,I=null,L=()=>({kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:0,workerRequestRoundTripMs:0,workerResponseValidationMs:0,requestSetupMs:w,promptUserMs:T,promptElementDefineMs:E,promptMountMs:D,promptHostFirstUpdateMs:O,promptHostInteractiveMs:k,promptConfirmEventMs:A,promptDecisionWaitMs:j,credentialCreateStartMs:M,credentialCreateMs:N,credentialSerializeMs:P,duplicateRetryCount:F,mainThreadTotalMs:m(C)}),R=l(e),z=u({adapters:R,worker:_,request:p,confirmationConfig:y,transactionSummary:b,theme:x,surface:S}),B=o(p),V=s(p);try{let e=performance.now(),o=p.payload.walletRecoveryRegistration,s=p.payload.walletAddAuthMethodRegistration,c=p.payload.webauthnChallenge,l=o?o.challengeB64u:s?s.challengeB64u:c?.kind===`intent_digest`?String(c.challengeB64u||``).trim():``,u=async()=>{if(l)return l;let e=f(p);if(!e)throw Error(`Missing intentDigest for registration flow`);return a(e)},d=o?.rpId??s?.rpId??R.security.getRpId();if(!d)throw Error(`Missing rpId for registration challenge`);let _=p.payload?.signerSlot??1,v=await u(),y={rpId:d,passkeyRegistration:h({walletId:B,nearAccountId:V,rpId:d,signerSlot:_})};w=m(e);let b={kind:`registration_modal`,requestId:p.requestId};I=await i.reserveRegistrationPrompt({owner:b,expiresAtMs:Date.now()+300*1e3,cancellation:{kind:`none`}});let x=performance.now(),{confirmed:S,error:H,diagnostics:U}=await z.promptUser({securityContext:y});if(T=m(x),E=U.elementDefineMs,D=U.mountMs,O=U.hostFirstUpdateMs,k=U.hostInteractiveMs,A=U.confirmEventMs,j=U.decisionWaitMs,!S)return z.confirmAndCloseModal({requestId:p.requestId,intentDigest:f(p),confirmed:!1,registrationDiagnostics:L(),error:H});let W,G=p.payload?.signerSlot??1;M=m(C);let K=performance.now();try{try{let e={kind:`reserved`,reservation:I,owner:b,cancellation:{kind:`none`}};W=await R.webauthn.createRegistrationCredential(g(o?{walletId:B,recoveryRegistration:o,prompt:e}:s?{walletId:B,addAuthMethodRegistration:s,prompt:e}:{walletId:B,challengeB64u:v,signerSlot:G,prompt:e}))}catch(e){let n=t(e),r=String(n?.name||``),i=String(n?.message||``);if(r===`InvalidStateError`||/excluded|already\s*registered/i.test(i)){if(F+=1,l)throw Error(`Registration credential already exists for this wallet registration intent; create a fresh intent before retrying`);if(p.payload.walletRecoveryRegistration||s)throw Error(`Server-issued registration requires a fresh ceremony`);let e=G!==void 0&&Number.isFinite(G)?G+1:2;G=e,p.payload.signerSlot=e,p.intentDigest=p.type===`registerAccount`?`register:${B}:${e}`:`device2-register:${B}:${e}`,v=await u(),W=await R.webauthn.createRegistrationCredential(g({walletId:B,challengeB64u:v,signerSlot:e,prompt:{kind:`immediate`,requestId:p.requestId,cancellation:{kind:`none`}}}))}else throw console.error(`[RegistrationFlow] credentials.create failed (non-duplicate)`,{name:r,msg:i}),n}}finally{N=m(K)}let q=performance.now(),J=r(W)?W:n({credential:W,firstPrfOutput:!0,secondPrfOutput:!0});P=m(q),z.confirmAndCloseModal({requestId:p.requestId,intentDigest:f(p),confirmed:!0,credential:J,registrationDiagnostics:L()})}catch(e){let n=c(e),r=String(t(e)?.message||e||``);n&&window.parent?.postMessage({type:`WALLET_UI_CLOSED`},`*`);let i=/WebAuthn PRF output is missing from navigator\.credentials\.create\(\)/i.test(r)||/does not fully support the WebAuthn PRF extension during registration/i.test(r)||/roaming hardware authenticators .* not supported in this flow/i.test(r);return z.confirmAndCloseModal({requestId:p.requestId,intentDigest:f(p),confirmed:!1,registrationDiagnostics:L(),error:n?d.cancelled:i?r:r||d.collectCredentialsFailed})}finally{I&&i.releaseReservation(I)}}export{p as n,_ as t};
|