@seams/wallet 0.18.0 → 0.19.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/SeamsWeb/index.js +1 -1
- package/dist/esm/SeamsWeb/walletIframe/client/inboundMessages.js +1 -1
- package/dist/esm/SeamsWeb/walletIframe/client/router.js +10 -4
- package/dist/esm/SeamsWeb/walletIframe/coordinator.js +23 -1
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +33 -6
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/icons.js +37 -1
- package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/presentation.js +1 -0
- package/dist/esm/core/browser/walletIframe/events.js +6 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/appearance.js +27 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/export-private-key-reveal.js +155 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/export-viewer-host.js +209 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/ExportPrivateKeySurface.js +319 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/mountExportPrivateKeySurface.js +92 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/surface-measurement-binding.js +12 -0
- package/dist/esm/core/ui/messages.js +4 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/react/components/AccountMenuButton/AccountMenuButtonView.js +1 -1
- package/dist/esm/react/components/AccountMenuButton/ExportKeysSection.css +20 -0
- package/dist/esm/react/components/AccountMenuButton/LinkedDevicesModal.css +9 -3
- package/dist/esm/react/components/AccountMenuButton/UserAccountButton.css +1 -0
- package/dist/esm/react/components/AccountMenuButton/Web3AuthProfileButton.css +15 -0
- package/dist/esm/react/styles/styles.css +36 -0
- package/dist/esm/sdk/{ConfirmationDrawer-mu3iThxX.js → ConfirmationDrawer-DCw0m-Iv.js} +1 -1
- package/dist/{public/sdk/adapters-u7LVXthY.js → esm/sdk/adapters-BNmcyf9K.js} +1 -1
- package/dist/esm/sdk/appearance-token-vars-DxBm_cKA.js +2 -0
- package/dist/{public/sdk/export-viewer-host-ivf9LlBo.js → esm/sdk/export-viewer-host-DsdzagKK.js} +1 -1
- package/dist/esm/sdk/{exportKeypairOperation-Gw7L5Htj.js → exportKeypairOperation-BwW_E4Lt.js} +1 -1
- package/dist/esm/sdk/{host-B-2QXolt.js → host-DMR4KDy9.js} +1 -1
- package/dist/esm/sdk/{localOnly-BKpUHtHa.js → localOnly-DO191vDh.js} +1 -1
- package/dist/esm/sdk/{mountExportPrivateKeySurface-C8pUK6PQ.js → mountExportPrivateKeySurface-DQzFzhNu.js} +1 -1
- package/dist/esm/sdk/{mountRecoveryCodeBackupSurface-DUudF89t.js → mountRecoveryCodeBackupSurface-B1D0ovqx.js} +1 -1
- package/dist/esm/sdk/{pendingWalletRecoveryCodeBackup-7tBjuSe7.js → pendingWalletRecoveryCodeBackup-DOeIn_Qj.js} +1 -1
- package/dist/esm/sdk/{registration-CWpOVwhj.js → registration-DknFwoqn.js} +1 -1
- package/dist/esm/sdk/{registration-D2OEgY7O.js → registration-sQndIWRF.js} +1 -1
- package/dist/esm/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/esm/sdk/runtime-auth-BxG-J-BB.js +1 -0
- package/dist/esm/sdk/{runtime-device-link-vhRhB-wS.js → runtime-device-link-Dn_5hPCq.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-BXWgFVBa.js → esm/sdk/runtime-ecdsa-tempo-lTFTb9Rh.js} +1 -1
- package/dist/esm/sdk/{runtime-email-otp-BlAaSKtk.js → runtime-email-otp-CPqTCH8Q.js} +1 -1
- package/dist/esm/sdk/{runtime-export-B4FuHhcH.js → runtime-export-Brz53_oi.js} +1 -1
- package/dist/esm/sdk/{runtime-near-BnWOpEpA.js → runtime-near-Da_xFUXx.js} +1 -1
- package/dist/esm/sdk/{runtime-preferences-COm-LTiu.js → runtime-preferences-riUZGaTs.js} +1 -1
- package/dist/esm/sdk/{runtime-recovery-BJTo5Idi.js → runtime-recovery-CTj4nDAM.js} +1 -1
- package/dist/esm/sdk/{runtime-recovery-codes-CEOjdUHV.js → runtime-recovery-codes-D8T9LQ7-.js} +1 -1
- package/dist/esm/sdk/{shared-BKPGtAps.js → shared-hx7KVyeq.js} +1 -1
- package/dist/esm/sdk/tx-confirm-ui.js +4 -0
- 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/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{ConfirmationDrawer-mu3iThxX.js → ConfirmationDrawer-DCw0m-Iv.js} +1 -1
- package/dist/{esm/sdk/adapters-u7LVXthY.js → public/sdk/adapters-BNmcyf9K.js} +1 -1
- package/dist/public/sdk/appearance-token-vars-DxBm_cKA.js +2 -0
- package/dist/{esm/sdk/export-viewer-host-ivf9LlBo.js → public/sdk/export-viewer-host-DsdzagKK.js} +1 -1
- package/dist/public/sdk/{exportKeypairOperation-Gw7L5Htj.js → exportKeypairOperation-BwW_E4Lt.js} +1 -1
- package/dist/public/sdk/{host-B-2QXolt.js → host-DMR4KDy9.js} +1 -1
- package/dist/public/sdk/{localOnly-BKpUHtHa.js → localOnly-DO191vDh.js} +1 -1
- package/dist/public/sdk/{mountExportPrivateKeySurface-C8pUK6PQ.js → mountExportPrivateKeySurface-DQzFzhNu.js} +1 -1
- package/dist/public/sdk/{mountRecoveryCodeBackupSurface-DUudF89t.js → mountRecoveryCodeBackupSurface-B1D0ovqx.js} +1 -1
- package/dist/public/sdk/{pendingWalletRecoveryCodeBackup-7tBjuSe7.js → pendingWalletRecoveryCodeBackup-DOeIn_Qj.js} +1 -1
- package/dist/public/sdk/{registration-CWpOVwhj.js → registration-DknFwoqn.js} +1 -1
- package/dist/public/sdk/{registration-D2OEgY7O.js → registration-sQndIWRF.js} +1 -1
- package/dist/public/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/sdk/runtime-auth-BxG-J-BB.js +1 -0
- package/dist/public/sdk/{runtime-device-link-vhRhB-wS.js → runtime-device-link-Dn_5hPCq.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-BXWgFVBa.js → public/sdk/runtime-ecdsa-tempo-lTFTb9Rh.js} +1 -1
- package/dist/public/sdk/{runtime-email-otp-BlAaSKtk.js → runtime-email-otp-CPqTCH8Q.js} +1 -1
- package/dist/public/sdk/{runtime-export-B4FuHhcH.js → runtime-export-Brz53_oi.js} +1 -1
- package/dist/public/sdk/{runtime-near-BnWOpEpA.js → runtime-near-Da_xFUXx.js} +1 -1
- package/dist/public/sdk/{runtime-preferences-COm-LTiu.js → runtime-preferences-riUZGaTs.js} +1 -1
- package/dist/public/sdk/{runtime-recovery-BJTo5Idi.js → runtime-recovery-CTj4nDAM.js} +1 -1
- package/dist/public/sdk/{runtime-recovery-codes-CEOjdUHV.js → runtime-recovery-codes-D8T9LQ7-.js} +1 -1
- package/dist/public/sdk/{shared-BKPGtAps.js → shared-hx7KVyeq.js} +1 -1
- package/dist/public/sdk/tx-confirm-ui.js +4 -0
- 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/public/sdk/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/public/sdk/workers/wallet_custody_ceremony_bg.wasm +0 -0
- package/dist/public/wallet-assets.manifest.json +46 -46
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/SeamsWeb/walletIframe/coordinator.d.ts +2 -1
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/domain.d.ts +20 -3
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/session.d.ts +3 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +1 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/icons.d.ts +2 -0
- package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
- package/dist/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
- package/dist/workers/wallet_custody_ceremony_bg.wasm +0 -0
- package/package.json +1 -1
- package/dist/esm/sdk/appearance-token-vars-CzBVbO39.js +0 -2
- package/dist/esm/sdk/runtime-auth-jtyQAuxZ.js +0 -1
- package/dist/public/sdk/appearance-token-vars-CzBVbO39.js +0 -2
- package/dist/public/sdk/runtime-auth-jtyQAuxZ.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-dVx5-UGu.js";import{D as t,I as n,M as r,N as i,O as a,R as o,S as s,T as c,h as l,i as u,j as d,o as f,r as p,s as m,w as h,x as g}from"./domainIds-C3fUa33Q.js";import{C as _,M as v,O as y,S as b,c as x,d as S,f as C,g as w,j as T,k as E,l as D,n as O,t as k,u as A}from"./chains-CPmd4s9f.js";import{O as j,S as M,_ as N,b as ee,c as P,k as te,v as F,w as ne,x as re,y as I}from"./primitives-CTmDwMNc.js";import{i as L,r as R}from"./base64-BmKR3UqU.js";import{r as ie}from"./secureRandomId-8LSc91aN.js";import{s as ae}from"./walletDbName-BxWApBQF.js";import{c as oe,d as se,f as ce,l as le,s as ue,u as de}from"./signingSessionSeal-DqbjG8c8.js";import{a as fe,i as pe,n as me}from"./activeWalletSession-BpbnpU9s.js";import{d as he,g as ge,h as _e,m as ve}from"./capabilityKinds-D0Yrp9uf.js";import{i as ye,n as be,r as xe}from"./canonicalPrimitives-BMP5yILS.js";import{n as Se,o as Ce,t as we}from"./errors-ADOZT8oV.js";import{c as Te,d as Ee,r as De,t as z}from"./accountIds-Cpvlkvbe.js";import{c as Oe,d as ke,i as Ae,l as je,n as Me,r as Ne,s as Pe}from"./registrationSignerPlan-BHkqlian.js";import{a as Fe,c as Ie,i as Le,o as Re,r as ze,s as Be}from"./ecdsaChainTarget-DkOrgv4y.js";import{c as Ve,d as He,h as Ue,m as We,n as Ge,s as Ke}from"./signerDomain-BFqRQ0Jl.js";import{i as qe,n as Je,r as Ye,t as Xe}from"./singletons-CAsc9LvA.js";import{L as Ze,M as Qe,d as $e,f as et,p as tt,u as nt}from"./accountLifecycle-fLNUdjct.js";import{d as rt}from"./walletAuthority-BY3kyKQ-.js";import{Et as it,H as at,Jt as ot,K as st,Nt as ct,Ot as lt,Pt as ut,Q as dt,St as ft,T as pt,Yt as mt,at as ht,en as gt,et as _t,gt as vt,ht as yt,jt as bt,kt as xt,nn as St,q as Ct,tn as wt,tt as Tt,vt as Et,w as Dt,xt as Ot,yt as kt}from"./emailOtpEcdsaDerivationIdentity-CupWCKNg.js";import{D as At,F as jt,I as Mt,J as Nt,K as Pt,P as Ft,S as It,T as Lt,U as Rt,X as zt,b as Bt,k as Vt,n as Ht,q as Ut,x as Wt}from"./challengeDelivery-CG2J5Qxs.js";import{l as Gt}from"./digestEncoding-aC4dSf_x.js";import{r as Kt}from"./walletAuthMethodRecord-CWdqdY_s.js";import{a as qt,i as Jt,r as Yt,t as Xt}from"./registrationIds-B1OpqRAt.js";import{a as Zt,c as Qt,d as $t,f as en,h as tn,l as nn,n as rn,r as an,u as on}from"./passkey-custody-Ba-NQ_4C.js";import{A as sn,B as cn,I as ln,N as un,P as dn,i as fn,j as pn}from"./ecdsaCapabilityManifest-DRc423SV.js";import{g as mn,i as B,p as hn,s as gn}from"./sdkSentEvents-DujYAPEM.js";import{C as _n,S as vn,b as yn,c as bn,g as xn,r as Sn,u as V,v as Cn,w as wn,x as Tn,y as En}from"./walletCustodyEcdsaContinuity-mGh1Ysko.js";import{t as Dn}from"./signerSlot-FJAGOhmg.js";import{c as On,o as kn,s as An}from"./wallet-recovery-DFaS3geI.js";import{n as jn}from"./authenticatorOptions-2_XK8aXv.js";import{X as Mn,j as Nn}from"./walletOwnershipGeneration-DSGfjuV2.js";import{c as Pn,r as Fn}from"./types-CQTWmtqu.js";import{o as In}from"./walletSessionAuthorizationStore-DnUMtkev.js";import{l as Ln,o as Rn,u as zn}from"./helpers-DS0bksx9.js";import{i as Bn}from"./profileAccountProjection-BNVJLOt2.js";import{A as Vn,C as Hn,E as Un,O as Wn,S as Gn,T as Kn,c as qn,d as Jn,f as Yn,h as Xn,n as Zn,p as Qn,r as $n,s as er,t as tr,x as nr,y as rr}from"./nearEd25519YaoMaterialActivation-DgWDGRI_.js";import{A as ir,a as ar,d as or,f as sr,j as cr,o as lr,u as ur}from"./nearEd25519YaoSigningPreparation-yKDLQXBS.js";import{n as dr}from"./lanes-BzU7cv2T.js";import{t as fr}from"./walletSessionAuthorizationStatus-ONPRiEbK.js";import{n as pr}from"./prfCache-BAFh1skJ.js";import{u as mr}from"./trace-CsRMlSh1.js";import{t as hr}from"./webauthnPromptCoordinator-9bVeHcTZ.js";import{t as gr}from"./intentDigest-Rh5Mg8X7.js";import{n as _r,t as vr}from"./pendingWalletRecoveryCodeBackup-7tBjuSe7.js";import{n as yr}from"./walletSessionAuthorizationProjection-DuU6w0FP.js";function br(){return Reflect.get(globalThis,`__SEAMS_REGISTRATION_BENCHMARK_DIAGNOSTICS`)===!0}function xr(){}function Sr(e){if(e.keySet!==`near_ed25519_v1`)throw Error(`The custody worker began an EVM run for a NEAR request`);return e}function Cr(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker began a NEAR run for an EVM request`);return e}function wr(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker completed a NEAR run for an EVM request`);return e}function Tr(e){switch(e.origin){case`establish`:case`establish_factor_after_round`:return{origin:`establish`,walletId:e.walletId};case`join`:return{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret};case`recover`:return{origin:`recover`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode};case`recover_and_reseal`:return{origin:`recover_and_reseal`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode,replacementFactorJson:e.replacementFactorJson,replacementFactorSecret:e.replacementFactorSecret};default:return Dr(e)}}async function Er(e){switch(e.origin){case`establish`:return{kind:`establish`,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:e.recoveryCodesJson};case`establish_factor_after_round`:{let t=await e.factor();return{kind:`establish`,factorJson:t.factorJson,factorSecret:t.factorSecret,recoveryCodesJson:e.recoveryCodesJson}}case`join`:case`recover`:return{kind:`existing`};case`recover_and_reseal`:return{kind:`recover_reseal`,replacementFactorJson:e.replacementFactorJson,replacementFactorSecret:e.replacementFactorSecret};default:return Dr(e)}}function Dr(e){throw Error(`Unsupported wallet custody origin: ${String(e)}`)}function Or(e,t){if(e.walletId!==t.activation.walletId)throw Error(`EVM custody activation changed the wallet identity`);if(e.keyManifestDigestB64u!==t.activation.keyManifestDigestB64u)throw Error(`EVM custody activation changed the key manifest digest`);if(e.clientRootPublicKey33B64u!==t.activation.clientRootPublicKey33B64u)throw Error(`EVM custody activation changed the client root public key`)}function kr(e,t,n){if(br())try{console.info(`[WalletCustody] timing `+JSON.stringify({event:`wallet_custody_timing`,ceremonyId:e,stage:`custody.${t}`,durationMs:Math.round((performance.now()-n)*10)/10,outcome:`success`}))}catch{}}async function Ar(e){let t=e.ceremonyId||ie(`wallet-custody-ceremony`,32,`wallet custody ceremony IDs`),{custody:n,keySetRun:r}=e,i=!1;try{if(r.keySet===`near_ed25519_v1`){let a=performance.now(),o;if(r.checkpointJson!==void 0){if(n.origin!==`join`)throw Error(`Checkpoint restoration requires existing custody`);o=(await e.runStep(`restoreNearRegistration`,{ceremonyId:t,custodyJson:n.custodyJson,factorSecret:n.factorSecret,checkpointJson:r.checkpointJson})).yaoExecuteRequestJson}else o=Sr(await e.runStep(`beginWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`near_ed25519_v1`,custody:Tr(n),protocolInputsJson:r.protocolInputsJson})).yaoExecuteRequestJson;if(kr(t,`begin`,a),i=!0,r.beforeRouterRound){a=performance.now();let n=await e.runStep(`checkpointNearRegistration`,{ceremonyId:t});kr(t,`checkpoint`,a),await r.beforeRouterRound(n.checkpointJson)}a=performance.now();let s=await r.runRouterRound(o);kr(t,`router_round`,a),a=performance.now(),await e.runStep(`completeWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`near_ed25519_v1`,protocolResultJson:s,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u}),kr(t,`complete`,a),await r.afterRouterRoundCompleted?.(s),a=performance.now();let c=await e.runStep(`finishWalletCustodyKeySetRun`,{ceremonyId:t,finish:await Er(n)});return kr(t,`finish`,a),c}if(n.origin===`establish_factor_after_round`)throw Error(`An EVM custody run seals under its factor before the relayer round`);let a=await e.runStep(`beginWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`evm_family_ecdsa_v1`,custody:n,protocolInputsJson:r.protocolInputsJson,evmFamilySigningKeySlotId:r.evmFamilySigningKeySlotId,recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});i=!0;let o=Cr(a);await r.beforeRelayerRound();let s=await r.runRelayerRound({contextBinding32B64u:o.ecdsaContextBinding32B64u,clientSharePublicKey33B64u:o.ecdsaClientSharePublicKey33B64u,clientShareRetryCounter:o.ecdsaClientShareRetryCounter,preActivationCommitPayload:o.preActivationCommitPayload}),c=wr(await e.runStep(`completeWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`evm_family_ecdsa_v1`,protocolResultJson:s}));return Or(o.preActivationCommitPayload,c),{...o.preActivationCommitPayload,clientRootPublicKey33B64u:c.activation.clientRootPublicKey33B64u,ecdsaReadyStateBlobB64u:c.activation.ecdsaReadyStateBlobB64u,ecdsaPublicFacts:c.activation.ecdsaPublicFacts}}catch(n){throw i&&await e.runStep(`discardWalletCustodyCeremony`,{ceremonyId:t}).catch(xr),n}}const jr=[1,2];function Mr(e){let t=[],n=new Set;for(let r of e){let e=k(r.network);if(e!==`evm`&&e!==`tempo`)continue;let i=Le(r),a=Re(i);n.has(a)||(n.add(a),t.push({chainTarget:i}))}return t}function Nr(e){let t=[],n=new Set;for(let r of e.chains){let i=k(r.network);if(i!==`evm`&&i!==`tempo`||!(i===`tempo`?e.signerOptions.tempo:e.signerOptions.evm).enabled)continue;let a=Le(r),o=Re(a);n.has(o)||(n.add(o),t.push({chainTarget:a}))}return t}function Pr(e){for(let t of e.signers)if(t.kind===`near_ed25519`)return!0;return!1}function Fr(e){let t=e.ecdsaChainTargets??Lr(e.configs,e.options);return Rr(e.accountProvisioning??Ae(),t)}function Ir(e){let t=null;for(let n of e.configs.network.chains)if(O(n.network)){t=Vr(e);break}return Rr(t,Lr(e.configs,e.options))}function Lr(e,t){let n=Nr({signerOptions:t.signerOptions??e.signing.thresholdEcdsa.provisioningDefaults,chains:e.network.chains}),r=[];for(let e of n)r.push(e.chainTarget);return r}function Rr(e,t){let n=[];if(e&&n.push({kind:`near_ed25519`,accountProvisioning:e,signerSlot:1,participantIds:[...M],derivationVersion:1}),t.length&&n.push({kind:`evm_family_ecdsa`,chainTargets:[...t],participantIds:[...jr]}),!n.length)throw Error(`Wallet registration requires at least one configured, enabled signer`);return{kind:`signer_set`,signers:n}}function zr(e){let t=Te(e);if(!t.ok)throw Error(t.message);return ke(t.value)}function Br(e){let t=String(e.walletId||``).trim(),n=String(e.relayerAccountId||``).trim();if(!t)throw Error(`Relayer named NEAR registration requires walletId`);if(!n)throw Error(`Relayer named NEAR registration requires relayer accountId`);return zr(`${t}.${n}`)}function Vr(e){let t=e.preference??e.configs.registration.nearAccountProvisioning;switch(t.kind){case`implicit_account`:return Ae();case`relayer_named_subaccount`:if(e.wallet.kind!==`provided`)throw Error(`Relayer named NEAR registration requires a provided walletId`);return Br({walletId:e.wallet.walletId,relayerAccountId:e.configs.network.relayer.accountId});default:return t}}function Hr(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function Ur(e,t){let n=s(e);if(!n.ok)throw Error(`${t} is invalid`);return n.value}function Wr(e,t){if(!Array.isArray(e)||e.length!==32)throw Error(`${t} must contain exactly 32 bytes`);let n=[];for(let r of e){if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw Error(`${t} must contain exactly 32 bytes`);n.push(r)}return Object.freeze(n)}function Gr(e,t){if(!Array.isArray(e)||e.length===0)throw Error(`${t} must contain bytes`);return e.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`${t} must contain bytes`);return e})}function Kr(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||e[0]<1||e[1]<1||e[0]===e[1])throw Error(`participantIds must contain two distinct positive integers`);return[Number(e[0]),Number(e[1])]}function qr(e){let t=E(e,`capability.registrationContinuity`);if(t.kind===`recovery`)return{kind:`recovery`,activationTranscript:Gr(t.activationTranscript,`capability.registrationContinuity.activationTranscript`)};if(t.kind!==`registration`)throw Error(`capability.registrationContinuity kind is invalid`);let n=Pt(t.admissionRequest),r=Rt(t.admissionReceipt);if(!n.ok)throw Error(`capability registration continuity transcript is invalid: ${n.message}`);if(!r.ok)throw Error(`capability registration continuity transcript is invalid: ${r.message}`);return{kind:`registration`,admissionRequest:n.value,admissionReceipt:r.value,activationTranscript:Gr(t.activationTranscript,`capability.registrationContinuity.activationTranscript`)}}function Jr(e){let t=E(e,`capability`);if(t.kind!==`router_ab_ed25519_yao_active_capability_v1`)throw Error(`Yao recovery capability kind is invalid`);let n=E(t.applicationBinding,`capability.applicationBinding`),r=E(t.lifecycle,`capability.lifecycle`),i;try{i=gt(t.materialActivation)}catch(e){throw Error(`capability.materialActivation is invalid: ${e instanceof Error?e.message:String(e)}`)}return{materialActivation:i,activeCapabilityBinding:Wr(t.activeCapabilityBinding,`capability.activeCapabilityBinding`),registeredPublicKey:Wr(t.registeredPublicKey,`capability.registeredPublicKey`),nearAccountId:z(T(t.nearAccountId,`capability.nearAccountId`)),applicationBinding:{wallet_id:T(n.wallet_id,`applicationBinding.wallet_id`),near_ed25519_signing_key_id:T(n.near_ed25519_signing_key_id,`applicationBinding.near_ed25519_signing_key_id`),signing_root_id:T(n.signing_root_id,`applicationBinding.signing_root_id`),key_creation_signer_slot:Hr(n.key_creation_signer_slot,`applicationBinding.key_creation_signer_slot`)},participantIds:Kr(t.participantIds),runtimePolicyScope:I(E(t.runtimePolicyScope,`capability.runtimePolicyScope`)),lifecycle:{lifecycleId:T(r.lifecycleId,`lifecycle.lifecycleId`),rootShareEpoch:T(r.rootShareEpoch,`lifecycle.rootShareEpoch`),accountId:T(r.accountId,`lifecycle.accountId`),thresholdSessionId:Ur(T(r.thresholdSessionId,`lifecycle.thresholdSessionId`),`lifecycle.thresholdSessionId`),signerSetId:T(r.signerSetId,`lifecycle.signerSetId`),signingWorkerId:T(r.signingWorkerId,`lifecycle.signingWorkerId`)},stateEpoch:Hr(t.stateEpoch,`capability.stateEpoch`),registrationContinuity:qr(t.registrationContinuity)}}var Yr=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,oi.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,oi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmactivatedclientv1_free(e,0)}create_signing_share(e,t,n,r,i){let a=H(n,K.__wbindgen_malloc),o=G,s=U(r,K.__wbindgen_malloc,K.__wbindgen_realloc),c=G,l=H(i,K.__wbindgen_malloc),u=G,d=K.wasmactivatedclientv1_create_signing_share(this.__wbg_ptr,e,t,a,o,s,c,l,u);if(d[2])throw W(d[1]);return Xr.__wrap(d[0])}static import_linked_material(t,n,r,i){let a=H(t,K.__wbindgen_malloc),o=G,s=U(i,K.__wbindgen_malloc,K.__wbindgen_realloc),c=G,l=K.wasmactivatedclientv1_import_linked_material(a,o,n,r,s,c);if(l[2])throw W(l[1]);return e.__wrap(l[0])}static import_local_material(t,n,r,i,a,o,s,c,l){let u=H(t,K.__wbindgen_malloc),d=G,f=H(n,K.__wbindgen_malloc),p=G,m=H(r,K.__wbindgen_malloc),h=G,g=H(i,K.__wbindgen_malloc),_=G,v=H(a,K.__wbindgen_malloc),y=G,b=H(l,K.__wbindgen_malloc),x=G,S=K.wasmactivatedclientv1_import_local_material(u,d,f,p,m,h,g,_,v,y,o,s,c,b,x);if(S[2])throw W(S[1]);return e.__wrap(S[0])}registered_public_key(){let e=K.wasmactivatedclientv1_registered_public_key(this.__wbg_ptr);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}seal_local_material(e,t,n){let r=H(e,K.__wbindgen_malloc),i=G,a=H(t,K.__wbindgen_malloc),o=G,s=H(n,K.__wbindgen_malloc),c=G,l=K.wasmactivatedclientv1_seal_local_material(this.__wbg_ptr,r,i,a,o,s,c);if(l[3])throw W(l[2]);var u=vi(l[0],l[1]).slice();return K.__wbindgen_free(l[0],l[1]*1,1),u}state_epoch(){let e=K.wasmactivatedclientv1_state_epoch(this.__wbg_ptr);return BigInt.asUintN(64,e)}};Symbol.dispose&&(Yr.prototype[Symbol.dispose]=Yr.prototype.free);var Xr=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,si.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,si.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmclientsigningsharev1_free(e,0)}client_commitments_json(){let e,t;try{let n=K.wasmclientsigningsharev1_client_commitments_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}client_signature_share_b64u(){let e,t;try{let n=K.wasmclientsigningsharev1_client_signature_share_b64u(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}client_verifying_share(){let e=K.wasmclientsigningsharev1_client_verifying_share(this.__wbg_ptr);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}};Symbol.dispose&&(Xr.prototype[Symbol.dispose]=Xr.prototype.free);var Zr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ci.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e,0)}complete(e){let t=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),n=G,r=K.wasmed25519yaoclientrootexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw W(r[1]);return ti.__wrap(r[0])}execute_request_json(){let e,t;try{let n=K.wasmed25519yaoclientrootexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),m=G,h=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),g=G,_=H(i,K.__wbindgen_malloc),v=G,y=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),b=G,x=H(o,K.__wbindgen_malloc),S=G,C=H(s,K.__wbindgen_malloc),w=G,T=H(c,K.__wbindgen_malloc),E=G,D=H(l,K.__wbindgen_malloc),O=G,k=H(u,K.__wbindgen_malloc),A=G,j=H(d,K.__wbindgen_malloc),M=G,N=H(f,K.__wbindgen_malloc),ee=G,P=K.wasmed25519yaoclientrootexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee);if(P[2])throw W(P[1]);return this.__wbg_ptr=P[0],ci.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(Zr.prototype[Symbol.dispose]=Zr.prototype.free);var Qr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,li.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaolaneclientv1_free(e,0)}complete(e){let t=K.wasmed25519yaolaneclientv1_complete(this.__wbg_ptr,e);if(t[2])throw W(t[1]);return W(t[0])}execute_request_json(){let e,t;try{let i=K.wasmed25519yaolaneclientv1_execute_request_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}constructor(){return this.__wbg_ptr=K.wasmed25519yaolaneclientv1_new(),li.register(this,this.__wbg_ptr,this),this}prepare(e,t,n,r,i,a,o,s,c,l){gi(a,$r);let u=H(o,K.__wbindgen_malloc),d=G,f=H(s,K.__wbindgen_malloc),p=G,m=H(c,K.__wbindgen_malloc),h=G,g=H(l,K.__wbindgen_malloc),_=G,v=K.wasmed25519yaolaneclientv1_prepare(this.__wbg_ptr,e,t,n,r,i,a.__wbg_ptr,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return W(v[0])}};Symbol.dispose&&(Qr.prototype[Symbol.dispose]=Qr.prototype.free);var $r=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,ui.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ui.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaolanesourcev1_free(e,0)}constructor(e,t,n,r,i,a){let o=H(e,K.__wbindgen_malloc),s=G,c=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),l=G,u=H(n,K.__wbindgen_malloc),d=G,f=H(r,K.__wbindgen_malloc),p=G,m=H(i,K.__wbindgen_malloc),h=G,g=H(a,K.__wbindgen_malloc),_=G,v=K.wasmed25519yaolanesourcev1_new(o,s,c,l,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return this.__wbg_ptr=v[0],ui.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&($r.prototype[Symbol.dispose]=$r.prototype.free);var ei=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,di.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaosourcepreservingregistrationsessionv1_free(e,0)}constructor(e,t,n,r,i,a,o,s,c){gi(i,$r);let l=H(a,K.__wbindgen_malloc),u=G,d=H(o,K.__wbindgen_malloc),f=G,p=H(s,K.__wbindgen_malloc),m=G,h=H(c,K.__wbindgen_malloc),g=G,_=K.wasmed25519yaosourcepreservingregistrationsessionv1_new(e,t,n,r,i.__wbg_ptr,l,u,d,f,p,m,h,g);if(_[2])throw W(_[1]);return this.__wbg_ptr=_[0],di.register(this,this.__wbg_ptr,this),this}take_execute_request_json(){let e,t;try{let i=K.wasmed25519yaosourcepreservingregistrationsessionv1_take_execute_request_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(ei.prototype[Symbol.dispose]=ei.prototype.free);var ti=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,fi.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,fi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmexporteded25519seedv1_free(e,0)}take_export_artifact_json(){let e,t;try{let i=K.wasmexporteded25519seedv1_take_export_artifact_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(ti.prototype[Symbol.dispose]=ti.prototype.free);var ni=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,pi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmordinaryed25519activationclientmaterialv1_free(e,0)}destroy(){K.wasmordinaryed25519activationclientmaterialv1_destroy(this.__wbg_ptr)}constructor(e,t,n,r,i,a){let o=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),s=G,c=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),l=G,u=U(n,K.__wbindgen_malloc,K.__wbindgen_realloc),d=G,f=H(r,K.__wbindgen_malloc),p=G,m=U(i,K.__wbindgen_malloc,K.__wbindgen_realloc),h=G,g=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),_=G,v=K.wasmordinaryed25519activationclientmaterialv1_new(o,s,c,l,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return this.__wbg_ptr=v[0],pi.register(this,this.__wbg_ptr,this),this}take_client_material(){let e=K.wasmordinaryed25519activationclientmaterialv1_take_client_material(this.__wbg_ptr);if(e[3])throw W(e[2]);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}};Symbol.dispose&&(ni.prototype[Symbol.dispose]=ni.prototype.free);var ri=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,mi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmwalletcustodyseedexportsessionv1_free(e,0)}complete(e){let t=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),n=G,r=K.wasmwalletcustodyseedexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw W(r[1]);return ti.__wrap(r[0])}execute_request_json(){let e,t;try{let n=K.wasmwalletcustodyseedexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),m=G,h=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),g=G,_=H(i,K.__wbindgen_malloc),v=G,y=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),b=G,x=H(o,K.__wbindgen_malloc),S=G,C=H(s,K.__wbindgen_malloc),w=G,T=H(c,K.__wbindgen_malloc),E=G,D=H(l,K.__wbindgen_malloc),O=G,k=H(u,K.__wbindgen_malloc),A=G,j=H(d,K.__wbindgen_malloc),M=G,N=H(f,K.__wbindgen_malloc),ee=G,P=K.wasmwalletcustodyseedexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee);if(P[2])throw W(P[1]);return this.__wbg_ptr=P[0],mi.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(ri.prototype[Symbol.dispose]=ri.prototype.free);function ii(e,t,n,r,i,a,o,s,c,l,u,d,f,p){let m=H(e,K.__wbindgen_malloc),h=G,g=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),_=G,v=H(n,K.__wbindgen_malloc),y=G,b=H(r,K.__wbindgen_malloc),x=G,S=H(i,K.__wbindgen_malloc),C=G,w=H(a,K.__wbindgen_malloc),T=G,E=H(o,K.__wbindgen_malloc),D=G,O=H(s,K.__wbindgen_malloc),k=G,A=H(d,K.__wbindgen_malloc),j=G,M=H(f,K.__wbindgen_malloc),N=G,ee=H(p,K.__wbindgen_malloc),P=G,te=K.openWalletCustodyEd25519MaterialV1(m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,c,l,u,A,j,M,N,ee,P);if(te[2])throw W(te[1]);return Yr.__wrap(te[0])}function ai(){let e={__proto__:null,__wbg_Error_92b29b0548f8b746:function(e,t){return Error(xi(e,t))},__wbg_Number_9a4e0ecb0fa16705:function(e){return Number(e)},__wbg_String_8564e559799eccda:function(e,t){let n=U(String(t),K.__wbindgen_malloc,K.__wbindgen_realloc),r=G;bi().setInt32(e+4,r,!0),bi().setInt32(e+0,n,!0)},__wbg___wbindgen_bigint_get_as_i64_d968e41184ae354f:function(e,t){let n=t,r=typeof n==`bigint`?n:void 0;bi().setBigInt64(e+8,Ti(r)?BigInt(0):r,!0),bi().setInt32(e+0,!Ti(r),!0)},__wbg___wbindgen_boolean_get_fa956cfa2d1bd751:function(e){let t=e,n=typeof t==`boolean`?t:void 0;return Ti(n)?16777215:n?1:0},__wbg___wbindgen_debug_string_c25d447a39f5578f:function(e,t){let n=U(_i(t),K.__wbindgen_malloc,K.__wbindgen_realloc),r=G;bi().setInt32(e+4,r,!0),bi().setInt32(e+0,n,!0)},__wbg___wbindgen_in_aca499c5de7ff5e5:function(e,t){return e in t},__wbg___wbindgen_is_bigint_2f76dc55065b4273:function(e){return typeof e==`bigint`},__wbg___wbindgen_is_function_1ff95bcc5517c252:function(e){return typeof e==`function`},__wbg___wbindgen_is_object_a27215656b807791:function(e){let t=e;return typeof t==`object`&&!!t},__wbg___wbindgen_is_string_ea5e6cc2e4141dfe:function(e){return typeof e==`string`},__wbg___wbindgen_is_undefined_c05833b95a3cf397:function(e){return e===void 0},__wbg___wbindgen_jsval_eq_e659fcf7b0e32763:function(e,t){return e===t},__wbg___wbindgen_jsval_loose_eq_db4c3b15f63fc170:function(e,t){return e==t},__wbg___wbindgen_number_get_394265ed1e1b84ee:function(e,t){let n=t,r=typeof n==`number`?n:void 0;bi().setFloat64(e+8,Ti(r)?0:r,!0),bi().setInt32(e+0,!Ti(r),!0)},__wbg___wbindgen_string_get_b0ca35b86a603356:function(e,t){let n=t,r=typeof n==`string`?n:void 0;var i=Ti(r)?0:U(r,K.__wbindgen_malloc,K.__wbindgen_realloc),a=G;bi().setInt32(e+4,a,!0),bi().setInt32(e+0,i,!0)},__wbg___wbindgen_throw_344f42d3211c4765:function(e,t){throw Error(xi(e,t))},__wbg_call_8a2dd23819f8a60a:function(){return wi(function(e,t){return e.call(t)},arguments)},__wbg_call_a6e5c5dce5018821:function(){return wi(function(e,t,n){return e.call(t,n)},arguments)},__wbg_crypto_38df2bab126b63dc:function(e){return e.crypto},__wbg_done_89b2b13e91a60321:function(e){return e.done},__wbg_entries_015dc610cd81ede0:function(e){return Object.entries(e)},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return wi(function(e,t){e.getRandomValues(t)},arguments)},__wbg_get_507a50627bffa49b:function(e,t){return e[t>>>0]},__wbg_get_78f252d074a84d0b:function(){return wi(function(e,t){return Reflect.get(e,t)},arguments)},__wbg_get_c7eb1f358a7654df:function(){return wi(function(e,t){return Reflect.get(e,t)},arguments)},__wbg_get_unchecked_6e0ad6d2a41b06f6:function(e,t){return e[t>>>0]},__wbg_get_with_ref_key_6412cf3094599694:function(e,t){return e[t]},__wbg_instanceof_ArrayBuffer_4480b9e0068a8adb:function(e){let t;try{t=e instanceof ArrayBuffer}catch{t=!1}return t},__wbg_instanceof_Map_e5b5e3db98422fcc:function(e){let t;try{t=e instanceof Map}catch{t=!1}return t},__wbg_instanceof_Uint8Array_309b927aaf7a3fc7:function(e){let t;try{t=e instanceof Uint8Array}catch{t=!1}return t},__wbg_isArray_0677c962b281d01a:function(e){return Array.isArray(e)},__wbg_isSafeInteger_04f36e4056f1b851:function(e){return Number.isSafeInteger(e)},__wbg_iterator_6f722e4a93058b71:function(){return Symbol.iterator},__wbg_length_1f0964f4a5e2c6d8:function(e){return e.length},__wbg_length_370319915dc99107:function(e){return e.length},__wbg_msCrypto_bd5a034af96bcba6:function(e){return e.msCrypto},__wbg_new_cd45aabdf6073e84:function(e){return new Uint8Array(e)},__wbg_new_da52cf8fe3429cb2:function(){return{}},__wbg_new_with_length_e6785c33c8e4cce8:function(e){return new Uint8Array(e>>>0)},__wbg_next_6dbf2c0ac8cde20f:function(e){return e.next},__wbg_next_71f2aa1cb3d1e37e:function(){return wi(function(e){return e.next()},arguments)},__wbg_node_84ea875411254db1:function(e){return e.node},__wbg_process_44c7a14e11e9f69e:function(e){return e.process},__wbg_prototypesetcall_4770620bbe4688a0:function(e,t,n){Uint8Array.prototype.set.call(vi(e,t),n)},__wbg_randomFillSync_6c25eac9869eb53c:function(){return wi(function(e,t){e.randomFillSync(t)},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return wi(function(){return module.require},arguments)},__wbg_set_6be42768c690e380:function(e,t,n){e[t]=n},__wbg_set_8535240470bf2500:function(){return wi(function(e,t,n){return Reflect.set(e,t,n)},arguments)},__wbg_static_accessor_GLOBAL_4ef717fb391d88b7:function(){let e=typeof global>`u`?null:global;return Ti(e)?0:hi(e)},__wbg_static_accessor_GLOBAL_THIS_8d1badc68b5a74f4:function(){let e=typeof globalThis>`u`?null:globalThis;return Ti(e)?0:hi(e)},__wbg_static_accessor_SELF_146583524fe1469b:function(){let e=typeof self>`u`?null:self;return Ti(e)?0:hi(e)},__wbg_static_accessor_WINDOW_f2829a2234d7819e:function(){let e=typeof window>`u`?null:window;return Ti(e)?0:hi(e)},__wbg_subarray_3ed232c8a6baee09:function(e,t,n){return e.subarray(t>>>0,n>>>0)},__wbg_value_a5d5488a9589444a:function(e){return e.value},__wbg_versions_276b2795b1c6a219:function(e){return e.versions},__wbindgen_cast_0000000000000001:function(e){return e},__wbindgen_cast_0000000000000002:function(e){return e},__wbindgen_cast_0000000000000003:function(e,t){return vi(e,t)},__wbindgen_cast_0000000000000004:function(e,t){return xi(e,t)},__wbindgen_cast_0000000000000005:function(e){return BigInt.asUintN(64,e)},__wbindgen_init_externref_table:function(){let e=K.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}};return{__proto__:null,"./router_ab_ed25519_yao_client_bg.js":e}}const oi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmactivatedclientv1_free(e,1)),si=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmclientsigningsharev1_free(e,1)),ci=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e,1)),li=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaolaneclientv1_free(e,1)),ui=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaolanesourcev1_free(e,1)),di=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaosourcepreservingregistrationsessionv1_free(e,1)),fi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmexporteded25519seedv1_free(e,1)),pi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmordinaryed25519activationclientmaterialv1_free(e,1)),mi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmwalletcustodyseedexportsessionv1_free(e,1));function hi(e){let t=K.__externref_table_alloc();return K.__wbindgen_externrefs.set(t,e),t}function gi(e,t){if(!(e instanceof t))throw Error(`expected instance of ${t.name}`)}function _i(e){let t=typeof e;if(t==`number`||t==`boolean`||e==null)return`${e}`;if(t==`string`)return`"${e}"`;if(t==`symbol`){let t=e.description;return t==null?`Symbol`:`Symbol(${t})`}if(t==`function`){let t=e.name;return typeof t==`string`&&t.length>0?`Function(${t})`:`Function`}if(Array.isArray(e)){let t=e.length,n=`[`;t>0&&(n+=_i(e[0]));for(let r=1;r<t;r++)n+=`, `+_i(e[r]);return n+=`]`,n}let n=/\[object ([^\]]+)\]/.exec(toString.call(e)),r;if(n&&n.length>1)r=n[1];else return toString.call(e);if(r==`Object`)try{return`Object(`+JSON.stringify(e)+`)`}catch{return`Object`}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}function vi(e,t){return e>>>=0,Ci().subarray(e/1,e/1+t)}let yi=null;function bi(){return(yi===null||yi.buffer.detached===!0||yi.buffer.detached===void 0&&yi.buffer!==K.memory.buffer)&&(yi=new DataView(K.memory.buffer)),yi}function xi(e,t){return Oi(e>>>0,t)}let Si=null;function Ci(){return(Si===null||Si.byteLength===0)&&(Si=new Uint8Array(K.memory.buffer)),Si}function wi(e,t){try{return e.apply(this,t)}catch(e){let t=hi(e);K.__wbindgen_exn_store(t)}}function Ti(e){return e==null}function H(e,t){let n=t(e.length*1,1)>>>0;return Ci().set(e,n/1),G=e.length,n}function U(e,t,n){if(n===void 0){let n=ki.encode(e),r=t(n.length,1)>>>0;return Ci().subarray(r,r+n.length).set(n),G=n.length,r}let r=e.length,i=t(r,1)>>>0,a=Ci(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=Ci().subarray(i+o,i+r),a=ki.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return G=o,i}function W(e){let t=K.__wbindgen_externrefs.get(e);return K.__externref_table_dealloc(e),t}let Ei=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});Ei.decode();let Di=0;function Oi(e,t){return Di+=t,Di>=2146435072&&(Ei=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),Ei.decode(),Di=t),Ei.decode(Ci().subarray(e,e+t))}const ki=new TextEncoder;`encodeInto`in ki||(ki.encodeInto=function(e,t){let n=ki.encode(e);return t.set(n),{read:e.length,written:n.length}});let G=0,K;function Ai(e,t){return K=e.exports,yi=null,Si=null,K.__wbindgen_start(),K}async function ji(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function Mi(e){if(K!==void 0)return K;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`)),e===void 0&&(e=new URL(`router_ab_ed25519_yao_client_bg.wasm`,import.meta.url));let t=ai();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await ji(await e,t);return Ai(n,r)}const Ni=`router_ab_ed25519_yao_active_client_v1`;function Pi(e){switch(e.authorization.kind){case`passkey`:return{protocol:e.protocol,authorization:{kind:`passkey`,webauthnAuthentication:zn(e.authorization.webauthnAuthentication)}};case`email_otp_factor`:return{protocol:e.protocol,authorization:{kind:`email_otp_factor`,providerSubjectId:e.authorization.providerSubjectId,walletAuthMethodId:e.authorization.walletAuthMethodId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode}}}}const Fi=Symbol(`router-ab-ed25519-yao-active-client-construction`);function Ii(e,t){if(!(e instanceof Uint8Array)||e.length!==32)throw Error(`${t} must contain 32 bytes`);return e}function Li(e){return e.authorization.kind===`passkey`}function Ri(e){switch(e.kind){case`wallet_custody_seed_v1`:return ri;case`ed25519_yao_client_root_v1`:return Zr;default:return Gi(e.kind)}}function zi(e){let t=[JSON.stringify(e.admission),JSON.stringify(e.applicationBinding),e.participantIds[0],e.participantIds[1],e.custodyEnvelope.factorSecret,e.custodyEnvelope.bindingJson,e.custodyEnvelope.nonce,e.custodyEnvelope.ciphertext,e.custodyEnvelope.aadHash,e.custodyEnvelope.ciphertextDigest,e.entropy.recipientKeyMaterial,e.entropy.deriverASealSeed,e.entropy.deriverBSealSeed];return new(Ri(e.custodyEnvelope))(...t)}function Bi(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Object.keys(e);if(t.length!==4||![`kind`,`challengeId`,`loginGrant`,`expiresAtMs`].every(e=>t.includes(e))||Reflect.get(e,`kind`)!==`email_otp_login_grant`)return null;let n=Reflect.get(e,`challengeId`),r=Reflect.get(e,`loginGrant`),i=Reflect.get(e,`expiresAtMs`);return typeof n!=`string`||n.trim().length===0||typeof r!=`string`||r.trim().length===0||typeof i!=`number`||!Number.isSafeInteger(i)||i<=0?null:{kind:`email_otp_login_grant`,challengeId:n,loginGrant:r}}function Vi(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Router export admission response must be an object`);let t=Object.keys(e),n=t.length===1&&t[0]===`protocol`,r=t.length===2&&t.includes(`protocol`)&&t.includes(`factorRelease`);if(!n&&!r)throw Error(`Router export admission response contains unexpected fields`);let i=Ft(Reflect.get(e,`protocol`));if(!i.ok)throw Error(i.message);return n?{kind:`protocol_only`,protocol:i.value}:{kind:`protocol_with_factor_release`,protocol:i.value,factorRelease:Bi(Reflect.get(e,`factorRelease`))}}function Hi(){return{recipientKeyMaterial:qi(),deriverASealSeed:qi(),deriverBSealSeed:qi()}}function Ui(e){e.recipientKeyMaterial.fill(0),e.deriverASealSeed.fill(0),e.deriverBSealSeed.fill(0)}function Wi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function Gi(e){throw Error(`Unhandled Ed25519 Yao Client lifecycle: ${String(e)}`)}function Ki(e){switch(e.kind){case`active`:return e.activated;case`disposed`:throw Error(`Ed25519 Yao Client state is disposed`);default:return Gi(e)}}function qi(){let e=new Uint8Array(32);do globalThis.crypto.getRandomValues(e);while(e.every(Ji));return e}function Ji(e){return e===0}function Yi(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Client commitments must be an object`);let n=Object.keys(t);if(n.length!==2||!n.includes(`hiding`)||!n.includes(`binding`))throw Error(`Client commitments contain unexpected fields`);let r=Reflect.get(t,`hiding`),i=Reflect.get(t,`binding`);if(typeof r!=`string`||typeof i!=`string`)throw Error(`Client commitments must contain hiding and binding strings`);return{hiding:r,binding:i}}function Xi(e,t){let n=t.binding.ceremony.lifecycle;return n.lifecycle_id===e.scope.lifecycle_id&&n.root_share_epoch===e.scope.root_share_epoch&&n.account_id===e.scope.account_id&&n.session_id===e.scope.threshold_session_id&&n.signer_set_id===e.scope.signer_set_id&&n.selected_server_id===e.scope.signing_worker_id&&St(t.binding.ceremony.material_activation,e.scope.material_activation)&&t.binding.state_epoch===e.state_epoch&&Wi(t.binding.registered_public_key,e.registered_public_key)&&Wi(t.binding.runtime_policy_binding,e.runtime_policy_binding)&&Wi(t.binding.authorization_digest,e.authorization.authorization_digest)}function Zi(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Ed25519 Yao export artifact must be an object`);let n=Object.keys(t).sort(),r=[`artifactKind`,`privateKey`,`publicKey`];if(n.length!==r.length||n.some((e,t)=>e!==r[t]))throw Error(`Ed25519 Yao export artifact contains unexpected fields`);if(Reflect.get(t,`artifactKind`)!==`near-ed25519-seed-v1`||typeof Reflect.get(t,`publicKey`)!=`string`||typeof Reflect.get(t,`privateKey`)!=`string`||!String(Reflect.get(t,`publicKey`)).startsWith(`ed25519:`)||!String(Reflect.get(t,`privateKey`)).startsWith(`ed25519:`))throw Error(`Ed25519 Yao export artifact is invalid`);let i=Reflect.get(t,`publicKey`),a=Reflect.get(t,`privateKey`);if(typeof i!=`string`||typeof a!=`string`)throw Error(`Ed25519 Yao export artifact is invalid`);return{artifactKind:`near-ed25519-seed-v1`,publicKey:i,privateKey:a}}function Qi(e){let t=new URL(e.routerOrigin);if(t.protocol!==`http:`&&t.protocol!==`https:`||t.pathname!==`/`)throw Error(`Router origin must be an HTTP origin without a path`);if(t.search||t.hash)throw Error(`Router origin must not contain query or hash`);if(typeof e.fetch!=`function`)throw Error(`Router fetch is required`);switch(e.authorization.kind){case`bearer`:if(!e.authorization.value.trim())throw Error(`Router bearer authorization is required`);break;case`recovery_challenge`:if(!e.authorization.challengeId.trim())throw Error(`Router recovery challenge ID is required`);break;case`cookies`:break}return{routerOrigin:t.origin,routing:e.routing,authorization:e.authorization,fetch:e.fetch,traceContext:$i(e.traceContext)}}function $i(e){if(!e)return _n();if(e.kind!==`router_ab_trace_context_v1`)throw Error(`Router trace context kind is invalid`);let t=wn(e.value);if(!t.ok)throw Error(t.message);return t.value}async function ea(e){let t=e.headers.get(`Server-Timing`),n;try{n=await e.json()}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}if(e.ok){let r=t||ta(e.url);return{ok:!0,value:n,...r?{serverTiming:r}:{}}}let r=C(n)?.code;return{ok:!1,message:JSON.stringify(n),...typeof r==`string`?{code:r}:{}}}function ta(e){if(!e||typeof performance>`u`||typeof performance.getEntriesByName!=`function`)return null;let t=performance.getEntriesByName(e,`resource`);for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.entryType!==`resource`)continue;let r=na(Reflect.get(n,`serverTiming`));if(r)return r}return null}function na(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=String(Reflect.get(n,`name`)||``).trim(),r=Number(Reflect.get(n,`duration`));/^[a-z0-9_]+$/.test(e)&&(!Number.isFinite(r)||r<0||t.push(`${e};dur=${r}`))}return t.length>0?t.join(`, `):null}var ra=class{config;constructor(e){this.config=Qi(e)}async send(e){let t;try{let n=!(e.kind===`export_admit`||e.kind===`export_execute`)&&this.config.authorization.kind===`bearer`?this.config.authorization.value:null,r=e.kind===`recovery_admit`&&this.config.authorization.kind===`recovery_challenge`?this.config.authorization.challengeId:null,i=this.config.authorization.kind===`cookies`;t=await this.config.fetch.call(globalThis,new URL(e.path,this.config.routerOrigin),{method:`POST`,headers:{...da(this.config.routing),...n?{authorization:n}:{},...r?{[Lt]:r}:{},"content-type":`application/json`,[vn]:this.config.traceContext.value},credentials:i?`include`:`omit`,body:JSON.stringify(e.body)})}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}return ea(t)}},ia=class{activeMetadata;lifecycle;constructor(e){if(e[Fi]!==!0)throw Error(`Ed25519 Yao Client state requires verified WASM completion`);this.activeMetadata={kind:e.metadata.kind,scope:{lifecycle_id:e.metadata.scope.lifecycle_id,root_share_epoch:e.metadata.scope.root_share_epoch,account_id:e.metadata.scope.account_id,threshold_session_id:e.metadata.scope.threshold_session_id,signer_set_id:e.metadata.scope.signer_set_id,signing_worker_id:e.metadata.scope.signing_worker_id,material_activation:e.metadata.scope.material_activation},applicationBinding:{wallet_id:e.metadata.applicationBinding.wallet_id,near_ed25519_signing_key_id:e.metadata.applicationBinding.near_ed25519_signing_key_id,signing_root_id:e.metadata.applicationBinding.signing_root_id,key_creation_signer_slot:e.metadata.applicationBinding.key_creation_signer_slot},participantIds:[e.metadata.participantIds[0],e.metadata.participantIds[1]],registeredPublicKey:e.metadata.registeredPublicKey.slice(),signingWorkerVerifyingShare:e.metadata.signingWorkerVerifyingShare.slice(),stateEpoch:e.metadata.stateEpoch,transcript:e.metadata.transcript.slice(),activeCapabilityBinding:[...e.metadata.activeCapabilityBinding],materialActivation:e.metadata.materialActivation},this.lifecycle={kind:`active`,activated:e.activated}}sealLocalMaterial(e){let t=Ki(this.lifecycle);try{return{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:e.nonce.slice(),ciphertext:t.seal_local_material(Ii(e.ownedPasskeyPrfFirst,`passkey PRF.first`),e.binding,e.nonce)}}finally{e.ownedPasskeyPrfFirst.fill(0)}}async createSigningShare(e){let t=Ki(this.lifecycle),n=Ii(e.admittedDigest,`admitted digest`),r=Ii(e.signingWorkerVerifyingShare,`SigningWorker verifying share`);if(!Wi(r,this.activeMetadata.signingWorkerVerifyingShare))throw Error(`SigningWorker verifying share does not match activated Client state`);let i=t.create_signing_share(this.activeMetadata.participantIds[0],this.activeMetadata.participantIds[1],n,JSON.stringify(e.signingWorkerCommitments),r);try{return{clientCommitments:Yi(i.client_commitments_json()),clientVerifyingShare:i.client_verifying_share(),clientSignatureShareB64u:i.client_signature_share_b64u()}}finally{i.free()}}metadata(){return{kind:this.activeMetadata.kind,scope:{lifecycle_id:this.activeMetadata.scope.lifecycle_id,root_share_epoch:this.activeMetadata.scope.root_share_epoch,account_id:this.activeMetadata.scope.account_id,threshold_session_id:this.activeMetadata.scope.threshold_session_id,signer_set_id:this.activeMetadata.scope.signer_set_id,signing_worker_id:this.activeMetadata.scope.signing_worker_id,material_activation:this.activeMetadata.scope.material_activation},applicationBinding:{wallet_id:this.activeMetadata.applicationBinding.wallet_id,near_ed25519_signing_key_id:this.activeMetadata.applicationBinding.near_ed25519_signing_key_id,signing_root_id:this.activeMetadata.applicationBinding.signing_root_id,key_creation_signer_slot:this.activeMetadata.applicationBinding.key_creation_signer_slot},participantIds:[this.activeMetadata.participantIds[0],this.activeMetadata.participantIds[1]],registeredPublicKey:this.activeMetadata.registeredPublicKey.slice(),signingWorkerVerifyingShare:this.activeMetadata.signingWorkerVerifyingShare.slice(),stateEpoch:this.activeMetadata.stateEpoch,transcript:this.activeMetadata.transcript.slice(),activeCapabilityBinding:[...this.activeMetadata.activeCapabilityBinding],materialActivation:this.activeMetadata.materialActivation}}status(){switch(this.lifecycle.kind){case`active`:return{kind:`active`};case`disposed`:return{kind:`disposed`};default:return Gi(this.lifecycle)}}dispose(){switch(this.lifecycle.kind){case`active`:{let e=this.lifecycle.activated;this.lifecycle={kind:`disposed`},e.free();return}case`disposed`:return;default:return Gi(this.lifecycle)}}};function aa(e){let t=null;try{return t=Yr.import_local_material(Ii(e.ownedPasskeyPrfFirst,`passkey PRF.first`),e.binding,e.sealed.nonce,e.sealed.ciphertext,e.metadata.registeredPublicKey,e.metadata.stateEpoch,e.metadata.participantIds[0],e.metadata.participantIds[1],e.metadata.signingWorkerVerifyingShare),new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedPasskeyPrfFirst.fill(0)}}function oa(e){let t=null;try{if(t=Yr.import_linked_material(Ii(e.ownedClientScalarShare,`linked-device Ed25519 Client share`),e.metadata.participantIds[0],e.metadata.participantIds[1],JSON.stringify(e.publicReceipt)),t.state_epoch()!==e.metadata.stateEpoch||!Wi(t.registered_public_key(),e.metadata.registeredPublicKey)||!Wi(e.publicReceipt.signing_worker_verifying_share,e.metadata.signingWorkerVerifyingShare))throw Error(`linked-device Ed25519 material metadata does not match its receipt`);return new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedClientScalarShare.fill(0)}}function sa(e){let t=null;try{return t=ii(e.ownedFactorSecret,e.envelope.bindingJson,e.envelope.nonce,e.envelope.ciphertext,e.envelope.aadHash,e.envelope.ciphertextDigest,e.applicationBindingDigest,e.metadata.registeredPublicKey,e.metadata.stateEpoch,e.metadata.participantIds[0],e.metadata.participantIds[1],e.metadata.signingWorkerVerifyingShare,e.sealed.nonce,e.sealed.ciphertext),new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedFactorSecret.fill(0)}}let ca=null;function la(e){throw ca=null,e}var ua=class e{constructor(){}static async initializeBundled(){return ca??=Mi().catch(la),await ca,new e}importLocalMaterial(e){return aa(e)}importLinkedMaterial(e){return oa(e)}openCustodyCache(e){return sa(e)}async exportSeed(e){let t=await e.transport.send({kind:`export_admit`,path:Wt,body:Pi({protocol:e.request,authorization:e.authorization})});if(!t.ok)return t;let n;try{n=Vi(t.value)}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}if(!Xi(e.request,n.protocol))return{ok:!1,message:`Router export admission does not match the requested exact capability`};let r;if(Li(e)){if(n.kind!==`protocol_only`)return{ok:!1,message:`Passkey export admission returned an Email OTP factor release`};r=e.custodyEnvelope}else{if(n.kind!==`protocol_with_factor_release`)return{ok:!1,message:`Email OTP export admission did not return the matching factor release`};let t=n.factorRelease;if(!t||t.challengeId!==e.authorization.challengeId)return{ok:!1,message:`Email OTP export admission did not return the matching factor release`};try{r=await e.resolveCustodyEnvelope(t)}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}let i=Hi(),a;try{a=zi({admission:n.protocol,applicationBinding:e.request.application_binding,participantIds:e.request.participant_ids,custodyEnvelope:r,entropy:i})}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}finally{r.factorSecret.fill(0),Ui(i)}try{let t=jt(JSON.parse(a.execute_request_json()));if(!t.ok)return{ok:!1,message:t.message};let n=await e.transport.send({kind:`export_execute`,path:It,body:{protocol:t.value}});if(!n.ok)return n;let r=Mt(n.value);if(!r.ok)return{ok:!1,message:r.message};let i=a.complete(JSON.stringify(r.value));try{return{ok:!0,artifact:Zi(i.take_export_artifact_json())}}finally{i.free()}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}finally{a.free()}}};function da(e){switch(e.kind){case`discovery`:return{};case`direct`:case`regional`:return j(e);default:return Gi(e)}}function fa(e){return{materialActivation:e.materialActivation,lifecycleId:e.scope.lifecycle_id,signingRootVersion:e.scope.root_share_epoch,signingRootId:e.applicationBinding.signing_root_id,signerSetId:e.scope.signer_set_id,thresholdSessionId:e.scope.threshold_session_id,activationTranscriptB64u:L(e.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(e.activeCapabilityBinding))}}function pa(e){if(!tn(e.binding))throw Error(`wallet custody cache accepts wallet custody seed envelopes only`);return{bindingJson:nn(e),nonceB64u:e.nonceB64u,ciphertextB64u:e.sealedCustodySecretB64u,aadHashB64u:e.aadHashB64u,ciphertextDigestB64u:e.ciphertextDigestB64u}}function ma(e){let{binding:t}=e.material,{activation:n}=e;return{kind:Ni,scope:{lifecycle_id:n.lifecycleId,root_share_epoch:n.signingRootVersion,account_id:t.walletId,threshold_session_id:n.thresholdSessionId,signer_set_id:n.signerSetId,signing_worker_id:t.signingWorkerId,material_activation:wt(n.materialActivation)},applicationBinding:{wallet_id:t.walletId,near_ed25519_signing_key_id:t.nearEd25519SigningKeyId,signing_root_id:n.signingRootId,key_creation_signer_slot:t.signerSlot},participantIds:t.participantIds,registeredPublicKey:R(t.registeredPublicKeyB64u),signingWorkerVerifyingShare:R(t.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(t.stateEpoch),transcript:R(n.activationTranscriptB64u),activeCapabilityBinding:Array.from(R(n.activationCapabilityBindingB64u)),materialActivation:n.materialActivation}}async function ha(e){let t=ma({material:e.material,activation:e.activation});return(await ua.initializeBundled()).openCustodyCache({ownedFactorSecret:e.ownedFactorSecret,envelope:{bindingJson:e.envelope.bindingJson,nonce:R(e.envelope.nonceB64u),ciphertext:R(e.envelope.ciphertextB64u),aadHash:R(e.envelope.aadHashB64u),ciphertextDigest:R(e.envelope.ciphertextDigestB64u)},applicationBindingDigest:R(e.material.binding.applicationBindingDigestB64u),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:R(e.material.sealed.nonceB64u),ciphertext:R(e.material.sealed.ciphertextB64u)},metadata:t})}async function ga(e){let t=await e.loadCachedMaterial();return t.kind===`found`?{kind:`opened`,activeClient:await ha({material:t.material,activation:e.activation,envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret})}:(e.ownedFactorSecret.fill(0),{kind:`rejoin_required`})}function _a(e){let t=String(e.rpId).trim(),n=String(e.nearAccountId).trim(),r=String(e.nearEd25519SigningKeyId).trim(),i=String(e.relayerKeyId).trim(),a=String(e.credentialIdB64u).trim(),o=ne(e.participantIds),s=Math.floor(Number(e.signerSlot));if(!t||!n||!r||!i||!a||!o||!Number.isSafeInteger(s)||s<1)throw Error(`Passkey Ed25519 sealed restore metadata is incomplete`);return{rpId:t,nearAccountId:n,nearEd25519SigningKeyId:r,relayerKeyId:i,participantIds:[...o],runtimePolicyScope:e.runtimePolicyScope,signerSlot:s,routerAbNormalSigning:e.routerAbNormalSigning,credentialIdB64u:a,materialActivation:e.materialActivation}}async function va(e){let t=String(e.session.thresholdSessionId||``).trim(),n=String(e.session.walletSessionAuth.walletSessionToken||``).trim(),r=String(e.session.signingLane.identity.signer.account.wallet.walletId||``).trim(),i=String(e.prfFirstB64u||``).trim(),a=Math.floor(Number(e.session.signingWalletSession.expiresAtMs)||0),o=Math.floor(Number(e.session.remainingUses)),s=e.session.signingLane.identity.auth;if(s.kind!==`passkey`)throw Error(`Ed25519 Yao sealed refresh persistence requires a passkey lane`);if(!t||!n||!r||!i||a<=0||!Number.isSafeInteger(o)||o<0)throw Error(`Ed25519 Yao sealed refresh persistence received an invalid session`);let c=e.session.signingLane.identity.signer;if(r!==String(c.account.wallet.walletId)||e.ed25519Restore.nearAccountId!==String(c.account.nearAccountId)||e.ed25519Restore.nearEd25519SigningKeyId!==String(c.nearEd25519SigningKeyId)||e.ed25519Restore.signerSlot!==c.signerSlot||e.ed25519Restore.rpId!==String(s.rpId)||e.ed25519Restore.credentialIdB64u!==s.credentialIdB64u||!p(e.ed25519Restore.materialActivation,e.materialActivation)||e.ed25519Restore.routerAbNormalSigning?.signingWorkerId!==e.session.routerAbNormalSigning.signingWorkerId)throw Error(`Ed25519 Yao sealed refresh metadata does not match the exact session`);let l={curve:`ed25519`,authMethod:`passkey`,walletId:r,relayerUrl:e.session.relayerUrl,walletSessionToken:n,ed25519Restore:e.ed25519Restore};await e.persistence.hydrateSigningSession({thresholdSessionId:t,prfFirstB64u:i,expiresAtMs:a,remainingUses:o,transport:l})}const ya=`[Registration] wallet timing summary`,ba=new Map(Object.entries({yao_credential_digest:`yaoServerCredentialDigestMs`,yao_d1_admission_read:`yaoServerD1AdmissionReadMs`,yao_router_execution:`yaoServerRouterExecutionMs`,yao_result_reconstruction:`yaoServerResultReconstructionMs`,yao_router_prepare_pair:`yaoServerRouterPreparePairMs`,yao_router_role_execution:`yaoServerRouterRoleExecutionMs`,yao_router_signing_worker_delivery:`yaoServerRouterSigningWorkerDeliveryMs`,ecdsa_respond_d1_claim:`ecdsaRespondD1ClaimMs`,ecdsa_respond_reconcile:`ecdsaRespondReconcileMs`,ecdsa_respond_router:`ecdsaRespondRouterMs`,ecdsa_respond_d1_commit:`ecdsaRespondD1CommitMs`,ecdsa_respond_total:`ecdsaRespondTotalMs`,ecdsa_activate_d1_claim:`ecdsaActivateD1ClaimMs`,ecdsa_activate_reconcile:`ecdsaActivateReconcileMs`,ecdsa_activate_router:`ecdsaActivateRouterMs`,ecdsa_activate_bootstrap:`ecdsaActivateBootstrapMs`,ecdsa_activate_session_provision:`ecdsaActivateSessionProvisionMs`,ecdsa_activate_d1_commit:`ecdsaActivateD1CommitMs`,ecdsa_activate_policy_lookup:`ecdsaActivatePolicyLookupMs`,ecdsa_activate_jwt_mint:`ecdsaActivateJwtMintMs`,ecdsa_activate_total:`ecdsaActivateTotalMs`,ecdsa_rt_authorize:`ecdsaRtAuthorizeMs`,ecdsa_rt_admission:`ecdsaRtAdmissionMs`,ecdsa_rt_derivers:`ecdsaRtDeriversMs`,ecdsa_rt_deriver_a:`ecdsaRtDeriverAMs`,ecdsa_rt_deriver_b:`ecdsaRtDeriverBMs`,ecdsa_rt_completion:`ecdsaRtCompletionMs`,ecdsa_rt_total:`ecdsaRtTotalMs`,ecdsa_rt_act_session:`ecdsaRtActSessionMs`,ecdsa_rt_act_worker:`ecdsaRtActWorkerMs`,ecdsa_rt_act_total:`ecdsaRtActTotalMs`,ecdsa_a_parse:`ecdsaDeriverAParseMs`,ecdsa_a_preload:`ecdsaDeriverAPreloadMs`,ecdsa_a_execute:`ecdsaDeriverAExecuteMs`,ecdsa_a_total:`ecdsaDeriverATotalMs`,ecdsa_b_parse:`ecdsaDeriverBParseMs`,ecdsa_b_preload:`ecdsaDeriverBPreloadMs`,ecdsa_b_execute:`ecdsaDeriverBExecuteMs`,ecdsa_b_total:`ecdsaDeriverBTotalMs`,ecdsa_sw_parse:`ecdsaSigningWorkerParseMs`,ecdsa_sw_activate:`ecdsaSigningWorkerActivateMs`,ecdsa_sw_total:`ecdsaSigningWorkerTotalMs`,near_finalize_authority:`nearFinalizeAuthorityMs`,near_finalize_fingerprint:`nearFinalizeFingerprintMs`,near_finalize_side_effect:`nearFinalizeSideEffectMs`,near_finalize_cleanup:`nearFinalizeCleanupMs`,near_finalize_session_projection:`nearFinalizeSessionProjectionMs`,near_finalize_session_seal:`nearFinalizeSessionSealMs`,near_finalize_total:`nearFinalizeTotalMs`}));function xa(e,t,n){br()&&console.info(`[Registration] ECDSA Server-Timing header presence`,{leg:t,present:!!n?.trim()}),Sa(e,n)}function Sa(e,t){if(e)for(let[n,r]of Ca(t))e.record(n,r)}function Ca(e){if(!e)return[];let t=[];for(let n of e.split(`,`)){let e=n.split(`;`),r=String(e[0]||``).trim(),i=ba.get(r);if(i)for(let n of e.slice(1)){let[e,r]=n.split(`=`);if(String(e||``).trim()!==`dur`)continue;let a=Number(String(r||``).trim());if(!Number.isFinite(a)||a<0)break;t.push([i,a]);break}}return t}function wa(e){Ea({ceremonyId:e.ceremonyId,stage:e.stage,durationMs:Math.max(0,performance.now()-e.startedAt),outcome:e.outcome})}function Ta(e,t,n){Ea({ceremonyId:e,stage:`session_hydration.${t}`,durationMs:n,outcome:`success`})}function Ea(e){if(br())try{console.info(`[Registration] NEAR timing`,JSON.stringify({event:`near_registration_timing`,ceremonyId:e.ceremonyId,stage:e.stage,durationMs:e.durationMs,outcome:e.outcome}))}catch{}}const Da=[`passkeyAuthConfirmationMs`,`passkeyAuthPrfExtractionMs`,`passkeyAuthCredentialRedactionMs`,`passkeyAuthWorkerReadyMs`,`passkeyAuthWorkerRequestRoundTripMs`,`passkeyAuthWorkerResponseValidationMs`,`passkeyAuthRequestSetupMs`,`passkeyAuthPromptUserMs`,`passkeyAuthPromptElementDefineMs`,`passkeyAuthPromptMountMs`,`passkeyAuthPromptHostFirstUpdateMs`,`passkeyAuthPromptHostInteractiveMs`,`passkeyAuthPromptConfirmEventMs`,`passkeyAuthPromptDecisionWaitMs`,`passkeyAuthCredentialCreateStartMs`,`passkeyAuthCredentialCreateMs`,`passkeyAuthCredentialSerializeMs`,`passkeyAuthDuplicateRetryCount`,`passkeyAuthMainThreadTotalMs`],Oa=[`emailOtpYaoEnrollmentMaterialWaitMs`,`emailOtpYaoWorkerRegistrationMs`,`emailOtpYaoTotalMs`],ka=[`ecdsaClientBootstrapMs`,`ecdsaRegistrationTotalMs`,`ecdsaRegistrationClientCreateMs`,`ecdsaRegistrationGatewayRespondMs`,`ecdsaRegistrationClientProofVerifyMs`,`ecdsaRegistrationGatewayActivateMs`,`ecdsaRegistrationClientActivationFinalizeMs`],Aa=[`ecdsaRegistrationPersistenceMs`,`ecdsaRegistrationSessionFinalizeMs`,`ecdsaRegistrationLocalRecordPersistenceMs`,`ecdsaRegistrationTargetCount`,`ecdsaRegistrationClientFinalizeMs`,`ecdsaRegistrationClientMaterialStoreMs`,`ecdsaRegistrationServerBootstrapMs`,`ecdsaRegistrationPasskeyBootstrapStoreMs`,`ecdsaRegistrationRoleLocalRecordPersistenceMs`,`ecdsaRegistrationWarmSessionHydrationMs`,`ecdsaRegistrationWarmSessionWorkerReadyMs`,`ecdsaRegistrationWarmSessionWorkerPutMs`,`ecdsaRegistrationWarmSessionSealedRecordPersistMs`,`ecdsaRegistrationWarmSessionSealResolveTransportMs`,`ecdsaRegistrationWarmSessionSealExistingRecordReadMs`,`ecdsaRegistrationWarmSessionSealPolicyReadMs`,`ecdsaRegistrationWarmSessionSealApplyServerSealMs`,`ecdsaRegistrationWarmSessionSealApplyRuntimeSetupMs`,`ecdsaRegistrationWarmSessionSealApplyClientSealMs`,`ecdsaRegistrationWarmSessionSealApplyServerRouteMs`,`ecdsaRegistrationWarmSessionSealApplyClientUnsealMs`,`ecdsaRegistrationWarmSessionSealApplyPolicyUpdateMs`,`ecdsaRegistrationWarmSessionSealRegisterMs`,`ecdsaRegistrationWarmSessionSealVerifyReadMs`,`ecdsaRegistrationEmailOtpSessionCommitMs`],ja=[...ka,...Aa],Ma=[`registrationWarmupMs`,`registrationWarmupWaitMs`,`registrationWarmupAuthenticatedWalletStateMs`,`registrationWarmupNoncePrefetchMs`,`registrationWarmupKeyMaterialReadMs`,`registrationWarmupUiConfirmPrewarmMs`,`registrationWarmupEmailOtpWorkerPrewarmMs`,`registrationWarmupEmailOtpYaoWasmInitMs`,`managedRegistrationGrantMs`,`registrationIntentMs`,`registrationIntentDigestMs`,`authProofMs`,...Da,`emailOtpEnrollmentMaterialMs`,...Oa,`yaoBranchTotalMs`,`yaoAdmissionMs`,`yaoClientSessionCreateMs`,`yaoClientCompletionMs`,`yaoServerCredentialDigestMs`,`yaoServerD1AdmissionReadMs`,`yaoServerRouterExecutionMs`,`yaoServerResultReconstructionMs`,`yaoServerRouterPreparePairMs`,`yaoServerRouterRoleExecutionMs`,`yaoServerRouterSigningWorkerDeliveryMs`,`ecdsaRespondD1ClaimMs`,`ecdsaRespondReconcileMs`,`ecdsaRespondRouterMs`,`ecdsaRespondD1CommitMs`,`ecdsaRespondTotalMs`,`ecdsaActivateD1ClaimMs`,`ecdsaActivateReconcileMs`,`ecdsaActivateRouterMs`,`ecdsaActivateBootstrapMs`,`ecdsaActivateSessionProvisionMs`,`ecdsaActivateD1CommitMs`,`ecdsaActivatePolicyLookupMs`,`ecdsaActivateJwtMintMs`,`ecdsaActivateTotalMs`,`ecdsaRtAuthorizeMs`,`ecdsaRtAdmissionMs`,`ecdsaRtDeriversMs`,`ecdsaRtDeriverAMs`,`ecdsaRtDeriverBMs`,`ecdsaRtCompletionMs`,`ecdsaRtTotalMs`,`ecdsaRtActSessionMs`,`ecdsaRtActWorkerMs`,`ecdsaRtActTotalMs`,`ecdsaDeriverAParseMs`,`ecdsaDeriverAPreloadMs`,`ecdsaDeriverAExecuteMs`,`ecdsaDeriverATotalMs`,`ecdsaDeriverBParseMs`,`ecdsaDeriverBPreloadMs`,`ecdsaDeriverBExecuteMs`,`ecdsaDeriverBTotalMs`,`ecdsaSigningWorkerParseMs`,`ecdsaSigningWorkerActivateMs`,`ecdsaSigningWorkerTotalMs`,`nearFinalizeAuthorityMs`,`nearFinalizeFingerprintMs`,`nearFinalizeSideEffectMs`,`nearFinalizeCleanupMs`,`nearFinalizeSessionProjectionMs`,`nearFinalizeSessionSealMs`,`nearFinalizeTotalMs`,`walletRegisterStartMs`,...ka,`emailOtpRecoveryCodeBackupMs`,`walletRegisterFinalizeMs`,...Aa];function q(e){throw Error(`Unexpected registration timing branch: ${String(e)}`)}function Na(e){switch(e.kind){case`near_ed25519`:return`near_ed25519`;case`evm_family_ecdsa`:return`evm_family_ecdsa`;default:return q(e)}}function Pa(e){return{kind:`signer_set`,branches:e.branches.map(Na)}}function Fa(e,t){return e.branches.includes(t)}function Ia(e){return Math.max(0,Math.round(performance.now()-e))}function La(e){switch(e){case`registrationIntentLoadMs`:case`registrationIntentDigestMs`:case`registrationIntentConsumeMs`:case`registrationPreparationPersistMs`:case`registrationPreparationLoadMs`:case`registrationPreparationConsumeMs`:case`registrationPreparationScopeCheckMs`:case`registrationAuthorityVerifyMs`:case`registrationEcdsaPrepareMs`:case`registrationCeremonyPersistMs`:case`registerPrepareTotalMs`:case`registerStartTotalMs`:case`registrationEcdsaRespondMs`:case`registrationFinalizeReplayLoadMs`:case`registrationCeremonyLoadMs`:case`registrationEcdsaBootstrapVerifyMs`:case`sponsoredNearAccountCreateMs`:case`registrationKeygenMs`:case`registrationEmailOtpEnrollmentPlanMs`:case`relaySessionMintMs`:case`relayGoogleEmailOtpActivationPlanMs`:case`relayPersistenceMs`:case`registrationFinalizeReplayCacheMs`:case`registerFinalizeTotalMs`:return e;default:return null}}function Ra(e){if(!b(e)||e.kind!==`wallet_registration_route_diagnostics_v1`||e.route!==`wallets_register_start`&&e.route!==`wallets_register_ecdsa_derivation_respond`&&e.route!==`wallets_register_finalize`||!Array.isArray(e.entries))return null;let t=[];for(let n of e.entries){if(!b(n))continue;let e=La(n.name),r=Number(n.durationMs);!e||!Number.isFinite(r)||r<0||t.push({name:e,durationMs:r})}return{kind:`wallet_registration_route_diagnostics_v1`,route:e.route,entries:t}}function za(e){return{kind:e.kind,route:e.route,entries:e.entries.map(Ba)}}function Ba(e){return{name:e.name,durationMs:e.durationMs}}function Va(e,t){let n={};for(let r of e)n[r]=t[r];return n}function Ha(e){let t={};for(let n of e)t[n]=0;return t}function Ua(e){switch(e.authMethod){case`passkey`:return{kind:`passkey`,authProofMs:e.buckets.authProofMs,...Va(Da,e.buckets),emailOtpEnrollmentMaterialMs:0,emailOtpRecoveryCodeBackupMs:0};case`email_otp`:return{kind:`email_otp`,authProofMs:e.buckets.authProofMs,...Ha(Da),emailOtpEnrollmentMaterialMs:e.buckets.emailOtpEnrollmentMaterialMs,emailOtpRecoveryCodeBackupMs:e.buckets.emailOtpRecoveryCodeBackupMs};default:return q(e.authMethod)}}function Wa(e){return Fa(e.signerSet,`near_ed25519`)?{kind:`ed25519_yao_enabled`,...Va(Oa,e.buckets)}:{kind:`ed25519_disabled`,...Ha(Oa)}}function Ga(e){return Fa(e.signerSet,`evm_family_ecdsa`)?{kind:`ecdsa_enabled`,...Va(ja,e.buckets)}:{kind:`ecdsa_disabled`,...Ha(ja)}}const Ka=[`registrationWarmupWaitMs`,`managedRegistrationGrantMs`,`registrationIntentMs`,`registrationIntentDigestMs`,`authProofMs`,`emailOtpEnrollmentMaterialMs`,`emailOtpYaoEnrollmentMaterialWaitMs`,`emailOtpYaoWorkerRegistrationMs`,`emailOtpYaoTotalMs`,`walletRegisterStartMs`,`ecdsaClientBootstrapMs`,`ecdsaRegistrationTotalMs`,`emailOtpRecoveryCodeBackupMs`,`walletRegisterFinalizeMs`,`ecdsaRegistrationPersistenceMs`];function qa(e){return e.startsWith(`registrationWarmup`)?`warmup`:e.startsWith(`passkeyAuth`)||e===`authProofMs`?`auth`:e.includes(`Yao`)||e.includes(`yao`)?`ed25519_yao`:e.includes(`ecdsa`)?`ecdsa`:`registration`}function Ja(e){return{name:e.name,kind:e.kind,startOffsetMs:e.startOffsetMs,endOffsetMs:e.endOffsetMs}}function Ya(e,t){let n=t.map(t=>({start:Math.max(0,Math.min(e,t.startOffsetMs)),end:Math.max(0,Math.min(e,t.endOffsetMs))})).filter(e=>e.end>e.start).sort((e,t)=>e.start-t.start||e.end-t.end),r=0,i=0,a=0;for(let e of n){if(a<=i){i=e.start,a=e.end;continue}if(e.start>a){r+=a-i,i=e.start,a=e.end;continue}a=Math.max(a,e.end)}return a>i?r+a-i:r}function Xa(e){let t=Ka.map(t=>({name:t,durationMs:e.buckets[t]})),n=t.reduce((e,t)=>e+Math.max(0,t.durationMs),0),r=t.filter(e=>e.durationMs>0).sort((e,t)=>t.durationMs===e.durationMs?e.name.localeCompare(t.name):t.durationMs-e.durationMs).slice(0,5),i=Ya(e.totalElapsedMs,e.spans);return{kind:`registration_critical_path_summary_v2`,totalElapsedMs:e.totalElapsedMs,measuredWorkMs:n,spanUnionMs:i,spanCoverageRatio:e.totalElapsedMs>0?Math.min(1,i/e.totalElapsedMs):1,unattributedElapsedMs:Math.max(0,e.totalElapsedMs-i),overlappedOrBackgroundMs:Math.max(0,n-e.totalElapsedMs),topBuckets:r,spans:e.spans.map(Ja)}}function Za(e){let t=Va(Ma,e.buckets);return{...t,auth:Ua({authMethod:e.authMethod,buckets:t}),ed25519:Wa({signerSet:e.signerSet,buckets:t}),ecdsa:Ga({signerSet:e.signerSet,buckets:t}),emailOtpYaoPrewarm:{...e.emailOtpYaoPrewarm}}}var Qa=class{startedAt;nearStageStartedAt;buckets;relayDiagnostics;spans;emailOtpYaoPrewarm;constructor(e){this.startedAt=e,this.nearStageStartedAt=e,this.buckets=Ha(Ma),this.relayDiagnostics=[],this.spans=[],this.emailOtpYaoPrewarm=$a()}markNearStage(e,t){let n=performance.now();Ea({ceremonyId:e,stage:t,durationMs:n-this.nearStageStartedAt,outcome:`success`}),this.nearStageStartedAt=n}async measure(e,t){let n=performance.now();try{return await t()}finally{this.buckets[e]=Ia(n),this.recordSpan(e,n,performance.now())}}record(e,t){let n=Math.max(0,Math.round(t));this.buckets[e]+=n}snapshot(){return Va(Ma,this.buckets)}spansSnapshot(){return this.spans.map(Ja)}recordSpan(e,t,n){this.spans.push({name:e,kind:qa(e),startOffsetMs:Math.max(0,Math.round(t-this.startedAt)),endOffsetMs:Math.max(0,Math.round(n-this.startedAt))})}captureRouteDiagnostics(e){let t=Ra(e);t&&this.relayDiagnostics.push(t)}captureWarmupDiagnostics(e){this.buckets.registrationWarmupAuthenticatedWalletStateMs=e.authenticatedWalletStateMs,this.buckets.registrationWarmupNoncePrefetchMs=e.noncePrefetchMs,this.buckets.registrationWarmupKeyMaterialReadMs=e.keyMaterialReadMs,this.buckets.registrationWarmupUiConfirmPrewarmMs=e.uiConfirmPrewarmMs,this.buckets.registrationWarmupEmailOtpWorkerPrewarmMs=e.emailOtpWorkerPrewarmMs,this.buckets.registrationWarmupEmailOtpYaoWasmInitMs=e.emailOtpYaoWasmInitMs,this.emailOtpYaoPrewarm={...e.emailOtpYaoPrewarm}}emailOtpYaoPrewarmSnapshot(){return{...this.emailOtpYaoPrewarm}}capturePasskeyAuthDiagnostics(e){this.buckets.passkeyAuthConfirmationMs=e.requestConfirmationMs,this.buckets.passkeyAuthPrfExtractionMs=e.prfExtractionMs,this.buckets.passkeyAuthCredentialRedactionMs=e.credentialRedactionMs,this.buckets.passkeyAuthWorkerReadyMs=e.confirmationWorkerReadyMs,this.buckets.passkeyAuthWorkerRequestRoundTripMs=e.confirmationWorkerRequestRoundTripMs,this.buckets.passkeyAuthWorkerResponseValidationMs=e.confirmationWorkerResponseValidationMs,this.buckets.passkeyAuthRequestSetupMs=e.confirmationRequestSetupMs,this.buckets.passkeyAuthPromptUserMs=e.confirmationPromptUserMs,this.buckets.passkeyAuthPromptElementDefineMs=e.confirmationPromptElementDefineMs,this.buckets.passkeyAuthPromptMountMs=e.confirmationPromptMountMs,this.buckets.passkeyAuthPromptHostFirstUpdateMs=e.confirmationPromptHostFirstUpdateMs,this.buckets.passkeyAuthPromptHostInteractiveMs=e.confirmationPromptHostInteractiveMs,this.buckets.passkeyAuthPromptConfirmEventMs=e.confirmationPromptConfirmEventMs,this.buckets.passkeyAuthPromptDecisionWaitMs=e.confirmationPromptDecisionWaitMs,this.buckets.passkeyAuthCredentialCreateStartMs=e.confirmationCredentialCreateStartMs,this.buckets.passkeyAuthCredentialCreateMs=e.confirmationCredentialCreateMs,this.buckets.passkeyAuthCredentialSerializeMs=e.confirmationCredentialSerializeMs,this.buckets.passkeyAuthDuplicateRetryCount=e.confirmationDuplicateRetryCount,this.buckets.passkeyAuthMainThreadTotalMs=e.confirmationMainThreadTotalMs}routeDiagnosticsSnapshot(){return this.relayDiagnostics.map(za)}totalMs(){return Ia(this.startedAt)}};function $a(){return{kind:`not_requested`,elapsedMs:0,workerPrewarmMs:0,yaoWasmInitMs:0}}function eo(e){let t=e.recorder.totalMs(),n=e.recorder.snapshot();return{kind:`registration_timing_summary_v2`,status:`succeeded`,authMethod:e.authMethod,signerSet:e.signerSet,totalMs:t,criticalPath:Xa({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:Za({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function to(e){let t=e.recorder.totalMs(),n=e.recorder.snapshot();return{kind:`registration_timing_summary_v2`,status:`failed`,authMethod:e.authMethod,signerSet:e.signerSet,totalMs:t,criticalPath:Xa({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),errorCode:e.errorCode,relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:Za({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function no(e){br()&&(console.info(ya,e),console.info(`${ya} ${JSON.stringify(e)}`))}function ro(e){let t={event:`seams_registration_timing_span_v1`,span:e.span,operation:`registration`,outcome:e.outcome,duration_ms:Math.max(0,Math.round(e.durationMs)),trace_id:e.traceContext.value};try{e.callback?.(t)}catch{}}function J(e){return{kind:`unavailable`,reason:e}}function io(e){let t=e.selected;if(t.kind!==`resolved`)switch(t.kind){case`missing_selection`:return J(`selected_authority_missing`);case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return J(`selected_authority_invalid`);default:return t}return t.selection.walletId!==e.walletId||t.authMethod.walletId!==e.walletId||t.authority.walletId!==e.walletId||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.walletAuthorityId!==t.authority.authorityId?J(`authority_identity_mismatch`):t.selection.lockState===`unlocked`?t.authMethod.status===`active`?t.authority.state===`active`?t.authMethod.kind===e.authMethod?{authority:t.authority,authMethod:t.authMethod}:J(`auth_method_mismatch`):J(`authority_inactive`):J(`auth_method_inactive`):J(`wallet_locked`)}function ao(e){let t=e.authority.signerActivations;return e.keyFamily===`ed25519`?t.ed25519?.materialActivation??null:t.ecdsa?.materialActivation??null}function oo(e){return e.session.capabilitySubjects.filter(t=>t.kind===`sign`&&t.keyFamily===e.keyFamily&&p(t.materialActivation,e.materialActivation)).length===1}function so(e){return ir(e)?{keyFamily:`ecdsa_secp256k1`,materialActivation:e.signer.materialActivation}:{keyFamily:`ed25519`}}async function co(e){let{input:t,ports:n}=e,r;try{r=await n.resolveSelectedWalletAuthority(String(t.walletId))}catch{return J(`persistence_unavailable`)}let i=io({selected:r,walletId:t.walletId,authMethod:t.authMethod});if(`kind`in i)return i;let a=ao({authority:i.authority,keyFamily:t.requiredSigningSubject.keyFamily});if(!a)return J(`signer_material_missing`);if(t.requiredSigningSubject.keyFamily===`ecdsa_secp256k1`&&!p(t.requiredSigningSubject.materialActivation,a))return J(`signer_material_mismatch`);let o;try{o=await n.readExactWithOperationCredential({walletId:t.walletId,authorityId:i.authority.authorityId,authMethodId:i.authMethod.walletAuthMethodId})}catch{return J(`persistence_unavailable`)}switch(o.kind){case`found`:break;case`missing`:return J(`wallet_session_missing`);case`upgrade_required`:return J(`wallet_session_upgrade_required`)}let s=o.record,c=o.operationCredential;return s.walletId!==t.walletId||s.authorityId!==i.authority.authorityId||s.authMethodId!==i.authMethod.walletAuthMethodId||s.authorityDigestB64u!==i.authority.authorityDigestB64u||s.authorityRevocationEpoch!==i.authority.revocationEpoch||s.quotaId!==t.quotaId||c.walletSessionId!==t.walletSessionId||c.token.trim().length===0?J(`wallet_session_identity_mismatch`):t.expiry.kind===`unexpired`&&s.expiresAtMs<=t.expiry.nowMs?J(`wallet_session_expired`):t.expiry.kind===`expired`&&s.expiresAtMs>t.expiry.nowMs?J(`wallet_session_not_expired`):oo({session:s,keyFamily:t.requiredSigningSubject.keyFamily,materialActivation:a})?{kind:`resolved`,resolved:{authMethod:i.authMethod,session:s,operationCredential:c,walletSessionId:c.walletSessionId,materialActivation:a}}:J(`wallet_session_capability_mismatch`)}function lo(e){return String(e||``).trim()}function uo(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:0}function fo(e){let t=Math.floor(Number(e));return Number.isSafeInteger(t)&&t>=0?t:null}function po(e){return e.expiresAtMs<=e.nowMs?{kind:`expired`}:e.remainingUses<=0?{kind:`exhausted`}:null}function mo(e,t){let n=lo(e);return n?{kind:`wallet_session_opaque`,walletSessionToken:n,credential:{kind:`wallet_session_opaque`,walletSessionToken:n,home:t}}:null}function ho(e){let t=mo(lo(e.walletSessionToken),e.home);if(!t)return{ok:!1,reason:`missing_wallet_session_token`};let n=lo(e.walletId),r=lo(e.nearAccountId),i=lo(e.nearEd25519SigningKeyId);if(!n||!r||!i)return{ok:!1,reason:`wallet_binding_mismatch`};let a=_e(e.walletSessionId),o=ve(e.authorizationId),c=he(e.quotaId),l=s(e.thresholdSessionId);if(!a.ok||!o.ok)return{ok:!1,reason:`missing_session_identity`};if(!c.ok)return{ok:!1,reason:`missing_quota_id`};if(!l.ok)return{ok:!1,reason:`missing_threshold_session_id`};let u=fo(e.nowMs),d=uo(e.remainingUses),f=uo(e.expiresAtMs);if(u==null||!Number.isSafeInteger(e.remainingUses)||!Number.isSafeInteger(e.expiresAtMs)||e.remainingUses<0||e.expiresAtMs<=0)return{ok:!1,reason:`invalid_budget`};let p=po({remainingUses:Math.max(0,Math.floor(e.remainingUses)),expiresAtMs:Math.max(0,Math.floor(e.expiresAtMs)),nowMs:u});if(p?.kind===`expired`)return{ok:!1,reason:`expired`};if(p?.kind===`exhausted`)return{ok:!1,reason:`exhausted`};let m;try{m=re(e.runtimePolicyScope)}catch{return{ok:!1,reason:`missing_signing_root`}}return m.signingRootId!==lo(e.signingRootId)||m.signingRootVersion!==lo(e.signingRootVersion)?{ok:!1,reason:`signing_root_mismatch`}:{ok:!0,value:{curve:`ed25519`,auth:t,walletSessionId:a.value,authorizationId:o.value,quotaId:c.value,thresholdSessionId:l.value,remainingUses:d,expiresAtMs:f,runtimePolicyScope:e.runtimePolicyScope,signingRootId:m.signingRootId,signingRootVersion:lo(m.signingRootVersion),routerAbNormalSigning:e.routerAbNormalSigning}}}const go=qe.signingSessionSeals,_o=qe.signingSessionRestoreLeases,vo=[Ye.ed25519ThresholdSessionId,Ye.ecdsaThresholdSessionId];function yo(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error||Error(`IndexedDB request failed`))})}function bo(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(e.error||Error(`IndexedDB transaction aborted`)),e.onerror=()=>n(e.error||Error(`IndexedDB transaction failed`))})}async function xo(){if(Xe.isDisabled())return null;try{return Je(await Xe.getDB())}catch{return null}}function So(e,t){return new Promise((n,r)=>{let i=[],a=e.openCursor(t);a.onsuccess=()=>{let e=a.result;if(!e){n(i);return}i.push({primaryKey:e.primaryKey,value:e.value}),e.continue()},a.onerror=()=>r(a.error||Error(`IndexedDB cursor failed`))})}function Co(e){return new Promise((t,n)=>{let r=[],i=e.openCursor();i.onsuccess=()=>{let e=i.result;if(!e){t(r);return}r.push({primaryKey:e.primaryKey,value:e.value}),e.continue()},i.onerror=()=>n(i.error||Error(`IndexedDB cursor failed`))})}async function wo(e,t){let n=new Map;for(let r of vo)try{let i=await So(e.index(r),t);for(let e of i)n.set(String(e.primaryKey),e)}catch{}return n.size?[...n.values()]:await Co(e).catch(()=>[])}const Y=new class{async collectAllRawSealedRecordEntries(){let e=await xo();if(!e)return[];let t=e.transaction(go,`readonly`),n=await Co(t.objectStore(go));return await bo(t).catch(()=>void 0),n}async collectRawSealedRecordEntriesByThresholdSessionId(e){let t=await xo();if(!t)return[];let n=t.transaction(go,`readonly`),r=await wo(n.objectStore(go),e);return await bo(n).catch(()=>void 0),r}async replaceSealedRecord(e){let t=await xo();if(!t)return;let n=t.transaction(go,`readwrite`),r=n.objectStore(go);for(let t of e.staleStoreKeys)r.delete(t);r.put(e.row),await bo(n)}async replaceSealedRecordAndDeleteRestoreLease(e){let t=await xo();if(!t)return!1;let n=t.transaction([go,_o],`readwrite`),r=n.objectStore(go);for(let t of e.staleStoreKeys)r.delete(t);return r.put(e.row),n.objectStore(_o).delete(e.restoreLeaseKey),await bo(n),!0}async deleteSealedRecords(e){if(!e.length)return;let t=await xo();if(!t)return;let n=t.transaction(go,`readwrite`),r=n.objectStore(go);for(let t of e)r.delete(t);await bo(n).catch(()=>void 0)}async deleteRestoreLease(e){let t=await xo();if(!t)return;let n=t.transaction(_o,`readwrite`);n.objectStore(_o).delete(e),await bo(n).catch(()=>void 0)}async deleteRestoreLeaseIf(e){let t=await xo();if(!t)return;let n=t.transaction(_o,`readwrite`),r=n.objectStore(_o),i=await yo(r.get(e.leaseKey));e.shouldDelete(i)&&r.delete(e.leaseKey),await bo(n).catch(()=>void 0)}async withRestoreLeaseTransaction(e,t){let n=await xo();if(!n)return null;try{let r=n.transaction([go,_o],`readwrite`),i=r.objectStore(go),a=r.objectStore(_o),o=await wo(i,e),s=!1,c=await t({entries:o,getRawRestoreLease:async e=>await yo(a.get(e)),putRestoreLease:e=>a.put(e),abort:()=>{s=!0}});return s?(r.abort(),c):(await bo(r),c)}catch{return null}}};function To(e){throw Error(`Unhandled durable sealed-session identity: ${String(e)}`)}function Eo(e){return{kind:`delete_durable_sealed_session`,durableRecord:e.durableRecord,deleteReason:e.deleteReason,preserveResolvedIdentity:e.preserveResolvedIdentity}}function Do(e){switch(e.curve){case`ed25519`:return{authMethod:e.authMethod,curve:`ed25519`};case`ecdsa`:return{authMethod:e.authMethod,curve:`ecdsa`,chainTarget:e.chainTarget};default:return To(e)}}function Oo(e){return[`ecdsa-material-v2`,e.walletId,e.authMethod,Re(e.chainTarget),e.materialActivation.activationId,e.materialActivation.capability,e.materialActivation.materialOwner,e.materialActivation.keyBinding,e.materialActivation.lifecycleBinding,e.materialActivation.signingWorker].map(e=>encodeURIComponent(String(e))).join(`:`)}const ko=`ecdsa_inactive_sealed_material_v1`,Ao=`sealed_record`;function jo(e){let t=C(e)??{},n=o(t.ed25519),r=o(t.ecdsa);return{...n?{ed25519:n}:{},...r?{ecdsa:r}:{}}}function Mo(e){return jo((C(e)??{}).thresholdSessionIds)}function No(e){let t=C(e);if(!t)return!1;let n=[`signing`,`Grant`,`Id`].join(``),r=[`signing`,`grant`,`id`].join(`_`);return Object.prototype.hasOwnProperty.call(t,n)||Object.prototype.hasOwnProperty.call(t,r)}function Po(e){let t=String(e||``).trim();return t===`ed25519`||t===`ecdsa`?t:void 0}function Fo(e){let t=C(e);return t&&Ao in t?t[Ao]:e}function Io(e){let t=e.ecdsaRestore?.chainTarget,n=o(e.thresholdSessionIds.ecdsa),r=o(e.thresholdSessionIds.ed25519);return{store_key:e.storeKey,wallet_id:e.walletId,auth_method:e.authMethod,curve:e.curve,signing_root_id:o(`signingRootId`in e?e.signingRootId:void 0),signing_root_version:o(`signingRootVersion`in e?e.signingRootVersion:void 0),ed25519_threshold_session_id:r,ecdsa_threshold_session_id:n,threshold_session_id:n||r,key_handle:o(e.ecdsaRestore?.keyHandle),chain_target_key:t?Re(t):void 0,expires_at_ms:e.expiresAtMs,updated_at:e.updatedAtMs,[Ao]:e}}function Lo(e){return{store_key:e.storeKey,wallet_id:e.walletId,auth_method:e.authMethod,curve:e.curve,key_handle:e.ecdsaRestore.keyHandle,chain_target_key:Re(e.ecdsaRestore.chainTarget),updated_at:e.updatedAtMs,[Ao]:e}}function Ro(e){return Io(e)}function zo(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:void 0}function Bo(e){return e.curve?e.curve:e.thresholdSessionIds.ecdsa?`ecdsa`:e.thresholdSessionIds.ed25519?`ed25519`:null}function Vo(e){try{return st(e)}catch{return null}}function Ho(e){switch(e){case`login`:case`registration`:case`manual-bootstrap`:case`email_otp`:return e;default:return null}}function Uo(e){try{let t=re(I(e)),n=o(t.signingRootId),r=o(t.signingRootVersion);return n&&r?{signingRootId:n,signingRootVersion:r}:null}catch{return null}}function Wo(e){let t=C(e);if(!t)return;let n=null;try{n=Fe(C(t.chainTarget)??{})}catch{n=null}let r=Ho(t.source),i=bt(t.authority),a=o(t.rpId),s=t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?t.runtimePolicyScope:void 0,c=Uo(s),l=o(t.signingRootId),u=o(t.signingRootVersion);if(l&&c?.signingRootId&&l!==c.signingRootId||u&&c?.signingRootVersion&&u!==c.signingRootVersion)return;let d=l||c?.signingRootId||``,f=u||c?.signingRootVersion||``,p=o(t.credentialIdB64u),m=null;try{m=dn(t.roleLocalMaterialRef)}catch{m=null}let h=lt(t.emailOtpAuthority),g=t.provider===`google`||t.provider===`email`?t.provider:null,_=o(t.providerSubjectId),v=o(t.emailHashHex),y=o(t.keyHandle),b=o(t.ecdsaThresholdKeyId),x=zo(t.ethereumAddress),S=o(t.relayerKeyId),w=o(t.thresholdEcdsaPublicKeyB64u),T=Vo(t.routerAbEcdsaDerivationNormalSigning),E=null;try{E=Ct(t.publicCapability)}catch{E=null}let D=Qo(t.participantIds);if(!n||!r||!d||!f||!y||!x||!S||!T||!E||!D.length)return;let O=p&&a&&m&&i&&r!==`email_otp`?{source:r,authority:i,roleLocalMaterialRef:m,rpId:a,credentialIdB64u:p}:_&&g&&v&&m&&i&&h&&r===`email_otp`?{source:r,provider:g,providerSubjectId:_,emailHashHex:v,authority:i,emailOtpAuthority:h,roleLocalMaterialRef:m}:null;if(!O)return;let k=o(t.clientVerifyingShareB64u);return{chainTarget:n,signingRootId:d,signingRootVersion:f,...O,keyHandle:y,...b?{ecdsaThresholdKeyId:b}:{},ethereumAddress:x,relayerKeyId:S,...k?{clientVerifyingShareB64u:k}:{},...w?{thresholdEcdsaPublicKeyB64u:w}:{},participantIds:D,routerAbEcdsaDerivationNormalSigning:T,publicCapability:E,...s?{runtimePolicyScope:s}:{}}}function Go(e){let t=C(e);if(!t)return;let r=o(t.nearAccountId),i=o(t.nearEd25519SigningKeyId),a=o(t.rpId),s=o(t.credentialIdB64u),c=o(t.providerSubjectId),u=t.provider===`google`||t.provider===`email`?t.provider:null,d=o(t.emailHashHex),f=o(t.authSubjectId),p=o(t.relayerKeyId),m=Qo(t.participantIds),h=n(t.signerSlot),g=se(t.routerAbNormalSigning),_=l(t.materialActivation),v=s&&!c&&_.ok?{credentialIdB64u:s,materialActivation:_.value}:u&&c&&d&&!s&&_.ok?{provider:u,providerSubjectId:c,emailHashHex:d,materialActivation:_.value}:null;if(!(!r||!i||!a||!p||!m.length||h==null||h<=0||!g||!v||f))return{nearAccountId:r,nearEd25519SigningKeyId:i,rpId:a,...v,relayerKeyId:p,participantIds:m,...t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?{runtimePolicyScope:t.runtimePolicyScope}:{},signerSlot:h,routerAbNormalSigning:g}}function Ko(e){let t=e.restore.materialActivation;return[`ed25519-material-v2`,e.walletId,e.authMethod,`ed25519`,t.activationId,t.capability,t.materialOwner,t.keyBinding,t.lifecycleBinding,t.signingWorker].map(Jo).join(`:`)}function qo(e){let t=e.restore.roleLocalMaterialRef;return[`inactive-material`,e.walletId,e.authMethod,`ecdsa`,Re(e.restore.chainTarget),t.materialActivation.activationId].map(Jo).join(`:`)}function Jo(e){return encodeURIComponent(String(e||``).trim())}function Yo(e){let t=String(e||``).trim();return t===`passkey`||t===`email_otp`?t:void 0}function Xo(e){let t=C(e);return!!(o(t?.subjectId)||o(t?.userId))}function Zo(e){let t=C(e);return!!(o(t?.signingRootId)||o(t?.signingRootVersion))}function Qo(e){return Array.isArray(e)?e.map(e=>Math.floor(Number(e))).filter(e=>Number.isFinite(e)&&e>0):[]}function $o(e){return{authMethod:o(e?.authMethod)||null,curve:o(e?.curve)||null,storeKey:o(e?.storeKey)||null,walletId:o(e?.walletId)||null,thresholdSessionIds:Mo(e),hasEcdsaRestore:!!C(e?.ecdsaRestore),hasEd25519Restore:!!C(e?.ed25519Restore),issuedAtMs:n(e?.issuedAtMs),expiresAtMs:n(e?.expiresAtMs),remainingUses:n(e?.remainingUses),updatedAtMs:n(e?.updatedAtMs)}}function X(e,t,n){return{kind:e,storeKey:o(t?.storeKey)||null,walletId:o(t?.walletId)||null,reason:n,safeSummary:$o(t)}}function es(e){return{v:2,alg:ue,storageScope:le,authMethod:e,secretKind:de}}function ts(e){e=Fo(e);let t=C(e);if(!t)return X(`malformed`,null,`invalid_payload`);if(No(t))return X(`delete_required`,t,`invalid_identity`);if(t.recordKind===`ecdsa_reauth_anchor_v1`)return X(`delete_required`,t,`invalid_header`);if(t.recordKind===ko){let e=is(t);return e?{kind:`ecdsa_inactive_material`,record:e}:X(`malformed`,t,`invalid_identity`)}if(Number(t.v)===1)return X(`delete_required`,t,`invalid_header`);if(Number(t.v)!==2||String(t.alg||``).trim()!==`shamir3pass-v2`||String(t.storageScope||``).trim()!==`iframe_origin_indexeddb`||String(t.secretKind||``).trim()!==`signing_session_secret32`)return X(`malformed`,t,`invalid_header`);let r=String(t.authMethod||``).trim(),i=Mo(t),a=o(t.sealedSecretB64u),s=Po(t.curve),c=o(t.subjectId),l=o(t.userId),u=o(t.walletId),d=o(t.signingRootId),f=o(t.signingRootVersion),p=f||(d?`default`:null),m=o(t.relayerUrl),h=o(t.keyVersion),g=o(t.groupId),_=n(t.issuedAtMs),v=n(t.expiresAtMs),y=n(t.remainingUses),b=n(t.updatedAtMs);if(!a||!h||g!==`rfc2409-group2`||r!==`passkey`&&r!==`email_otp`||!i.ed25519&&!i.ecdsa||!u)return X(`malformed`,t,`invalid_identity`);let x=Bo({curve:s,thresholdSessionIds:i});if(!x||_==null||_<=0||v==null||v<=0||y==null||y<0||b==null||b<=0)return X(`malformed`,t,`invalid_identity`);let S=C(t.ecdsaRestore),w=C(t.ed25519Restore),T=Wo(t.ecdsaRestore),E=Go(t.ed25519Restore);if(x===`ecdsa`){if(!i.ecdsa)return X(`malformed`,t,`invalid_identity`);if(c||l||d||f)return X(`delete_required`,t,`invalid_identity`);if(!S||!m)return X(`rebuild_required`,t,`missing_restore_metadata`);if(!Qo(S.participantIds).length)return X(`delete_required`,t,`missing_participant_ids`);if(!T)return X(`rebuild_required`,t,`missing_restore_metadata`);let e=Oo({walletId:u,authMethod:r,chainTarget:T.chainTarget,materialActivation:T.roleLocalMaterialRef.materialActivation}),n=o(t.storeKey);return n&&n!==e?X(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...es(r),storeKey:e,thresholdSessionIds:{...i.ed25519?{ed25519:i.ed25519}:{},ecdsa:i.ecdsa},sealedSecretB64u:a,curve:`ecdsa`,walletId:u,relayerUrl:m,keyVersion:h,groupId:oe,ecdsaRestore:T,...E?{ed25519Restore:E}:{},issuedAtMs:_,expiresAtMs:v,remainingUses:y,updatedAtMs:b}}}if(!i.ed25519)return X(`malformed`,t,`invalid_identity`);if(c||l)return X(`delete_required`,t,`invalid_identity`);if(!w||!m)return X(`rebuild_required`,t,`missing_restore_metadata`);if(!Qo(w.participantIds).length)return X(`delete_required`,t,`missing_participant_ids`);if(!E)return X(`rebuild_required`,t,`missing_restore_metadata`);let D=Ko({walletId:u,authMethod:r,restore:E}),O=o(t.storeKey);return O&&O!==D?X(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...es(r),storeKey:D,thresholdSessionIds:{ed25519:i.ed25519,...i.ecdsa?{ecdsa:i.ecdsa}:{}},sealedSecretB64u:a,curve:`ed25519`,walletId:u,...d?{signingRootId:d}:{},...p?{signingRootVersion:p}:{},relayerUrl:m,keyVersion:h,groupId:oe,...T?{ecdsaRestore:T}:{},ed25519Restore:E,issuedAtMs:_,expiresAtMs:v,remainingUses:y,updatedAtMs:b}}}function ns(e){let t=ts(Fo(e));return t.kind===`current`?t.record:null}function rs(e){let t=C(e);if(!t||t.clientVerifyingShareB64u!=null)return null;let n,r,i,a;try{n=Fe(t.chainTarget&&typeof t.chainTarget==`object`?t.chainTarget:{}),r=I(t.runtimePolicyScope);let e=st(t.routerAbEcdsaDerivationNormalSigning);if(!e)return null;i=e,a=Ct(t.publicCapability)}catch{return null}let s=o(t.signingRootId),c=o(t.signingRootVersion),l=null;try{l=dn(t.roleLocalMaterialRef)}catch{l=null}let u=bt(t.authority),d=lt(t.emailOtpAuthority),f=o(t.keyHandle),p=o(t.ecdsaThresholdKeyId),m=o(t.ethereumAddress),h=o(t.relayerKeyId),g=o(t.thresholdEcdsaPublicKeyB64u),_=Qo(t.participantIds);if(!s||!c||!f||!p||!m||!h||!g||!_.length)return null;let v={chainTarget:n,signingRootId:s,signingRootVersion:c,keyHandle:f,ecdsaThresholdKeyId:p,ethereumAddress:m,relayerKeyId:h,thresholdEcdsaPublicKeyB64u:g,participantIds:_,runtimePolicyScope:r,routerAbEcdsaDerivationNormalSigning:i,publicCapability:a};switch(t.source){case`email_otp`:{let e=t.provider===`google`||t.provider===`email`?t.provider:null,n=o(t.providerSubjectId),r=o(t.emailHashHex);return!e||!n||!r||!l||!u||!d||t.rpId!=null||t.credentialIdB64u!=null?null:{...v,source:`email_otp`,provider:e,providerSubjectId:n,emailHashHex:r,authority:u,emailOtpAuthority:d,roleLocalMaterialRef:l}}case`login`:case`registration`:case`manual-bootstrap`:{let e=o(t.rpId),n=o(t.credentialIdB64u);return!e||!n||!l||!u||t.providerSubjectId!=null||t.emailHashHex!=null?null:{...v,source:t.source,authority:u,roleLocalMaterialRef:l,rpId:e,credentialIdB64u:n}}default:return null}}function is(e){let t=C(Fo(e));if(!t||t.recordKind!==ko||No(t)||t.thresholdSessionIds!=null||t.ed25519Restore!=null||t.curve!==`ecdsa`)return null;let r=Yo(t.authMethod),i=o(t.walletId),a=o(t.relayerUrl),s=rs(t.ecdsaRestore),c=o(t.sealedSecretB64u),l=o(t.keyVersion),u=o(t.groupId),d=n(t.updatedAtMs),f=t.authorizationRetirementReason;if(!r||!i||!a||!s||t.alg!==`shamir3pass-v2`||t.storageScope!==`iframe_origin_indexeddb`||t.secretKind!==`signing_session_secret32`||!c||!l||u!==`rfc2409-group2`||t.issuedAtMs!=null||t.expiresAtMs!=null||t.remainingUses!=null||d==null||d<=0||f!==`expired`&&f!==`exhausted`)return null;let p=qo({walletId:i,authMethod:r,restore:s});return o(t.storeKey)===p?as({storeKey:p,walletId:i,relayerUrl:a,sealedSecretB64u:c,keyVersion:l,updatedAtMs:d,authorizationRetirementReason:f,authMethod:r,ecdsaRestore:s}):null}function as(e){let{authMethod:t,ecdsaRestore:n}=e,r={recordKind:ko,storeKey:e.storeKey,curve:`ecdsa`,walletId:e.walletId,relayerUrl:e.relayerUrl,alg:ue,storageScope:le,secretKind:de,sealedSecretB64u:e.sealedSecretB64u,keyVersion:e.keyVersion,groupId:oe,updatedAtMs:e.updatedAtMs,authorizationRetirementReason:e.authorizationRetirementReason};return t===`email_otp`&&n.source===`email_otp`||t===`passkey`&&n.source!==`email_otp`?{...r,authMethod:t,ecdsaRestore:n}:null}function os(e){if(e.classification.kind===`ecdsa_inactive_material`||e.classification.kind===`rebuild_required`)return;let t=e.classification.kind===`malformed`?`malformed`:`rejected`,n={operation:e.operation,outcome:t,classificationKind:e.classification.kind,...e.classification};console.warn(`[SigningSessionSealedStore] rejected sealed record`,n)}function ss(e){let t=String(e.thresholdSessionId||``).trim(),r=Po(e.curve),i=e.authMethod===`passkey`||e.authMethod===`email_otp`?e.authMethod:void 0;if(!r||!i)return null;let a=cs({thresholdSessionId:t,curve:r,thresholdSessionIds:e.thresholdSessionIds}),s=o(e.walletId),c=o(e.sealedSecretB64u),l=n(e.expiresAtMs),u=n(e.remainingUses),d=n(e.issuedAtMs),f=n(e.updatedAtMs),p=o(e.keyVersion);if(!t||!c||!p||e.groupId!==`rfc2409-group2`||!a.ed25519&&!a.ecdsa||d==null||d<=0||l==null||l<=0||u==null||u<0||f==null||f<=0)return null;let m=Wo(e.ecdsaRestore),h=Go(e.ed25519Restore);if(Xo(e)||r===`ecdsa`&&(!m?.chainTarget||!s||Zo(e)))return null;let g,_;e.curve===`ed25519`&&(g=o(e.signingRootId),_=o(e.signingRootVersion));let v=ts({...es(i),thresholdSessionIds:a,sealedSecretB64u:c,curve:r,...s?{walletId:s}:{},...g?{signingRootId:g}:{},..._?{signingRootVersion:_}:{},...o(e.relayerUrl)?{relayerUrl:o(e.relayerUrl)}:{},keyVersion:p,groupId:oe,...m?{ecdsaRestore:m}:{},...h?{ed25519Restore:h}:{},issuedAtMs:d,expiresAtMs:l,remainingUses:u,updatedAtMs:f});return v.kind===`current`?v.record:(os({operation:`build current sealed session record`,classification:v}),null)}function cs(e){let t=jo(e.thresholdSessionIds),n=String(e.thresholdSessionId||``).trim();return n&&(e.curve===`ed25519`&&t.ed25519===n||e.curve===`ecdsa`&&t.ecdsa===n)?t:{}}function ls(e,t){let n=o(t),r=o(e.ecdsaThresholdKeyId),i=o(e.thresholdEcdsaPublicKeyB64u);if(!n||!r||!i)return null;let a;try{a=I(e.runtimePolicyScope)}catch{return null}let s={chainTarget:e.chainTarget,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,keyHandle:e.keyHandle,ecdsaThresholdKeyId:r,ethereumAddress:e.ethereumAddress,relayerKeyId:e.relayerKeyId,thresholdEcdsaPublicKeyB64u:i,participantIds:[...e.participantIds],runtimePolicyScope:a,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,publicCapability:e.publicCapability};switch(e.source){case`email_otp`:return{...s,source:`email_otp`,provider:e.provider,providerSubjectId:e.providerSubjectId,emailHashHex:e.emailHashHex,authority:e.authority,emailOtpAuthority:e.emailOtpAuthority,roleLocalMaterialRef:dn(e.roleLocalMaterialRef)};case`login`:case`registration`:case`manual-bootstrap`:return{...s,source:e.source,authority:e.authority,roleLocalMaterialRef:dn(e.roleLocalMaterialRef),rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}}}function us(e){let t=e.record,n=ls(t.ecdsaRestore,t.relayerUrl);return n?as({storeKey:qo({walletId:t.walletId,authMethod:t.authMethod,restore:n}),walletId:t.walletId,relayerUrl:t.relayerUrl,sealedSecretB64u:t.sealedSecretB64u,keyVersion:t.keyVersion,updatedAtMs:e.updatedAtMs,authorizationRetirementReason:e.retirement,authMethod:t.authMethod,ecdsaRestore:n}):null}function ds(e){let t=us(e);if(!t)throw Error(`[SigningSessionSealedStore] inactive ECDSA material requires exact public restore facts`);return t}const fs=15e3;function ps(e){return ie(e,32,`sealed signing session restore IDs`)}function ms(e){return{lease_key:e.leaseKey,owner_id:e.ownerId,attempt_id:e.attemptId,started_at_ms:e.startedAtMs,expires_at_ms:e.expiresAtMs,lease:e}}function hs(e){let t=new Set,n=o(e.walletId);return n&&t.add(n),t}function gs(e,t){let n=hs(e);if(!n.size)return!1;for(let e of hs(t))if(n.has(e))return!0;return!1}function _s(e,t){if(!gs(e,t)||e.authMethod!==t.authMethod||e.curve!==t.curve)return!1;if(e.curve===`ed25519`&&t.curve===`ed25519`)return p(e.ed25519Restore.materialActivation,t.ed25519Restore.materialActivation);if(e.curve===`ecdsa`){let n=o(e.ecdsaRestore?.keyHandle),r=o(t.ecdsaRestore?.keyHandle);if(!n||!r||n!==r)return!1;let i=e.ecdsaRestore?.chainTarget,a=t.ecdsaRestore?.chainTarget;if(!i||!a||!Be(i,a))return!1}return!0}function vs(e){return x({storeKey:e.storeKey,walletId:e.walletId,authMethod:e.authMethod,signingRootId:e.signingRootId??null,signingRootVersion:e.signingRootVersion??null,restore:e.ed25519Restore})}function ys(e,t){if(typeof e.primaryKey!=`string`||!e.primaryKey.trim())throw Error(`[SigningSessionSealedStore] exact Ed25519 record key is invalid`);return{primaryKey:e.primaryKey,record:t}}function bs(e,t){return e.record.updatedAtMs===t.record.updatedAtMs?e.primaryKey===e.record.storeKey?e:t.primaryKey===t.record.storeKey?t:e.primaryKey.localeCompare(t.primaryKey)<=0?e:t:e.record.updatedAtMs>t.record.updatedAtMs?e:t}async function xs(e,t={writeCanonical:!1}){let n=e[0];if(!n)return null;let r=vs(n.record);for(let t of e.slice(1))if(vs(t.record)!==r)throw Error(`[SigningSessionSealedStore] exact Ed25519 material has conflicting public identity facts`);let i=e.reduce(bs),a=i.record.storeKey,o=[...new Set(e.map(e=>e.primaryKey))].filter(e=>e!==a);return(t.writeCanonical||o.length>0||i.primaryKey!==a)&&await Y.replaceSealedRecord({row:Ro(i.record),staleStoreKeys:o}),i.record}async function Ss(e){let t=Fo(e.value),n=ts(t);if(n.kind!==`current`)return n;let r=C(t);return No(C(e.value))||No(r)?X(`delete_required`,r,`invalid_identity`):n}function Cs(e){return Mo(Fo(e))}function ws(e,t,n,r){os({operation:e,classification:t}),(t.kind===`delete_required`||t.kind===`malformed`)&&r.push(n)}function Ts(e){let t=C(e);if(!t)return null;if(C(t.lease))return Ts(t.lease);if(Number(t.v)!==1||No(t))return null;let r=o(t.leaseKey),i=o(t.ownerId),a=o(t.attemptId),s=n(t.startedAtMs),c=n(t.expiresAtMs);return!r||!i||!a||s==null||s<=0||c==null||c<=s?null:{v:1,leaseKey:r,ownerId:i,attemptId:a,startedAtMs:s,expiresAtMs:c}}function Es(e){return{v:1,leaseKey:e.leaseKey,ownerId:e.ownerId,attemptId:ps(`restore-attempt`),startedAtMs:e.nowMs,expiresAtMs:e.nowMs+e.ttlMs}}function Ds(e,t,n){return!(e.authMethod!==n.authMethod||e.thresholdSessionIds[n.curve]!==t||n.curve===`ecdsa`&&(!e.ecdsaRestore?.chainTarget||!Be(e.ecdsaRestore.chainTarget,n.chainTarget)))}function Os(e,t){if(e?.authMethod&&e.curve===`ed25519`||e?.authMethod&&e.curve===`ecdsa`&&e.chainTarget)return e;throw console.warn(`[SigningSessionSealedStore] rejected ambiguous sealed record access`,{operation:t}),Error(`[SigningSessionSealedStore] ${t} requires an explicit authMethod, curve, and ECDSA chain target`)}async function ks(e){let t=await Y.collectRawSealedRecordEntriesByThresholdSessionId(e);return t.length?t:(await Y.collectAllRawSealedRecordEntries()).filter(t=>{let n=Cs(t.value);return n.ed25519===e||n.ecdsa===e})}async function As(e,t,n){let r=await ks(e),i=null,a=[],o=[];for(let s of r){let r=await Ss(s);if(r.kind===`current`){Ds(r.record,e,t)&&(i=r.record,r.record.curve===`ed25519`&&a.push(ys(s,r.record)));continue}ws(n,r,s.primaryKey,o)}return await Y.deleteSealedRecords(o),a.length>0?await xs(a):i}async function js(e,t){try{let n=await ks(e),r=[];for(let i of n){let n=await Ss(i),a=n.kind===`current`?n.record:null;a?.storeKey&&Ds(a,e,t)&&r.push(i.primaryKey)}await Y.deleteSealedRecords(r)}catch{}}async function Ms(e){if(!hs(e).size||!e.authMethod)return[];try{let t=await Y.collectAllRawSealedRecordEntries(),n=[];for(let r of t){let t=await Ss(r),i=t.kind===`current`?t.record:null;i&&i.storeKey!==e.storeKey&&_s(i,e)&&n.push(i)}return n}catch{return[]}}function Ns(e){if(e.curve!==`ecdsa`)return null;let t=ls(e.ecdsaRestore,e.relayerUrl);return t?qo({walletId:e.walletId,authMethod:e.authMethod,restore:t}):null}async function Ps(e,t){let n=Os(t,`read`),r=String(e||``).trim();return r?await As(r,n,`read`):null}function Fs(e,t){return e.curve===`ed25519`&&e.authMethod===t.authMethod&&p(e.ed25519Restore.materialActivation,t.materialActivation)}async function Is(e){let t=await Y.collectAllRawSealedRecordEntries(),n=[],r=[];for(let i of t){let t=await Ss(i);if(t.kind===`current`){let n=t.record;Fs(n,e)&&r.push(ys(i,n));continue}ws(`read exact Ed25519 material`,t,i.primaryKey,n)}return await Y.deleteSealedRecords(n),await xs(r)}async function Ls(e){let t=o(e.walletId);if(!t)return[];let n=Os(e.filter,`list exact account records`),r=e.filter.curve===`ecdsa`?e.filter.chainTarget:void 0,i=await Y.collectAllRawSealedRecordEntries(),a=[];try{let e=[],o=new Set,s=new Map;for(let c of i){let i=await Ss(c);if(i.kind!==`current`){ws(`list exact account records`,i,c.primaryKey,a);continue}let l=i.record;if(l.walletId===t&&l.authMethod===n.authMethod&&l.thresholdSessionIds[n.curve]&&!(r&&(!l.ecdsaRestore?.chainTarget||!Be(l.ecdsaRestore.chainTarget,r)))){if(l.curve===`ed25519`){let e=s.get(l.storeKey)??[];e.push(ys(c,l)),s.set(l.storeKey,e);continue}o.has(l.storeKey)||(o.add(l.storeKey),e.push(l))}}for(let t of s.values()){let n=await xs(t);n&&e.push(n)}return await Y.deleteSealedRecords(a),e}finally{await Y.deleteSealedRecords(a)}}async function Rs(e){let t=o(e.walletId);if(!t)return[];if(e.filter.curve!==`ecdsa`)return console.warn(`[SigningSessionSealedStore] rejected non-ECDSA wallet-scoped list`,{operation:`list wallet ecdsa records`}),[];let n=await Y.collectAllRawSealedRecordEntries(),r=[];try{let i=[],a=new Set;for(let o of n){let n=await Ss(o);if(n.kind===`ecdsa_inactive_material`){let r=n.record;if(r.walletId!==t||e.filter.authMethod&&r.authMethod!==e.filter.authMethod||a.has(r.storeKey))continue;a.add(r.storeKey),i.push(r);continue}if(n.kind!==`current`){ws(`list wallet ecdsa records`,n,o.primaryKey,r);continue}let s=n.record;s.walletId===t&&(e.filter.authMethod&&s.authMethod!==e.filter.authMethod||s.thresholdSessionIds.ecdsa&&s.ecdsaRestore?.chainTarget&&(a.has(s.storeKey)||(a.add(s.storeKey),i.push(s))))}return await Y.deleteSealedRecords(r),i}finally{await Y.deleteSealedRecords(r)}}async function zs(e){let t=ts(e);if(t.kind!==`current`){os({operation:`write exact sealed session`,classification:t});return}let n=t.record;if(n.curve===`ed25519`){let e=[{primaryKey:n.storeKey,record:n}],t=await Y.collectAllRawSealedRecordEntries();for(let r of t){let t=await Ss(r);t.kind===`current`&&t.record.curve===`ed25519`&&t.record.storeKey===n.storeKey&&e.push(ys(r,t.record))}await xs(e,{writeCanonical:!0});return}let r=await Ms(n),i=Ns(n);await Y.replaceSealedRecord({row:Ro(n),staleStoreKeys:[...r.map(e=>e.storeKey),...i?[i]:[]]})}function Bs(e,t,n){return Vs({current:e,inactive:ds({record:e,retirement:t,updatedAtMs:n})})}async function Vs(e){await Y.replaceSealedRecordAndDeleteRestoreLease({row:Lo(e.inactive),staleStoreKeys:[e.current.storeKey],restoreLeaseKey:e.current.storeKey})}async function Hs(e){let t=Os(e.filter,`update policy`),n=String(e.thresholdSessionId||``).trim();if(!n)return;let r=await Ps(n,t);r&&await Ws(r,e)}async function Us(e){let t=await Is(e.locator);t&&await Ws(t,e)}async function Ws(e,t){let r=n(t.expiresAtMs??e.expiresAtMs),i=n(t.remainingUses??e.remainingUses),a=n(t.updatedAtMs);if(r==null||r<=0||i==null||i<0||a==null||a<=0)return;let o={...e,expiresAtMs:r,remainingUses:i,updatedAtMs:a};if(o.curve===`ecdsa`){let e=r<=Date.now()?`expired`:i===0?`exhausted`:null;if(e){await Bs(o,e,a);return}}await zs(o)}async function Gs(e,t,n){let r=Os(t,`delete`),i=String(e||``).trim();if(!i)return;let a=await As(i,r,`delete`);await js(i,r),a&&n.deleteResolvedIdentity&&await Y.deleteRestoreLease(a.storeKey)}async function Ks(e,t){let n=await Y.collectAllRawSealedRecordEntries(),r=[],i=[];for(let a of n){let n=await Ss(a);if(n.kind!==`current`){os({operation:`delete exact Ed25519 material`,classification:n});continue}let o=n.record;Fs(o,e)&&(r.push(a.primaryKey),t.deleteResolvedIdentity&&i.push(o.storeKey))}if(await Y.deleteSealedRecords(r),t.deleteResolvedIdentity)for(let e of i)await Y.deleteRestoreLease(e)}async function qs(e){let t=e.preserveResolvedIdentity?{deleteResolvedIdentity:!1}:{deleteResolvedIdentity:!0,resolvedIdentityDeleteReason:`durable_record_deleted`};if(e.durableRecord.curve===`ed25519`){await Ks({kind:`ed25519_durable_material`,authMethod:e.durableRecord.authMethod,materialActivation:e.durableRecord.materialActivation},t);return}let n=Do(e.durableRecord),r=await Js(e.durableRecord.thresholdSessionId,n);if(e.preserveResolvedIdentity&&e.durableRecord.curve===`ecdsa`&&r?.curve===`ecdsa`&&(e.deleteReason===`expired`||e.deleteReason===`exhausted`)){await Bs(r,e.deleteReason,Date.now());return}await Gs(e.durableRecord.thresholdSessionId,n,t)}async function Js(e,t){try{return await Ps(e,t)}catch{return null}}async function Ys(e){let t=Os(e,`acquire restore lease`),r=String(e.thresholdSessionId||``).trim();if(!r)return null;let i=n(e.nowMs??Date.now())??Date.now(),a=Math.max(1,n(e.ttlMs??fs)??fs),s=o(e.ownerId)||ps(`restore-owner`);return await As(r,t,`acquire restore lease`)?await Y.withRestoreLeaseTransaction(r,async e=>{let n=[];for(let t of e.entries){let e=ns(t.value);e?.storeKey&&!n.some(t=>t.storeKey===e.storeKey)&&n.push(e)}let o=n.find(e=>Ds(e,r,t))||null;if(!o)return e.abort(),null;let c=Ts(await e.getRawRestoreLease(o.storeKey));if(c&&c.expiresAtMs>i&&c.ownerId!==s)return e.abort(),null;let l=Es({leaseKey:o.storeKey,ownerId:s,nowMs:i,ttlMs:a});return e.putRestoreLease(ms(l)),{...l,thresholdSessionId:r}}):null}async function Xs(e){!e?.leaseKey||!e.ownerId||!e.attemptId||await Y.deleteRestoreLeaseIf({leaseKey:e.leaseKey,shouldDelete:t=>{let n=Ts(t);return n?.ownerId===e.ownerId&&n.attemptId===e.attemptId}})}function Zs(e){return String(e??``).trim()||null}function Qs(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function $s(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:null}function ec(e){let t=ne(e);return t?.length===2?[t[0],t[1]]:null}function tc(e){let t=e.ed25519Restore;switch(e.authMethod){case Ge.passkey:{let e=Zs(t.credentialIdB64u);return e?{kind:`passkey`,rpId:pt(t.rpId),credentialIdB64u:e}:null}case Ge.emailOtp:{if(!(`provider`in t))return null;let e=Zs(t.providerSubjectId),n=Zs(t.emailHashHex);return!e||!n?null:{kind:`email_otp`,provider:t.provider,providerSubjectId:e,emailHashHex:n}}}}function nc(e){switch(e.kind){case`passkey`:return{kind:Ge.passkey,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u};case`email_otp`:return{kind:Ge.emailOtp,providerSubjectId:e.providerSubjectId}}}function rc(e){let t=e.ed25519Restore,n=Zs(e.thresholdSessionIds.ed25519),r=Zs(e.relayerUrl),i=Zs(t.relayerKeyId),a=Qs(e.expiresAtMs),o=$s(e.remainingUses),s=Dn(t.signerSlot),c=ec(t.participantIds),l=ae(t.runtimePolicyScope),u=l?re(l):null,d=Zs(u?.signingRootVersion),f=se(t.routerAbNormalSigning),p=tc(e);if(!n||!r||!i||!a||o===null||!s||!c||!l||!u||!d||!f||f.signingWorkerId!==i||!p||e.signingRootId!==u.signingRootId||e.signingRootVersion!==d)return null;try{return{kind:`exact_ed25519_sealed_session_runtime`,sealedRecord:e,walletId:Ie(e.walletId),nearAccountId:z(t.nearAccountId),nearEd25519SigningKeyId:Yt(t.nearEd25519SigningKeyId),signerSlot:s,factor:p,auth:nc(p),thresholdSessionId:Fn.thresholdEd25519Session(n),remainingUses:o,expiresAtMs:a,relayerUrl:r,relayerKeyId:i,participantIds:c,runtimePolicyScope:l,signingRootId:u.signingRootId,signingRootVersion:d,routerAbNormalSigning:f}}catch{return null}}async function ic(e){let t;switch(e.runtime.factor.kind){case`passkey`:t=xt({walletId:e.runtime.walletId,factor:{kind:`passkey`,credentialIdB64u:e.runtime.factor.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.runtime.factor.rpId},bindingId:e.walletAuthMethodId});break;case`email_otp`:t=lt({walletId:e.runtime.walletId,factor:{kind:`email_otp`,provider:e.runtime.factor.provider,providerUserId:e.runtime.factor.providerSubjectId},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:e.runtime.factor.emailHashHex},bindingId:e.walletAuthMethodId});break;default:return ac(e.runtime.factor)}if(!t)throw Error(`[SigningEngine][near] sealed Ed25519 authority is invalid`);return await ct({authority:t})}function ac(e){throw Error(`Unsupported Ed25519 factor: ${String(e)}`)}async function oc(e){let{authorization:t,runtime:n}=e;if(t.session.walletId!==n.walletId||t.session.authMethodId!==t.selectedAuthMethod.walletAuthMethodId||t.session.quotaId!==t.status.quotaId||t.operationCredential.walletSessionId!==t.status.walletSessionId||t.operationCredential.token.trim().length===0||t.status.remainingUses<=0||!ar({session:t.session,materialActivation:n.sealedRecord.ed25519Restore.materialActivation}))return!1;if(n.factor.kind===`passkey`){if(t.selectedAuthMethod.kind!==`passkey`||String(t.selectedAuthMethod.rpId)!==String(n.factor.rpId)||t.selectedAuthMethod.credentialIdB64u!==n.factor.credentialIdB64u||t.selectedFactorAuthority.factor.kind!==`passkey`||t.selectedFactorAuthority.factor.credentialIdB64u!==n.factor.credentialIdB64u||t.selectedFactorAuthority.verifier.kind!==`webauthn`||String(t.selectedFactorAuthority.verifier.rpId)!==String(n.factor.rpId))return!1}else if(t.selectedAuthMethod.kind!==`email_otp`||t.selectedAuthMethod.emailHashHex!==n.factor.emailHashHex||t.selectedFactorAuthority.factor.kind!==`email_otp`||t.selectedFactorAuthority.factor.provider!==n.factor.provider||t.selectedFactorAuthority.factor.providerUserId!==n.factor.providerSubjectId||t.selectedFactorAuthority.verifier.kind!==`email_otp_wallet_auth_method`||t.selectedFactorAuthority.verifier.emailHashHex!==n.factor.emailHashHex)return!1;try{let e=await ic({runtime:n,walletAuthMethodId:t.selectedAuthMethod.walletAuthMethodId}),r=await ct({authority:t.selectedFactorAuthority});return e.walletId===t.selectedAuthority.walletId&&e.walletAuthMethodId===t.selectedAuthMethod.walletAuthMethodId&&e.walletId===r.walletId&&e.walletAuthMethodId===r.walletAuthMethodId&&e.authorityDigest===r.authorityDigest}catch{return!1}}function sc(e,t){switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u;case`email_otp`:return t.kind===`email_otp`&&e.providerSubjectId===t.providerSubjectId}}function cc(e){let t=e.laneIdentity.signer,n=e.record.ed25519Restore;return e.record.walletId===t.account.wallet.walletId&&n.nearAccountId===t.account.nearAccountId&&n.nearEd25519SigningKeyId===t.nearEd25519SigningKeyId&&n.signerSlot===t.signerSlot&&e.record.thresholdSessionIds.ed25519===e.laneIdentity.thresholdSessionId}function lc(e,t){return sc(e.auth,t.auth)}async function uc(e,t){let n=(await t.listExactSealedSessionsForWallet({walletId:e.walletId,filter:{authMethod:e.laneIdentity.auth.kind,curve:`ed25519`}})).filter(t=>t.curve===`ed25519`&&cc({record:t,laneIdentity:e.laneIdentity}));if(n.length===0)return{kind:`missing`};if(n.length>1)return{kind:`conflict`};let r=rc(n[0]);return!r||!lc(r,e.laneIdentity)?{kind:`corrupt`}:{kind:`resolved`,runtime:r}}async function dc(e){return await uc(e,{listExactSealedSessionsForWallet:Ls})}async function fc(e,t){return mc(await pc(e,t))}async function pc(e,t){let n=await Promise.all([t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Ge.passkey,curve:`ed25519`}}),t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Ge.emailOtp,curve:`ed25519`}})]),r=[];for(let e of n)for(let t of e)t.curve===`ed25519`&&r.push(t);return r}function mc(e){if(e.length===0)return{kind:`missing`};if(e.length>1)return{kind:`conflict`};let t=rc(e[0]);return t?{kind:`resolved`,runtime:t}:{kind:`corrupt`}}async function hc(e){return await fc(e,{listExactSealedSessionsForWallet:Ls})}async function gc(e,t){let n=await pc(e.walletId,t),r=[];for(let t of n)t.ed25519Restore.nearAccountId===e.nearAccountId&&t.ed25519Restore.nearEd25519SigningKeyId===e.nearEd25519SigningKeyId&&r.push(t);return mc(r)}async function _c(e){return await gc(e,{listExactSealedSessionsForWallet:Ls})}function vc(e,t){let n=String(e).trim();if(!n)throw Error(`${t} is required for Ed25519 Wallet Session state`);return n}function yc(e,t){if(!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be positive for Ed25519 Wallet Session state`);return e}function bc(e){let t=Fn.thresholdEd25519Session(vc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=vc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=vc(e.relayerUrl,`relayerUrl`),i=vc(e.providerSubjectId,`providerSubjectId`),a=yc(e.signerSlot,`signerSlot`),o=yc(e.signingWalletSession.remainingUses,`remainingUses`);return{walletSessionAuth:{kind:`wallet_session_opaque`,home:e.signingWalletSession.auth.credential.home,walletSessionToken:n},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,signingLane:dr({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:a,auth:{kind:`email_otp`,providerSubjectId:i},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,retention:`session`,sessionOrigin:`login`}),remainingUses:o,signingRootId:e.signingWalletSession.signingRootId,signingRootVersion:e.signingWalletSession.signingRootVersion,routerAbNormalSigning:e.signingWalletSession.routerAbNormalSigning,runtimePolicyScope:e.signingWalletSession.runtimePolicyScope,relayerUrl:r,signingWalletSession:e.signingWalletSession,authority:e.authority}}function xc(e){let t=Fn.thresholdEd25519Session(vc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=vc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=vc(e.relayerUrl,`relayerUrl`),i=vc(e.credentialIdB64u,`credentialIdB64u`),a=yc(e.signerSlot,`signerSlot`);return{walletSessionAuth:{kind:`wallet_session_opaque`,home:e.signingWalletSession.auth.credential.home,walletSessionToken:n},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,signingLane:dr({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:a,auth:{kind:`passkey`,rpId:e.rpId,credentialIdB64u:i},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,storageSource:`login`}),remainingUses:e.signingWalletSession.remainingUses,signingRootId:e.signingWalletSession.signingRootId,signingRootVersion:e.signingWalletSession.signingRootVersion,routerAbNormalSigning:e.signingWalletSession.routerAbNormalSigning,runtimePolicyScope:e.signingWalletSession.runtimePolicyScope,relayerUrl:r,signingWalletSession:e.signingWalletSession,authority:e.authority}}async function Sc(e){let t=e.authorization.operationCredential.token,n=e.authorization.session.authorizationId,r=await ic({runtime:e.runtime,walletAuthMethodId:e.authorization.selectedAuthMethod.walletAuthMethodId}),i=await ct({authority:e.authorization.selectedFactorAuthority}),a=Math.min(e.runtime.expiresAtMs,e.authorization.status.expiresAtMs);if(!t||!n||e.authorization.session.walletId!==e.runtime.walletId||e.authorization.selectedAuthMethod.kind!==e.runtime.auth.kind||r.walletId!==e.runtime.walletId||r.walletAuthMethodId!==e.authorization.selectedAuthMethod.walletAuthMethodId||r.walletId!==i.walletId||r.walletAuthMethodId!==i.walletAuthMethodId||String(r.authorityDigest)!==String(i.authorityDigest)||e.authorization.operationCredential.walletSessionId!==e.authorization.status.walletSessionId||a<=e.nowMs)throw Error(`Ed25519 Wallet Session authorization does not match sealed material`);let o=ho({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,walletSessionId:e.authorization.operationCredential.walletSessionId,authorizationId:n,quotaId:e.authorization.session.quotaId,thresholdSessionId:e.runtime.thresholdSessionId,remainingUses:Math.min(e.runtime.remainingUses,e.authorization.status.remainingUses),expiresAtMs:a,runtimePolicyScope:e.runtime.runtimePolicyScope,signingRootId:e.runtime.signingRootId,signingRootVersion:e.runtime.signingRootVersion,routerAbNormalSigning:e.runtime.routerAbNormalSigning,walletSessionToken:t,home:e.authorization.operationCredential.home,nowMs:e.nowMs});if(!o.ok)throw Error(`Ed25519 Wallet Session runtime is invalid: ${o.reason}`);if(e.runtime.factor.kind===`passkey`&&e.runtime.auth.kind===`passkey`)return xc({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,signerSlot:e.runtime.signerSlot,rpId:e.runtime.factor.rpId,credentialIdB64u:e.runtime.factor.credentialIdB64u,relayerUrl:e.runtime.relayerUrl,authority:r,signingWalletSession:o.value});if(e.runtime.factor.kind===`email_otp`&&e.runtime.auth.kind===`email_otp`)return bc({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,providerSubjectId:e.runtime.auth.providerSubjectId,signerSlot:e.runtime.signerSlot,relayerUrl:e.runtime.relayerUrl,authority:r,signingWalletSession:o.value});throw Error(`Ed25519 sealed runtime factor and auth binding disagree`)}function Cc(e){return{thresholdSessionId:e.thresholdSessionId,signer:e.signingLane.identity.signer,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,routerAbNormalSigning:e.routerAbNormalSigning,runtimePolicyScope:e.runtimePolicyScope,relayerUrl:e.relayerUrl}}function wc(e){return e.authorization.capabilitySubjects.some(t=>t.kind===`sign`&&t.keyFamily===`ed25519`&&p(t.materialActivation,e.materialActivation))}function Tc(e){let t=e.state,n=e.authorization,r=t.signingLane.identity.signer.account.wallet.walletId,i=e.operationCredential.token,a=t.signingLane.identity.signer,o=Math.min(t.signingWalletSession.expiresAtMs,n.expiresAtMs);if(!i||!wc({authorization:n,materialActivation:e.materialActivation})||n.walletId!==r||n.authMethodId!==t.authority.walletAuthMethodId||e.operationCredential.walletSessionId!==t.walletSessionId||n.authorizationId!==t.signingWalletSession.authorizationId||o<=e.nowMs||!Number.isSafeInteger(o))return null;let s=ho({walletId:String(a.account.wallet.walletId),nearAccountId:String(a.account.nearAccountId),nearEd25519SigningKeyId:String(a.nearEd25519SigningKeyId),walletSessionId:String(t.walletSessionId),authorizationId:String(t.signingWalletSession.authorizationId),quotaId:String(t.quotaId),thresholdSessionId:String(t.thresholdSessionId),remainingUses:t.remainingUses,expiresAtMs:o,runtimePolicyScope:t.runtimePolicyScope,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,routerAbNormalSigning:t.routerAbNormalSigning,walletSessionToken:i,home:e.operationCredential.home,nowMs:e.nowMs});if(!s.ok)return null;switch(t.signingLane.auth.kind){case`passkey`:return{...xc({walletId:a.account.wallet.walletId,nearAccountId:a.account.nearAccountId,nearEd25519SigningKeyId:a.nearEd25519SigningKeyId,signerSlot:a.signerSlot,rpId:t.signingLane.auth.rpId,credentialIdB64u:t.signingLane.auth.credentialIdB64u,relayerUrl:t.relayerUrl,authority:t.authority,signingWalletSession:s.value}),walletSessionAuthorization:n,walletSessionOperationCredential:e.operationCredential};case`email_otp`:return{...bc({walletId:a.account.wallet.walletId,nearAccountId:a.account.nearAccountId,nearEd25519SigningKeyId:a.nearEd25519SigningKeyId,providerSubjectId:t.signingLane.auth.providerSubjectId,signerSlot:a.signerSlot,relayerUrl:t.relayerUrl,authority:t.authority,signingWalletSession:s.value}),walletSessionAuthorization:n,walletSessionOperationCredential:e.operationCredential};default:return Ec(t.signingLane.auth)}}function Ec(e){throw Error(`Unknown Ed25519 signing lane auth: ${String(e)}`)}async function Dc(e){let t=e.state.signingLane.identity.signer.account.wallet.walletId,n=await co({ports:e.ports,input:{walletId:t,authMethod:Pn(e.state.signingLane.auth),walletSessionId:e.state.walletSessionId,quotaId:e.state.quotaId,requiredSigningSubject:so(e.state.signingLane.identity),expiry:{kind:`unexpired`,nowMs:e.nowMs}}});return n.kind!==`resolved`||n.resolved.authMethod.walletAuthMethodId!==e.state.authority.walletAuthMethodId?null:Tc({state:e.state,authorization:n.resolved.session,operationCredential:n.resolved.operationCredential,materialActivation:n.resolved.materialActivation,nowMs:e.nowMs})}function Oc(e){return ut(x({operation:`wallet_add_signer_activate_v2`,addSignerCeremonyId:e.addSignerCeremonyId,activationCorrelationId:e.activationCorrelationId,publicFacts:e.publicFacts}))}async function kc(e){return L(await A(String(Oc(e))))}function Ac(e){let t;try{t=$t(e,`custody envelope`)}catch(e){return{ok:!1,reason:e instanceof Error?e.message:`custody envelope is invalid`}}let n=t.lifecycle.state;return n===`active`?t.binding.kind===`wallet_custody_seed_v1`?{ok:!0,custodyJson:JSON.stringify({envelopeBinding:{walletId:t.walletId,envelopeId:t.envelopeId,factor:t.factor,envelopeRevision:t.envelopeRevision,binding:t.binding,ownership:on(t.ownership)},nonceB64u:t.nonceB64u,sealedCustodySecretB64u:t.sealedCustodySecretB64u,aadHashB64u:t.aadHashB64u,ciphertextDigestB64u:t.ciphertextDigestB64u})}:{ok:!1,reason:`generic custody wire rejects non-seed envelopes`}:{ok:!1,reason:`custody envelope is ${n}`}}function jc(e){let t={};return br()&&(t[`X-Seams-Benchmark-Diagnostics`]=`registration-flow`),e&&(t[vn]=e.value),Object.keys(t).length>0?t:void 0}function Mc(e){let t=R(e);if(t.length!==20)throw Error(`ECDSA activation returned an invalid address`);let n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return`0x${n}`}var Nc=class extends Error{code=`wallet_unlock_required`;next=`unlock_exact_method`;projection;constructor(e){super(`Registration response was already committed; exact-method unlock is required`),this.name=`RegistrationExactMethodUnlockRequiredError`,this.projection=e}};function Pc(e){switch(e.kind){case`issued`:return e.session;case`already_committed`:throw new Nc(e.session);default:return q(e)}}function Fc(e){let t=e[0];if(t)for(let n of e.slice(1)){let e=Lc(t,n);if(e)throw Error(`ECDSA registration returned partitioned EVM-family wallet key material: ${e}`)}}function Ic(e){for(let t of e.walletKeys)if(!vt(t.publicCapability,e.session.publicCapability))throw Error(`ECDSA registration wallet key public capability does not match client-verified activation`)}function Lc(e,t){return e.keyScope!==`evm-family`||t.keyScope!==`evm-family`?`keyScope`:e.walletId===t.walletId?e.evmFamilySigningKeySlotId===t.evmFamilySigningKeySlotId?e.keyHandle===t.keyHandle?e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId?e.signingRootId===t.signingRootId?e.signingRootVersion===t.signingRootVersion?e.thresholdEcdsaPublicKeyB64u===t.thresholdEcdsaPublicKeyB64u?e.thresholdOwnerAddress.trim().toLowerCase()===t.thresholdOwnerAddress.trim().toLowerCase()?e.relayerKeyId===t.relayerKeyId?e.relayerVerifyingShareB64u===t.relayerVerifyingShareB64u?e.participantIds.join(`,`)===t.participantIds.join(`,`)?null:`participantIds`:`relayerVerifyingShareB64u`:`relayerKeyId`:`thresholdOwnerAddress`:`thresholdEcdsaPublicKeyB64u`:`signingRootVersion`:`signingRootId`:`ecdsaThresholdKeyId`:`keyHandle`:`evmFamilySigningKeySlotId`:`walletId`}function Rc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||Re(r)!==Re(i))return!1}return!0}async function zc(e){try{await e.context.signingEngine.closeRouterAbEcdsaRegistrationCeremony({kind:`close_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:e.ceremonyId})}catch{return}}function Bc(e){let t=e.prepare;return{formatVersion:t.formatVersion,walletId:t.walletId,evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,keyScope:t.keyScope,relayerKeyId:t.relayerKeyId,registrationPreparationId:t.registrationPreparationId,requestId:t.requestId,thresholdSessionId:t.thresholdSessionId,ttlMs:t.ttlMs,remainingUses:t.remainingUses,participantIds:[...t.participantIds],runtimePolicyScope:t.runtimePolicyScope,derivationClientSharePublicKey33B64u:e.verified.derivationClientSharePublicKey33B64u,clientShareRetryCounter:e.verified.clientShareRetryCounter,contextBinding32B64u:e.verified.contextBinding32B64u}}async function Vc(e){return{canonicalRequest:Oc(e),requestDigest:xe(await kc(e))}}async function Hc(e){try{return await Jn(e)}catch{return await Jn(e)}}async function Uc(e){return e.registrationTiming?await e.registrationTiming.measure(e.bucket,e.operation):await e.operation()}async function Wc(e){let[t,...n]=e.started.chainTargets;if(!t)throw Error(`Strict ECDSA ceremony requires at least one EVM-family target`);let r=e.addSignerCeremonyId,i=be(r);try{let a=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientCreateMs`,operation:e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony.bind(e.context.signingEngine,{kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:r,registration:e.started.strictRegistration})}),o=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Kn.bind(void 0,{relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:r,ecdsa:{kind:`router_ab_ecdsa_registration_v1`,strictRegistration:a.registrationRequest,requestDigestB64u:a.registrationRequestDigestB64u}})}),s=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientProofVerifyMs`,operation:e.context.signingEngine.verifyRouterAbEcdsaRegistrationClientProofs.bind(e.context.signingEngine,{kind:`verify_router_ab_ecdsa_registration_client_proofs_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:o.ecdsa.strictResult.response.bundles}})}),c=Ac(e.custodyEnvelope);if(!c.ok)throw Error(c.reason);let l={response:null,journalId:null},u=await e.context.signingEngine.joinWalletCustodyEvmFamilyKeySet({walletId:e.walletId,custodyJson:c.custodyJson,factorSecret:e.factorSecret,evmFamilySigningKeySlotId:e.started.prepare.evmFamilySigningKeySlotId,applicationBindingDigestB64u:s.applicationBindingDigestB64u,runRelayerRound:async a=>{let o=ht({registrationRequestDigestB64u:s.registrationRequestDigestB64u,proofTranscriptDigestB64u:s.proofTranscriptDigestB64u,contextBinding32B64u:a.contextBinding32B64u,derivationClientSharePublicKey33B64u:a.clientSharePublicKey33B64u,clientShareRetryCounter:a.clientShareRetryCounter,participantId:1}),c=await Vc({addSignerCeremonyId:r,activationCorrelationId:i,publicFacts:o}),u={bytes:Array.from(R(String(c.requestDigest)))},d=await e.context.signingEngine.persistInitialCanonicalEcdsaActivation({kind:`persist_initial_canonical_ecdsa_activation_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientActivation:o,planInput:{authority:e.authority,targetMemberships:[t,...n],evmFamilySigningKeySlotId:Gt(e.started.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:ln(e.started.prepare.ecdsaThresholdKeyId),signingRootId:ot(e.started.prepare.signingRootId),signingRootVersion:mt(e.started.prepare.signingRootVersion),runtimePolicyScope:e.started.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:sn(a.clientSharePublicKey33B64u),participantIds:[Dt(e.started.prepare.participantIds[0]),Dt(e.started.prepare.participantIds[1])],relayerKeyId:cn(e.started.prepare.relayerKeyId),bindingDigest:pn(a.contextBinding32B64u),journalId:i,requestDigest:c.requestDigest,canonicalRequest:c.canonicalRequest,createdAt:ye(new Date().toISOString())}});if(!d.ok)throw Error(`Canonical ECDSA activation persistence failed (${d.code}): ${d.message}`);l.journalId=d.journalId,l.response=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Hc.bind(void 0,{relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:r,activationCorrelationId:i,publicFacts:o,expectedActivationRequestDigest:u})});let f=l.response.ecdsa.activation.ecdsa_activation.public_identity;return JSON.stringify({relayerKeyId:e.started.prepare.relayerKeyId,relayerPublicKey33B64u:f.server_public_key33_b64u,groupPublicKey33B64u:f.threshold_public_key33_b64u,ethereumAddress:Mc(f.ethereum_address20_b64u),relayerShareRetryCounter:f.server_share_retry_counter})}});if(!l.response||!l.journalId)throw Error(`Add-signer ECDSA custody join did not activate`);let d=l.response,f=l.journalId,p=u.commitPayload.clientRootPublicKey33B64u;if(!p)throw Error(`Add-signer ECDSA custody join returned no client root public key`);let m=Bc({prepare:e.started.prepare,verified:u.clientBootstrap}),h=Gn({clientBootstrap:m,serverBootstrap:d.ecdsa.bootstrap,activationEpoch:d.ecdsa.activation.ecdsa_activation.activation_epoch});return{chainTargets:[t,...n],clientBootstrap:m,bootstrap:h,activatedThresholdSessionId:d.ecdsa.bootstrap.thresholdSessionId,journalId:f,activationReceipt:d.ecdsa.activation,custodyKeySet:{kind:`evm_family_ecdsa_v1`,keyManifestDigestB64u:u.commitPayload.keyManifestDigestB64u,clientRootPublicKey33B64u:p},custodyLocalMaterial:u.localMaterial}}catch(t){throw await zc({context:e.context,ceremonyId:r}),t}}async function Gc(e){let t=await e.context.signingEngine.finalizeRouterAbEcdsaRegistrationActivation({kind:`finalize_router_ab_ecdsa_registration_activation_v1`,bootstrapOwner:`wallet_custody`,journalId:e.pending.journalId,activationReceipt:e.pending.activationReceipt,routerAbEcdsaDerivationNormalSigning:e.pending.bootstrap.routerAbEcdsaDerivationNormalSigning,readyStateBlobB64u:e.pending.custodyLocalMaterial.readyStateBlobB64u,walletCustodyPublicFacts:e.pending.custodyLocalMaterial.publicFacts});return{chainTargets:e.pending.chainTargets,authority:t.authority,clientBootstrap:e.pending.clientBootstrap,bootstrap:e.pending.bootstrap,activatedThresholdSessionId:e.pending.activatedThresholdSessionId,roleLocalMaterial:t.roleLocalMaterial,materialActivation:t.materialActivation,clientPublicFacts:t.publicFacts,publicCapability:t.publicCapability}}function Kc(e){switch(e.tokens.kind){case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:return e.tokens.ecdsa;case`near_ed25519`:throw Error(`Registration-established session is missing ECDSA authorization`);default:return q(e.tokens)}}function qc(e){let[t]=e.walletKeys;if(!t)throw Error(`ECDSA registration did not return wallet key material`);let n=Kc(e.session.registrationEstablishedSession);if(String(e.session.registrationEstablishedSession.walletId)!==t.walletId||n.thresholdSessionId!==e.session.activatedThresholdSessionId||n.keyHandle!==t.keyHandle||!Jc(n.runtimePolicyScope,e.session.clientBootstrap.runtimePolicyScope)||!yt(n.routerAbEcdsaDerivationNormalSigning,e.session.bootstrap.routerAbEcdsaDerivationNormalSigning))throw Error(`Registration-established ECDSA session changed the signer identity`);for(let r of e.walletKeys)if(r.walletId!==t.walletId||r.keyHandle!==n.keyHandle||r.ecdsaThresholdKeyId!==t.ecdsaThresholdKeyId)throw Error(`ECDSA registration material changed the established session identity`)}function Jc(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}async function Yc(e,t){e.kind===`passkey`&&await Promise.allSettled([Promise.resolve().then(t),ua.initializeBundled()])}function Xc(e){return ft({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:String(e.credential.rawId||e.credential.id||``).trim()})}async function Zc(e){if(!e.material)throw Error(`Email OTP registration ${e.operation} is missing enrollment material`);return await e.material}function Qc(e){let t=e.admissionRequest,n=s(t.scope.threshold_session_id);if(!n.ok)throw Error(`Ed25519 registration threshold-session identity is invalid`);let r=t.participant_ids,i=I(e.finalized.runtimePolicyScope);if(t.application_binding.wallet_id!==e.walletId||t.application_binding.near_ed25519_signing_key_id!==e.finalized.nearEd25519SigningKeyId||t.application_binding.key_creation_signer_slot!==e.finalized.signerSlot||r[0]!==e.finalized.participantIds[0]||r[1]!==e.finalized.participantIds[1]||!Jc(i,e.expectedRuntimePolicyScope)||t.application_binding.signing_root_id!==`${i.projectId}:${i.envId}`||t.scope.root_share_epoch!==i.signingRootVersion||t.scope.signing_worker_id!==e.finalized.routerAbNormalSigning.signingWorkerId||e.finalized.relayerKeyId!==e.finalized.routerAbNormalSigning.signingWorkerId)throw Error(`Ed25519 registration material changed the admitted signer identity`);return{identity:{walletId:String(e.walletId),nearAccountId:e.finalized.nearAccountId,nearEd25519SigningKeyId:e.finalized.nearEd25519SigningKeyId,thresholdSessionId:n.value,signerSlot:e.finalized.signerSlot,signingRootId:t.application_binding.signing_root_id,signingRootVersion:t.scope.root_share_epoch,signingWorkerId:t.scope.signing_worker_id},stableServerScope:{relayerKeyId:e.finalized.relayerKeyId,participantIds:e.finalized.participantIds,runtimePolicyScope:i,routerAbNormalSigning:e.finalized.routerAbNormalSigning}}}function $c(e){switch(e.tokens.kind){case`near_ed25519`:case`near_ed25519_and_evm_family_ecdsa`:return e.tokens.ed25519;case`evm_family_ecdsa`:throw Error(`Registration-established session is missing Ed25519 authorization`);default:return q(e.tokens)}}async function el(e){let t=$c(e.registrationEstablishedSession);if(t.nearAccountId!==String(e.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.nearEd25519SigningKeyId)||t.thresholdSessionId!==String(e.thresholdSessionId)||!Jc(t.runtimePolicyScope,e.runtimePolicyScope))throw Error(`Registration-established Email OTP Ed25519 session changed signer identity`);let n=re(t.runtimePolicyScope),r=n.signingRootVersion;if(!r)throw Error(`Registration-established Ed25519 session is missing a signing-root version`);let i=ho({walletId:String(e.walletId),nearAccountId:String(e.nearAccountId),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId),walletSessionId:String(e.registrationEstablishedSession.walletSessionId),authorizationId:String(e.registrationEstablishedSession.authorizationId),quotaId:String(e.registrationEstablishedSession.quotaId),thresholdSessionId:t.thresholdSessionId,remainingUses:e.registrationEstablishedSession.remainingUses,expiresAtMs:e.registrationEstablishedSession.expiresAtMs,runtimePolicyScope:t.runtimePolicyScope,signingRootId:n.signingRootId,signingRootVersion:r,routerAbNormalSigning:t.routerAbNormalSigning,walletSessionToken:e.registrationEstablishedSession.operationCredential.token,home:e.registrationEstablishedSession.operationCredential.home,nowMs:Date.now()});if(!i.ok)throw Error(`Registration-established Email OTP Ed25519 session is unusable (${i.reason})`);let a=await ct({authority:e.emailOtpAuthContext.authority});return bc({walletId:e.walletId,nearAccountId:z(e.nearAccountId),nearEd25519SigningKeyId:Jt(e.nearEd25519SigningKeyId),providerSubjectId:sr(e.emailOtpAuthContext),signerSlot:e.signerSlot,relayerUrl:e.relayerUrl,authority:a,signingWalletSession:i.value})}function tl(e){if(e.authMethod.kind!==`passkey`)throw Error(`Ed25519 Yao registration requires a passkey registration intent`);return{version:e.version,walletId:e.walletId,authMethod:e.authMethod,signerSelection:e.signerSelection,foundingWalletAuthMethodId:e.foundingWalletAuthMethodId,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},nonceB64u:e.nonceB64u}}function nl(e){if(e.finalized.authMethod.kind!==`passkey`||e.finalized.rpId!==e.expectedRpId)throw Error(`Ed25519 Yao finalize returned a different passkey authority`);if(e.finalized.walletId!==e.expectedWalletId)throw Error(`Ed25519 Yao finalize returned a different wallet`);if(e.finalized.ed25519.publicKey!==e.clientPublicKey||e.finalized.ed25519.nearEd25519SigningKeyId!==e.finalized.resolvedAccount.nearEd25519SigningKeyId||e.finalized.ed25519.nearAccountId!==e.finalized.resolvedAccount.nearAccountId)throw Error(`Ed25519 Yao finalize returned mismatched signer identity`);return{rpId:e.finalized.rpId,credentialIdB64u:e.finalized.authMethod.credentialIdB64u}}function rl(e){if(e.finalized.authMethod.kind!==`email_otp`||e.finalized.authMethod.registrationAuthorityId!==e.expectedRegistrationAuthorityId)throw Error(`Ed25519 Yao finalize returned a different Email OTP authority`);if(e.finalized.walletId!==e.expectedWalletId)throw Error(`Ed25519 Yao finalize returned a different wallet`);if(e.finalized.ed25519.publicKey!==e.clientPublicKey||e.finalized.ed25519.nearEd25519SigningKeyId!==e.finalized.resolvedAccount.nearEd25519SigningKeyId||e.finalized.ed25519.nearAccountId!==e.finalized.resolvedAccount.nearAccountId)throw Error(`Ed25519 Yao finalize returned mismatched signer identity`)}async function il(e,t){let n=await new ra(t).send({kind:`admit`,path:At,body:e.admissionRequest});if(!n.ok)throw Error(n.message);let r=Rt(n.value);if(!r.ok)throw Error(r.message);return r.value}function al(e){let t=$c(e.session);return{thresholdSessionId:String(t.thresholdSessionId),prfFirstB64u:e.prfFirstB64u,expiresAtMs:e.session.expiresAtMs,remainingUses:e.session.remainingUses,diagnostics:{recordDuration:Ta.bind(void 0,e.ceremonyId)},...e.preparedServerSeal?{preparedServerSeal:e.preparedServerSeal}:{},transport:{curve:`ed25519`,authMethod:`passkey`,walletId:e.walletId,relayerUrl:e.relayerUrl,walletSessionToken:e.session.operationCredential.token,ed25519Restore:_a({rpId:e.restore.rpId,nearAccountId:e.restore.nearAccountId,nearEd25519SigningKeyId:e.restore.nearEd25519SigningKeyId,relayerKeyId:e.restore.relayerKeyId,participantIds:e.restore.participantIds,runtimePolicyScope:t.runtimePolicyScope,signerSlot:e.restore.signerSlot,routerAbNormalSigning:t.routerAbNormalSigning,credentialIdB64u:e.restore.credentialIdB64u,materialActivation:e.restore.materialActivation})}}}function ol(e){if(e.operation!==`registration_activate`||e.signerPlanKind!==`evm_family_ecdsa`)return!1;let t=e.localMaterial.keyFamilies;return t.length===1&&t[0]===`ecdsa_secp256k1`}function sl(e){if(e.operation!==`registration_activate`||e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)return!1;let t=e.localMaterial.keyFamilies;return t.length===1&&t[0]===`ecdsa_secp256k1`}function cl(e){let t=e.registrationEstablishedSession.session.tokens;if(t.kind===`evm_family_ecdsa`||t.kind===`near_ed25519_and_evm_family_ecdsa`)return t;throw Error(`pending ECDSA activation returned no ECDSA projection`)}function ll(e,t,n){let r=t.registrationEstablishedSession.session,i=cl(t);return t.walletId===e.walletId&&t.custodyKeyManifestDigestB64u===e.localMaterial.custodyCommit.keyManifestDigestB64u&&t.walletCustody?.status===`committed`&&r.walletId===e.walletId&&r.walletSession.walletId===e.walletId&&r.walletSession.authMethodId===e.walletAuthMethodId&&r.tokens.kind===`evm_family_ecdsa`&&i.ecdsa.keyHandle===n.keyHandle&&i.ecdsa.thresholdSessionId===t.ecdsa.bootstrap.thresholdSessionId&&r.expiresAtMs===t.ecdsa.bootstrap.expiresAtMs&&r.remainingUses===t.ecdsa.bootstrap.remainingUses}function ul(e,t,n){let r=e.ecdsa_activation.public_identity;return kt({registrationRequestDigestB64u:t.publicCapability.registration_request_digest_b64u,proofTranscriptDigestB64u:L(Uint8Array.from(e.transcript_digest.bytes)),contextBinding32B64u:r.context_binding_b64u,derivationClientSharePublicKey33B64u:r.derivation_client_share_public_key33_b64u,clientShareRetryCounter:r.client_share_retry_counter,participantId:1},n)}function dl(e,t){return e.derivationClientSharePublicKey33B64u===t.derivationClientSharePublicKey33B64u&&e.relayerPublicKey33B64u===t.relayerVerifyingShareB64u&&e.groupPublicKey33B64u===t.thresholdEcdsaPublicKeyB64u&&e.ethereumAddress===t.thresholdOwnerAddress.toLowerCase()}function fl(e,t){return e.server_public_key33_b64u===t.relayerVerifyingShareB64u&&e.threshold_public_key33_b64u===t.thresholdEcdsaPublicKeyB64u&&gl(e.ethereum_address20_b64u)===t.thresholdOwnerAddress&&e.server_share_retry_counter===t.relayerShareRetryCounter}function pl(e,t){return e.walletId===t.walletId&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.evmFamilySigningKeySlotId===t.evmFamilySigningKeySlotId&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion&&e.thresholdEcdsaPublicKeyB64u===t.thresholdEcdsaPublicKeyB64u&&e.ethereumAddress.toLowerCase()===t.thresholdOwnerAddress.toLowerCase()&&e.relayerKeyId===t.relayerKeyId&&e.relayerVerifyingShareB64u===t.relayerVerifyingShareB64u&&e.clientShareRetryCounter===t.clientShareRetryCounter&&e.relayerShareRetryCounter===t.relayerShareRetryCounter}function ml(e,t){let n={relayerUrl:e,registrationCeremonyId:t.registrationCeremonyId,signedSetup:t.signedSetup,idempotencyKey:t.idempotencyKey,walletCustodyCommit:t.localMaterial.custodyCommit,...t.auth.kind===`email_otp`?{emailOtpEnrollment:t.auth.enrollment}:{}},r={activationCorrelationId:t.localMaterial.ecdsa.activationJournalId,activationRequestDigestB64u:t.localMaterial.ecdsa.activationRequestDigestB64u,clientActivation:t.localMaterial.ecdsa.clientActivation};return{...n,signerPlanKind:t.signerPlanKind,ecdsa:r}}function hl(e){let t=e.ecdsa.walletKeys[0];if(!t)throw Error(`pending ECDSA activation returned no wallet keys`);return Fc(e.ecdsa.walletKeys),[t,...e.ecdsa.walletKeys.slice(1)]}function gl(e){let t=R(e);if(t.length!==20)throw Error(`pending ECDSA activation returned an invalid address`);let n=`0x`;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n}function _l(e,t,n){if(!ll(e,t,n))throw Error(`pending ECDSA activation projection mismatch`);Cn(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function vl(e){return e.ok===!0&&e.kind===`evm_family_ecdsa`&&e.registrationEstablishedSession.kind===`already_committed`}async function yl(e,t){if(e.auth.kind===`passkey`){if(t.authMethod.kind!==`passkey`||t.rpId!==e.auth.rpId||t.authMethod.credentialIdB64u!==e.auth.credentialIdB64u)throw Error(`pending ECDSA activation returned a different Passkey method`);return}if(t.authMethod.kind!==`email_otp`||t.authMethod.registrationAuthorityId!==e.auth.registrationAuthorityId)throw Error(`pending ECDSA activation returned a different Email OTP method`);let n=lt(t.authority),r=await S(e.auth.email);if(!n||n.factor.providerUserId!==e.auth.providerSubject||n.verifier.emailHashHex.toLowerCase()!==r.toLowerCase())throw Error(`pending ECDSA activation returned a different Email OTP identity`)}function bl(e,t,n){let r=t.ecdsa.activation,i=r.ecdsa_activation,a=i.public_identity,o=e.localMaterial.ecdsa.clientActivation;if(r.activation_correlation_id!==e.localMaterial.ecdsa.activationJournalId||L(Uint8Array.from(r.activation_request_digest.bytes))!==e.localMaterial.ecdsa.activationRequestDigestB64u||!ul(r,n,o)||!dl(t.ecdsa.bootstrap.publicIdentity,n)||i.context.application_binding_digest_b64u!==t.ecdsa.bootstrap.applicationBindingDigestB64u||!fl(a,n))throw Error(`pending ECDSA activation facts mismatch`);if(!pl(t.ecdsa.bootstrap,n))throw Error(`pending ECDSA bootstrap changed committed key identity`)}function xl(e){let t=cl(e).ecdsa,n=e.ecdsa.activation.ecdsa_activation;if(!p(t.materialActivation,gt(n.material_activation))||!yt(t.routerAbEcdsaDerivationNormalSigning,e.ecdsa.bootstrap.routerAbEcdsaDerivationNormalSigning))throw Error(`pending ECDSA activation facts do not match the committed projection`)}async function Sl(e){let t=e.response;if(!vl(t))throw Error(t.ok?`pending ECDSA activation replay did not return a committed projection`:`pending ECDSA activation replay failed`);let n=hl(t)[0];if(_l(e.pending,t,n),await yl(e.pending,t),bl(e.pending,t,n),xl(t),e.pending.signerPlanKind===`evm_family_ecdsa`){if(t.nearProvisioning!==void 0)throw Error(`ECDSA-only registration unexpectedly has deferred NEAR provisioning`)}else if(t.nearProvisioning?.status!==`near_pending`)throw Error(`mixed registration did not retain deferred NEAR provisioning`);return t}function Cl(e){return String(Ln(e)||``).trim()}function wl(e,t){let n=Cl(e);if(!n)throw Error(`${t} requires PRF.first output from the passkey credential`);return n}function Tl(e){return String(e?.rawId||e?.id||``).trim()}async function El(e){let t=new xn,n=gt(e.activationReceipt.ecdsa_activation.material_activation),r=await t.lookupByMaterialActivation({walletId:e.authority.walletId,authority:e.authority,materialActivation:n});if(r.kind===`missing`){let t=await Sn(e);return{roleLocalMaterialRef:t.roleLocalMaterialRef,publication:[t]}}if(r.kind!==`active`)throw Error(`Pending ECDSA registration continuity is ${r.kind}`);let i=r.manifest,a=i.durableMaterial;if(!Et(i.activation.serverActivation.serverActivationReceipt.protocolReceipt,e.activationReceipt)||!vt(a.roleLocalPublicFacts.publicCapability,e.publicCapability)||!Nn(i.signer.scope,fn({targetMemberships:e.chainTargets}))||a.roleLocalBinding.keyHandle!==e.keyHandle||a.roleLocalBinding.ecdsaThresholdKeyId!==e.ecdsaThresholdKeyId||a.roleLocalBinding.relayerKeyId!==e.relayerKeyId||a.bindingDigest!==e.publicFacts.contextBinding32B64u||i.signer.signingRootId!==e.signingRootId||i.signer.signingRootVersion!==e.signingRootVersion||!Mn(a.runtimePolicyScope,e.runtimePolicyScope))throw Error(`Pending ECDSA registration conflicts with its restored activation`);return{roleLocalMaterialRef:{kind:`ecdsa_role_local_persisted_material_ref_v1`,durableMaterialRef:a.durableMaterialRef,bindingDigest:a.bindingDigest,materialActivation:n},publication:[]}}function Dl(e){let t=e[0];if(!t)throw Error(`ECDSA registration finalization returned no wallet keys`);return[t,...e.slice(1)]}function Ol(e){let t=e[0];if(!t)throw Error(`ECDSA registration activation returned no chain targets`);return[t.chainTarget,...e.slice(1).map(e=>e.chainTarget)]}async function kl(e){let t=Dl(e.walletKeys);if(e.pending.auth.kind===`passkey`){if(e.response.authMethod.kind!==`passkey`||!e.response.authMethod.credentialPublicKeyB64u)throw Error(`ECDSA registration publication has no exact Passkey credential`);return await nt({kind:`passkey`,walletId:e.pending.walletId,rpId:e.pending.auth.rpId,credentialIdB64u:e.pending.auth.credentialIdB64u,credentialPublicKeyB64u:e.response.authMethod.credentialPublicKeyB64u,transports:e.pending.auth.transports,walletKeys:t})}if(e.response.authMethod.kind!==`email_otp`)throw Error(`ECDSA Email OTP registration publication has a different auth method`);let n=lt(e.response.authority);if(!n)throw Error(`ECDSA Email OTP registration authority is invalid`);return await nt({kind:`email_otp`,walletId:e.pending.walletId,email:e.pending.auth.email,registrationAuthorityId:e.pending.auth.registrationAuthorityId,authority:n,walletKeys:t})}function Al(e){return{pending:e.pending,authority:e.response.authority,foundingAuthority:{authority:e.response.foundingAuthority,authMethod:e.response.foundingAuthMethod},request:{operation:e.pending.operation,registrationCeremonyId:e.pending.registrationCeremonyId,idempotencyKey:e.pending.idempotencyKey,walletId:e.pending.walletId,walletAuthMethodId:e.pending.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:e.session.session.wallet_session,operationCredential:e.session.session.operation_credential},ecdsaContinuity:e.ecdsaContinuity,registration:e.registration}}async function jl(e){let t=await e.ports.activateWalletRegistration(ml(e.relayerUrl,e.pending)),n=await Sl({pending:e.pending,response:t}),r=hl(n),i={sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,relayerUrl:e.relayerUrl,pending:e.pending,response:n,walletKeys:r,exactMethod:e.exactMethod,signingSurface:e.signingSurface},a=await e.ports.unlockPendingEcdsaRegistration(i),o=r[0];if(!o)throw Error(`ECDSA registration activation returned no primary key`);let s=await ct({authority:n.authority}),c=await El({authority:s,chainTargets:Ol(r),walletId:String(e.pending.walletId),keyHandle:o.keyHandle,ecdsaThresholdKeyId:o.ecdsaThresholdKeyId,signingRootId:o.signingRootId,signingRootVersion:o.signingRootVersion,relayerKeyId:o.relayerKeyId,participantIds:o.participantIds,publicCapability:o.publicCapability,activationReceipt:n.ecdsa.activation,runtimePolicyScope:cl(n).ecdsa.runtimePolicyScope,readyStateBlobB64u:a.readyStateBlobB64u,publicFacts:a.publicFacts}),l={kind:`ecdsa_role_local_worker_handle_v1`,materialHandle:un(c.roleLocalMaterialRef.durableMaterialRef),bindingDigest:c.roleLocalMaterialRef.bindingDigest,durableMaterialRef:c.roleLocalMaterialRef.durableMaterialRef},u=await e.signingSurface.finalizeWalletRegistrationEcdsaSessions({walletId:String(e.pending.walletId),session:{chainTargets:Ol(r),authority:s,bootstrap:{applicationBindingDigestB64u:n.ecdsa.bootstrap.applicationBindingDigestB64u},roleLocalMaterial:l,materialActivation:c.roleLocalMaterialRef.materialActivation,clientPublicFacts:{contextBinding32B64u:a.publicFacts.contextBinding32B64u,derivationClientSharePublicKey33B64u:a.publicFacts.derivationClientSharePublicKey33B64u,clientVerifyingShareB64u:a.publicFacts.clientVerifyingShare33B64u,relayerPublicKey33B64u:a.publicFacts.relayerPublicKey33B64u,groupPublicKey33B64u:a.publicFacts.groupPublicKey33B64u,ethereumAddress:a.publicFacts.ethereumAddress},publicCapability:o.publicCapability},walletKeys:r}),d=await kl({pending:e.pending,response:n,walletKeys:u});if(await e.ports.publishPendingWalletRegistrationCommit(Al({pending:e.pending,response:n,registration:d,session:a.session,ecdsaContinuity:c.publication})),e.pending.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&e.pending.auth.kind===`passkey`&&a.kind===`passkey`){let t=wl(a.credential,`Pending NEAR registration continuation`),n=xh({context:e.nearContext,sessionAuthority:{record:a.session.session.wallet_session,operationCredential:a.session.session.operation_credential},factor:{kind:`passkey`,rpId:e.pending.auth.rpId,credentialIdB64u:Tl(a.credential),prfFirstB64u:t},ownedFactorSecret:R(t).slice().buffer,custodyEnvelope:a.custody.envelope});e.nearCompletion===`await`&&await n}return{kind:`published`,registrationCeremonyId:e.pending.registrationCeremonyId,walletId:n.walletId,signingSession:{sessionId:String(a.session.session.threshold_session_id),status:`active`,authMethod:a.kind,remainingUses:a.session.session.remaining_uses,expiresAtMs:a.session.session.expires_at_ms}}}function Ml(e,t,n){e?.(mn({flowId:`unlock:${t}`,accountId:t,...n}))}async function Nl(e){let{context:t,authMethod:n,unlockSubjectId:r,loginResult:i,onEvent:a,afterCall:o}=e;return i.success&&t.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:i.walletId,authMethod:n}),Ml(a,r,{phase:gn.STEP_07_COMPLETED,status:`succeeded`,data:{...i.success&&i.kind===`near_wallet_unlocked`?{operationalPublicKey:i.operationalPublicKey??``}:{walletId:i.success?String(i.walletId):``}}}),await o?.(!0,i),i}async function Pl(e){let{message:t,unlockSubjectId:n,error:r,onEvent:i,onError:a,afterCall:o,callOnError:s=!0,callAfterCall:c=!0,cancelled:l=!1}=e;return s&&a?.(Ce(r)),Ml(i,n,{phase:l?gn.CANCELLED:gn.FAILED,status:l?`cancelled`:`failed`,...l?{}:{message:t},interaction:{kind:`passkey_assert`,overlay:`hide`},error:{message:t}}),c&&await o?.(!1),{success:!1,error:t}}async function Fl(e){let t=An(),n=null;try{let r=JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:L(e)}))),i=await Ar({runStep:e.runStep,custody:e.factorAfterRouterRound?{origin:`establish_factor_after_round`,walletId:e.walletId,recoveryCodesJson:r,factor:e.factorAfterRouterRound}:{origin:`establish`,walletId:e.walletId,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:r},keySetRun:{keySet:`near_ed25519_v1`,protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],...e.continuityRegisteredPublicKeyB64u===void 0?{}:{continuityRegisteredPublicKeyB64u:e.continuityRegisteredPublicKeyB64u}}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async t=>{let r=await e.runRouterRound(t);return n=Yl(r),r}}});if(!n)throw Error(`the NEAR custody ceremony produced no activation session id`);let a=await Jl(i,t);return{recoveryCodes:t.codes,activationReference:{kind:`router_ab_ed25519_yao_activation_reference_v1`,lifecycle_id:e.registrationCeremonyId,session_id:n},commitPayload:ql(a),localMaterial:i.ed25519LocalMaterialB64u&&i.ed25519LocalMaterialNonceB64u&&i.ed25519ApplicationBindingDigestB64u?{b64u:i.ed25519LocalMaterialB64u,nonceB64u:i.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:i.ed25519ApplicationBindingDigestB64u}:null}}finally{t&&On(t),t=null}}function Il(e){let t=e.establishedCustody;if(!t)throw Error(`wallet custody join requires an established envelope`);let n;try{n=JSON.parse(t.envelopeBindingJson)}catch{throw Error(`wallet custody envelope binding is not JSON`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`wallet custody envelope binding must be an object`);return JSON.stringify({envelopeBinding:n,nonceB64u:t.envelopeNonceB64u,sealedCustodySecretB64u:t.sealedCustodySecretB64u,aadHashB64u:t.envelopeAadHashB64u,ciphertextDigestB64u:t.envelopeCiphertextDigestB64u})}async function Ll(e){let t=An(),n=null,r=null;try{let i=t;if(!i)throw Error(`recovery codes were not issued`);let a=await Ar({runStep:e.runStep,custody:{origin:`establish`,walletId:e.walletId,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:L(e)})))},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:e.confirmRecoveryCodesBackedUp.bind(void 0,t.codes),runRelayerRound:async t=>{let a=rn(await Jl(t.preActivationCommitPayload,i));return n=a,r={contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.clientSharePublicKey33B64u,clientShareRetryCounter:t.clientShareRetryCounter,participantId:1},await e.runRelayerRound({...t,preActivationCommitPayload:a})}}});if(!n||!r)throw Error(`the EVM custody ceremony reached no activation round`);if(!a.ecdsaReadyStateBlobB64u||!a.ecdsaPublicFacts)throw Error(`the EVM custody ceremony produced no local signing material`);return{recoveryCodes:t.codes,commitPayload:n,clientBootstrap:r,localMaterial:{readyStateBlobB64u:a.ecdsaReadyStateBlobB64u,publicFacts:a.ecdsaPublicFacts}}}finally{t&&On(t),t=null}}async function Rl(e){let t=null,n=null,r=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:async r=>(t=r.preActivationCommitPayload,n={contextBinding32B64u:r.contextBinding32B64u,derivationClientSharePublicKey33B64u:r.clientSharePublicKey33B64u,clientShareRetryCounter:r.clientShareRetryCounter,participantId:1},await e.runRelayerRound(r))}});if(!t||!n)throw Error(`the EVM custody join reached no activation round`);if(r.establishedCustody)throw Error(`an EVM custody join must not establish a second wallet seed`);if(!r.ecdsaReadyStateBlobB64u||!r.ecdsaPublicFacts)throw Error(`the EVM custody join produced no local signing material`);return{commitPayload:t,clientBootstrap:n,localMaterial:{readyStateBlobB64u:r.ecdsaReadyStateBlobB64u,publicFacts:r.ecdsaPublicFacts}}}function zl(e){switch(e.factorReplacement.kind){case`preserve_existing`:return{origin:`recover`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode};case`reseal_replacement_factor`:return{origin:`recover_and_reseal`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode,replacementFactorJson:e.factorReplacement.factorJson,replacementFactorSecret:e.factorReplacement.factorSecret};default:return Bl(e.factorReplacement)}}function Bl(e){throw Error(`unsupported recovery factor replacement: ${String(e)}`)}async function Vl(e){if(await Gl({walletId:e.walletId,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,clientRootPublicKey33B64u:e.registeredClientRootPublicKey33B64u})!==e.recordedKeyManifestDigestB64u)throw Error(`EVM recovery manifest digest does not match the registered identity`);let t=await Ar({runStep:e.runStep,custody:zl(e),keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:e.resolveRelayerPublicIdentity},recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});if(!t.ecdsaReadyStateBlobB64u||!t.ecdsaPublicFacts)throw Error(`the EVM recovery produced no local signing material`);if(t.clientRootPublicKey33B64u!==e.registeredClientRootPublicKey33B64u)throw Error(`the EVM recovery changed the registered client root public key`);return{readyStateBlobB64u:t.ecdsaReadyStateBlobB64u,publicFacts:t.ecdsaPublicFacts,recoveryReplacementEnvelope:t.recoveryReplacementEnvelope??null}}async function Hl(e){let t=await Gl({walletId:e.walletId,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,clientRootPublicKey33B64u:e.registeredClientRootPublicKey33B64u}),n=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:async()=>e.relayerPublicIdentityJson},recordedKeyManifestDigestB64u:t});if(n.establishedCustody)throw Error(`an EVM cold unlock must not establish custody`);if(!n.ecdsaReadyStateBlobB64u||!n.ecdsaPublicFacts)throw Error(`the EVM cold unlock produced no local signing material`);return{readyStateBlobB64u:n.ecdsaReadyStateBlobB64u,publicFacts:n.ecdsaPublicFacts}}function Ul(e,t){e.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255)}function Wl(e,t,n){let r=new TextEncoder().encode(t);Ul(e,r.length),e.push(...r),Ul(e,n.length),e.push(...n)}async function Gl(e){let t=String(e.walletId||``).trim(),n=String(e.evmFamilySigningKeySlotId||``).trim(),r=R(e.clientRootPublicKey33B64u);if(!t||!n||r.length!==33)throw Error(`EVM custody continuity identity is invalid`);let i=[];return Wl(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/evm-family-ecdsa/v1`)),Wl(i,`walletId`,new TextEncoder().encode(t)),Wl(i,`evmFamilySigningKeySlotId`,new TextEncoder().encode(n)),Wl(i,`clientRootPublicKey33`,r),L(await D(Uint8Array.from(i)))}async function Kl(e){let t=String(e.walletId||``).trim(),n=String(e.nearEd25519SigningKeyId||``).trim(),r=R(e.registeredPublicKeyB64u);if(!t||!n||r.length!==32)throw Error(`NEAR custody continuity identity is invalid`);let i=[];return Wl(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/near-ed25519/v1`)),Wl(i,`walletId`,new TextEncoder().encode(t)),Wl(i,`nearEd25519SigningKeyId`,new TextEncoder().encode(n)),Wl(i,`registeredPublicKey`,r),L(await D(Uint8Array.from(i)))}function ql(e){let{ed25519LocalMaterialB64u:t,ed25519LocalMaterialNonceB64u:n,ed25519ApplicationBindingDigestB64u:r,ecdsaReadyStateBlobB64u:i,recoveryReplacementEnvelope:a,...o}=e;return o}async function Jl(e,t){let n=e.establishedCustody;if(!n)return e;if(n.recoveryManifestKekWraps.length!==t.codeBytes.length)throw Error(`recovery code and wrap counts do not match`);let r=await Promise.all(t.codeBytes.map(async(e,t)=>{let r=n.recoveryManifestKekWraps[t];if(!r)throw Error(`recovery code and wrap counts do not match`);return{locatorB64u:await kn(e),recoveryKeyId:r.recoveryKeyId}}));if(new Set(r.map(e=>e.locatorB64u)).size!==r.length)throw Error(`recovery code locators must be unique`);return{...e,establishedCustody:{...n,recoveryCodeLocators:r}}}function Yl(e){let t;try{t=JSON.parse(e)}catch{throw Error(`the Router activation result is not JSON`)}let n=t?.binding?.session_id;if(!Array.isArray(n)||n.length===0)throw Error(`the Router activation result carries no session id`);return n.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`the Router activation session id is not a byte array`);return e})}async function Xl(e){if(await Kl({walletId:e.walletId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,registeredPublicKeyB64u:e.registeredPublicKeyB64u})!==e.recordedKeyManifestDigestB64u)throw Error(`NEAR recovery manifest digest does not match the registered identity`);let t=null,n=null,r=await Ar({runStep:e.runStep,custody:zl(e),keySetRun:{keySet:`near_ed25519_v1`,protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],continuityRegisteredPublicKeyB64u:e.registeredPublicKeyB64u}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async n=>(t=await e.runRouterRound(n),t),afterRouterRoundCompleted:async t=>{n=await e.activateRouterRecovery(t)}},recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});if(!r.ed25519LocalMaterialB64u||!r.ed25519LocalMaterialNonceB64u)throw Error(`the NEAR recovery sealed no local signing material`);if(!r.ed25519ApplicationBindingDigestB64u)throw Error(`the NEAR recovery omitted its application binding digest`);if(!t||!n)throw Error(`the NEAR recovery produced no Router activation`);return{localMaterial:{b64u:r.ed25519LocalMaterialB64u,nonceB64u:r.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:r.ed25519ApplicationBindingDigestB64u},activationResultJson:t,activationReceipt:n,recoveryReplacementEnvelope:r.recoveryReplacementEnvelope??null}}async function Zl(e){return await $l(e,e.registrationCeremonyId,void 0,`registration join`)}async function Ql(e){let t=String(e.registeredPublicKeyB64u||``).trim();if(!t)throw Error(`a cold unlock must name the key set it reproduces`);let n=null,r=null,i=await $l({...e,preparation:{kind:`fresh`}},e.recoveryLifecycleId,t,`cold unlock`,async t=>{n=t,r=await e.activateRouterRecovery(t)});if(!n||!r)throw Error(`the NEAR cold unlock produced no Router recovery activation`);return{...i,activationResultJson:n,activationReceipt:r}}async function $l(e,t,n,r,i){let a=null,o=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`near_ed25519_v1`,...e.preparation.kind===`checkpoint`?{checkpointJson:e.preparation.checkpointJson}:{protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],...n?{continuityRegisteredPublicKeyB64u:n}:{}}),beforeRouterRound:e.beforeRouterRound},nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async t=>{let n=await e.runRouterRound(t);return a=Yl(n),n},...i?{afterRouterRoundCompleted:i}:{}}});if(!a)throw Error(`the NEAR ${r} produced no activation session id`);if(o.establishedCustody)throw Error(`a NEAR ${r} must not establish custody`);if(!o.ed25519LocalMaterialB64u||!o.ed25519LocalMaterialNonceB64u)throw Error(`the NEAR ${r} sealed no local material`);return{commitPayload:ql(o),activationReference:{kind:`router_ab_ed25519_yao_activation_reference_v1`,lifecycle_id:t,session_id:a},localMaterial:{b64u:o.ed25519LocalMaterialB64u,nonceB64u:o.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:String(o.ed25519ApplicationBindingDigestB64u||``)}}}function eu(e){switch(e.routeFamily){case`operation_step_up`:return{routeFamily:e.routeFamily,operation:e.operation,operationCredential:e.operationCredential};case`registration`:if(e.operation!==`registration`)throw Error(`Email OTP registration routes require registration operation`);return{routeFamily:`registration`,operation:e.operation};case`login`:if(!Ue(e.operation))throw Error(`Email OTP login routes require a login operation`);return{routeFamily:`login`,operation:e.operation};case`signing_session`:if(e.operation!==`transaction_sign`&&e.operation!==`export_key`)throw Error(`Email OTP signing-session routes require signing or export operation`);return{routeFamily:`signing_session`,authLane:e.authLane,operation:e.operation}}throw Error(`Unsupported Email OTP route family`)}var tu=class e extends Error{kind=`email_otp_signing_session_auth_state_error`;failure;constructor(t){super(nu(t)),this.name=`EmailOtpSigningSessionAuthStateError`,this.failure=t,Object.setPrototypeOf(this,e.prototype)}};function nu(e){return`Email OTP ${e.expectedCurve} signing-session auth lane is unavailable at ${e.source}; unlock wallet again`}function ru(e){throw new tu(e)}function iu(e){return e.freshRouteFamily===`registration`?eu({routeFamily:`registration`,operation:He}):eu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function au(e){return e?.kind!==`signing_session`&&ru({kind:`auth_lane_missing`,source:`route_plan`,expectedCurve:`unknown`}),e}function ou(e){return eu({routeFamily:`signing_session`,authLane:e.authLane,operation:e.operation})}function su(e){if(e.kind===`signing_session`&&e.curve===`ecdsa`)return{kind:`threshold_ecdsa_session`,operationCredential:e.operationCredential,curve:`ecdsa`,thresholdSessionId:e.thresholdSessionId,chainTarget:e.chainTarget}}function cu(e){if(e.routeFamily===`signing_session`)return su(e.authLane)}async function lu(e){return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`unlockEmailOtpAuthorityWallet`,timeoutMs:6e4,payload:{relayUrl:e.relayUrl,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,challengeId:e.challengeId,otpCode:e.otpCode,ed25519:e.ed25519}}})}async function uu(e){return await e.base.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`loginWithEmailOtpWallet`,timeoutMs:6e4,payload:{relayUrl:e.base.relayUrl,walletId:String(e.base.walletSession.walletId),authoritySelector:e.base.authoritySelector,userId:String(e.base.walletSession.walletSessionUserId),verification:e.base.verification,groupId:e.base.groupId,routePlan:e.base.routePlan,otpChannel:Ke,material:e.material},onEvent:e.base.onProgress}})}async function du(e){let t=await uu({base:e,material:e.ecdsaSessionPolicy?{kind:`ecdsa`,ecdsaSessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope,ecdsaSessionPolicy:e.ecdsaSessionPolicy}:{kind:`ecdsa`,ecdsaSessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope}});if(t.kind!==`ecdsa`)throw Error(`Email OTP wallet unlock returned the wrong material branch`);if(e.ecdsaSessionPolicy){if(t.operation!==`wallet_unlock`)throw Error(`Email OTP wallet unlock returned a non-unlock ECDSA result`);return{kind:`ecdsa`,operation:`wallet_unlock`,recovery:t.recovery,emailOtpSessionHandle:t.emailOtpSessionHandle,ecdsaSession:t.ecdsaSession,ecdsaCustody:t.ecdsaCustody}}if(t.operation!==e.ecdsaSessionHandleBinding.operation)throw Error(`Email OTP ECDSA result operation does not match its request`);return{kind:`ecdsa`,operation:t.operation,recovery:t.recovery,emailOtpSessionHandle:t.emailOtpSessionHandle}}async function fu(e){let t=await uu({base:e,material:{kind:`ed25519_yao_recovery`,providerSubject:e.providerSubject,nearAccountId:e.nearAccountId,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,walletCustodyEd25519Material:e.walletCustodyEd25519Material,ed25519YaoRecovery:{kind:Bt,signerSlot:e.signerSlot,remainingUses:e.remainingUses,orgId:e.orgId}}});if(t.kind===`ed25519_yao_capability`)return{kind:t.kind,recovery:t.recovery,activeClientHandle:t.activeClientHandle,metadata:t.metadata,ed25519YaoCapability:t.ed25519YaoCapability,walletSessionAuthorization:t.walletSessionAuthorization,...t.walletCustodyEd25519Material?{walletCustodyEd25519Material:t.walletCustodyEd25519Material}:{},ed25519ExportRootCustody:t.ed25519ExportRootCustody};if(t.kind!==`wallet_custody_cache_absent`)throw Error(`Email OTP Ed25519 Yao unlock returned the wrong material branch`);return{kind:`wallet_custody_cache_absent`,recovery:t.recovery,ed25519YaoRecovery:t.ed25519YaoRecovery}}async function pu(e){let t=await uu({base:e,material:{kind:`wallet_unlock_capabilities`,ecdsa:{sessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope,sessionPolicy:e.ecdsaSessionPolicy},ed25519Yao:{providerSubject:e.providerSubject,nearAccountId:e.nearAccountId,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,walletCustodyEd25519Material:e.walletCustodyEd25519Material,recovery:{kind:Bt,signerSlot:e.signerSlot,remainingUses:e.remainingUses,orgId:e.runtimePolicyScope.orgId}}}});if(t.kind!==`wallet_unlock_capabilities`)throw Error(`Email OTP capability unlock returned the wrong material branch`);return{kind:`wallet_unlock_capabilities`,recovery:t.recovery,walletSessionAuthorization:t.walletSessionAuthorization,ed25519ExportRootCustody:t.ed25519ExportRootCustody,ecdsa:{kind:`ecdsa`,operation:`wallet_unlock`,recovery:t.recovery,emailOtpSessionHandle:t.ecdsa.emailOtpSessionHandle,ecdsaSession:t.ecdsa.session,ecdsaCustody:t.ecdsa.custody},ed25519Yao:t.ed25519Yao.kind===`wallet_custody_cache_absent`?{kind:`wallet_custody_cache_absent`,recovery:t.recovery,ed25519YaoRecovery:t.ed25519Yao.bootstrap}:{kind:`ed25519_yao_capability`,recovery:t.recovery,activeClientHandle:t.ed25519Yao.activeClientHandle,metadata:t.ed25519Yao.metadata,ed25519YaoCapability:t.ed25519Yao.bootstrap,walletSessionAuthorization:t.walletSessionAuthorization,ed25519ExportRootCustody:t.ed25519ExportRootCustody}}}function mu(e){let t=e.walletSessionState.signingLane;if(t.auth.kind!==`passkey`)throw Error(`[SigningEngine][near] Passkey recovery returned another auth lane`);let n=t.identity.signer;return{walletId:n.account.wallet.walletId,nearAccountId:n.account.nearAccountId,thresholdSessionId:e.walletSessionState.thresholdSessionId,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,materialActivation:e.materialActivation,auth:{kind:`passkey`,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u},nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}}function hu(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function gu(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||e[0]<1||e[1]<1||e[0]===e[1])throw Error(`participantIds must contain two distinct positive integers`);return[Number(e[0]),Number(e[1])]}function _u(e){return e.kind===`sign`&&e.keyFamily===`ed25519`}function vu(e,t,n,r,i,a){if(`sessionKind`in e||`walletSessionToken`in e)throw Error(`sync-account signer bootstrap must not carry a Wallet Session bearer`);if(T(e.walletId,`session.walletId`)!==n.walletId||T(e.nearAccountId,`session.nearAccountId`)!==n.nearAccountId||T(e.nearEd25519SigningKeyId,`session.nearEd25519SigningKeyId`)!==n.nearEd25519SigningKeyId)throw Error(`Yao recovery session identity does not match the verified passkey`);let o=I(E(e.runtimePolicyScope,`session.runtimePolicyScope`)),s=se(e.routerAbNormalSigning);if(!s)throw Error(`Yao recovery session signing state is invalid`);let c=_e(e.walletSessionId),l=he(e.quotaId);if(!c.ok||!l.ok)throw Error(`Yao recovery Wallet Session identity is invalid`);let u=hu(e.expiresAtMs,`session.expiresAtMs`),d=hu(e.remainingUses,`session.remainingUses`),f=r.capabilitySubjects.find(_u);if(r.walletId!==n.walletId||r.authorityId!==a.walletAuthorityId||r.authMethodId!==a.walletAuthMethodId||r.authorityDigestB64u!==a.authorityDigestB64u||r.authorityRevocationEpoch!==a.authorityRevocationEpoch||r.expiresAtMs!==u||i.walletSessionId!==c.value||!f||!p(f.materialActivation,a.materialActivation))throw Error(`Yao recovery session does not match the exact Wallet Session`);return{thresholdSessionId:T(e.thresholdSessionId,`session.thresholdSessionId`),authorizationId:r.authorizationId,walletSessionId:i.walletSessionId,quotaId:l.value,expiresAtMs:u,remainingUses:d,runtimePolicyScope:o,participantIds:t,routerAbNormalSigning:s,walletSession:r,operationCredential:i}}function yu(e){let t=e.capability,n=e.session,r=re(n.runtimePolicyScope);if(!r||t.applicationBinding.wallet_id!==String(e.walletId)||t.applicationBinding.near_ed25519_signing_key_id!==e.nearEd25519SigningKeyId||t.applicationBinding.key_creation_signer_slot!==e.signerSlot||t.nearAccountId!==e.nearAccountId||t.lifecycle.accountId!==String(e.walletId)||t.lifecycle.signingWorkerId!==e.relayerKeyId||n.routerAbNormalSigning?.signingWorkerId!==e.relayerKeyId||n.participantIds[0]!==t.participantIds[0]||n.participantIds[1]!==t.participantIds[1]||!ee(n.runtimePolicyScope,t.runtimePolicyScope)||n.runtimePolicyScope.signingRootVersion!==t.lifecycle.rootShareEpoch||t.applicationBinding.signing_root_id!==r.signingRootId||e.operationalPublicKey!==`ed25519:${Ee(Uint8Array.from(t.registeredPublicKey))}`)throw Error(`Yao recovery response does not preserve the registered wallet identity`)}function bu(e){if(yu(e),e.capability.lifecycle.thresholdSessionId!==e.session.thresholdSessionId)throw Error(`Yao recovery response does not preserve the threshold material lifecycle`)}function xu(e,t){if(yu(e),!p(e.capability.materialActivation,t))throw Error(`Yao warm recovery response does not preserve exact material activation`)}function Su(e){return`operationCredential`in e?e.operationCredential.token:e.walletSessionToken}function Cu(e){let n=E(e,`sync-account response`);if(n.ok!==!0||n.verified!==!0)throw Error(`sync-account response is not verified`);let r=qt(T(n.walletId,`walletId`)),i=z(T(n.nearAccountId,`nearAccountId`)),a=T(n.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),o=E(n.thresholdEd25519,`thresholdEd25519`),s=gu(o.participantIds),l=E(n.ed25519YaoRecovery,`ed25519YaoRecovery`);if(l.kind!==`router_ab_ed25519_yao_sync_recovery_v1`)throw Error(`sync-account recovery kind is invalid`);let u=bt(l.authorityRef);if(!u||String(u.walletId)!==String(r))throw Error(`sync-account recovery authority is invalid`);let d=c(n.walletAuthMethodId),f=t(n.walletAuthorityId),p=rt(n.foundingAuthority),m=Kt(n.foundingAuthMethod);if(!d.ok||!f.ok||d.value!==u.walletAuthMethodId||!p.ok||p.value.state!==`active`||p.value.provenance.kind!==`wallet_registration`||p.value.walletId!==r||p.value.authorityId!==f.value||!m||m.kind!==`passkey`||m.status!==`active`||m.walletId!==r||m.walletAuthorityId!==f.value||m.walletAuthMethodId!==d.value)throw Error(`sync-account exact auth-method identity is invalid`);let h=E(n.walletCustody,`walletCustody`);if(h.kind!==`wallet_custody_sync_bootstrap_v1`)throw Error(`walletCustody kind is invalid`);let g=Jr(l.capability),_=me(n.walletSession),v=pe(n.operationCredential),y={authority:u,walletAuthMethodId:d.value,walletAuthorityId:f.value,foundingAuthority:p.value,foundingAuthMethod:m,walletId:r,nearAccountId:i,nearEd25519SigningKeyId:a,signerSlot:hu(n.signerSlot,`signerSlot`),operationalPublicKey:T(n.publicKey,`publicKey`),relayerKeyId:T(o.relayerKeyId,`thresholdEd25519.relayerKeyId`),keyVersion:T(o.keyVersion,`thresholdEd25519.keyVersion`),credentialIdB64u:T(n.credentialIdB64u,`credentialIdB64u`),credentialPublicKeyB64u:T(n.credentialPublicKeyB64u,`credentialPublicKeyB64u`),session:vu(E(o.session,`thresholdEd25519.session`),s,{walletId:String(r),nearAccountId:String(i),nearEd25519SigningKeyId:a},_,v,{walletAuthorityId:f.value,walletAuthMethodId:d.value,authorityDigestB64u:p.value.authorityDigestB64u,authorityRevocationEpoch:p.value.revocationEpoch,materialActivation:g.materialActivation}),capability:g,walletSession:_,operationCredential:v,walletCustody:{envelope:$t(h.envelope),storeVersion:T(h.storeVersion,`walletCustody.storeVersion`)}};return bu(y),y}function wu(e){let t=e.parsed,n=t.session,r=re(n.runtimePolicyScope),i=ho({walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,walletSessionId:n.walletSessionId,authorizationId:n.authorizationId,quotaId:n.quotaId,thresholdSessionId:e.thresholdSessionId,remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs,runtimePolicyScope:n.runtimePolicyScope,signingRootId:r.signingRootId,signingRootVersion:String(r.signingRootVersion||``),routerAbNormalSigning:n.routerAbNormalSigning,walletSessionToken:Su(n),home:`operationCredential`in n?n.operationCredential.home:n.home,nowMs:Math.min(Date.now(),n.expiresAtMs-1)});if(!i.ok)throw Error(`recovered Yao Wallet Session is unusable: ${i.reason}`);return xc({walletId:Ie(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:Yt(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,rpId:pt(e.rpId),credentialIdB64u:t.credentialIdB64u,relayerUrl:e.relayerUrl,authority:t.authority,signingWalletSession:i.value})}function Tu(e){if(!b(e)||e.kind!==`wallet_custody_passkey_login_v1`)throw Error(`Passkey wallet unlock returned invalid custody data`);if(!b(e.ed25519))throw Error(`Passkey wallet unlock omitted Ed25519 custody continuity`);if(e.ed25519.kind===`absent`)return{kind:`wallet_custody_passkey_login_v1`,envelope:$t(e.envelope),storeVersion:T(e.storeVersion,`walletCustody.storeVersion`),ed25519:{kind:`absent`}};if(e.ed25519.kind!==`active`)throw Error(`Passkey wallet unlock returned invalid Ed25519 custody state`);let t=Number(e.ed25519.signerSlot),n=e.ed25519.participantIds;if(!Number.isSafeInteger(t)||t<1||!Array.isArray(n)||n.length!==2||!n.every(e=>Number.isSafeInteger(e)&&Number(e)>0)||n[0]===n[1])throw Error(`Passkey wallet unlock returned invalid Ed25519 signer identity`);return{kind:`wallet_custody_passkey_login_v1`,envelope:$t(e.envelope),storeVersion:T(e.storeVersion,`walletCustody.storeVersion`),ed25519:{kind:`active`,nearAccountId:T(e.ed25519.nearAccountId,`walletCustody.ed25519.nearAccountId`),nearEd25519SigningKeyId:T(e.ed25519.nearEd25519SigningKeyId,`walletCustody.ed25519.nearEd25519SigningKeyId`),signerSlot:t,publicKey:T(e.ed25519.publicKey,`walletCustody.ed25519.publicKey`),relayerKeyId:T(e.ed25519.relayerKeyId,`walletCustody.ed25519.relayerKeyId`),participantIds:[Number(n[0]),Number(n[1])],capability:Jr(e.ed25519.capability)}}}function Eu(e){if(!b(e))throw Error(`ECDSA custody chain target is invalid`);let t=T(e.kind,`ecdsaCustody.chainTarget.kind`),n=Number(e.chainId),r=T(e.networkSlug,`ecdsaCustody.chainTarget.networkSlug`);if(!Number.isSafeInteger(n)||n<0||!r)throw Error(`ECDSA custody chain target is invalid`);if(t===`evm`){if(e.namespace!==`eip155`)throw Error(`ECDSA custody EVM namespace is invalid`);return{kind:`evm`,namespace:`eip155`,chainId:n,networkSlug:r}}if(t===`tempo`)return{kind:`tempo`,chainId:n,networkSlug:r};throw Error(`ECDSA custody chain target kind is invalid`)}function Du(e){if(!b(e)||e.kind!==`wallet_custody_ecdsa_sync_continuity_v1`)throw Error(`Passkey wallet unlock returned invalid ECDSA custody continuity`);if(!Array.isArray(e.signers))throw Error(`Passkey wallet unlock returned invalid ECDSA custody signers`);let t=[];for(let n of e.signers){if(!b(n)||!b(n.walletKey))throw Error(`Passkey wallet unlock returned invalid ECDSA custody signer`);let e=n.walletKey,r=e.participantIds;if(!Array.isArray(r)||r.length!==2||r[0]!==1||r[1]!==2)throw Error(`Passkey wallet unlock returned invalid ECDSA custody participants`);t.push({chainTarget:Eu(n.chainTarget),walletKey:{walletId:T(e.walletId,`ecdsaCustody.walletKey.walletId`),keyHandle:T(e.keyHandle,`ecdsaCustody.walletKey.keyHandle`),ecdsaThresholdKeyId:T(e.ecdsaThresholdKeyId,`ecdsaCustody.walletKey.ecdsaThresholdKeyId`),signingRootId:T(e.signingRootId,`ecdsaCustody.walletKey.signingRootId`),signingRootVersion:T(e.signingRootVersion,`ecdsaCustody.walletKey.signingRootVersion`),relayerKeyId:T(e.relayerKeyId,`ecdsaCustody.walletKey.relayerKeyId`),contextBinding32B64u:T(e.contextBinding32B64u,`ecdsaCustody.walletKey.contextBinding32B64u`),derivationClientSharePublicKey33B64u:T(e.derivationClientSharePublicKey33B64u,`ecdsaCustody.walletKey.derivationClientSharePublicKey33B64u`),participantIds:[1,2],publicCapability:Ct(e.publicCapability)},activationReceipt:Tt(n.activationReceipt),runtimePolicyScope:I(n.runtimePolicyScope)})}if(t.length===0)throw Error(`Passkey wallet unlock omitted ECDSA custody signers`);return{kind:`wallet_custody_ecdsa_sync_continuity_v1`,signers:t}}function Ou(e){let t=e.raw.sessionKind;if(t===`issued_exact_wallet_session`){let n=pe(e.raw.operationCredential);if(n.walletSessionId!==e.walletSessionId)throw Error(`Wallet unlock Ed25519 credential does not identify its session`);return{sessionKind:t,operationCredential:n}}if(t!==`already_committed_exact_wallet_session`)throw Error(`Wallet unlock returned an unsupported Ed25519 session kind`);if(e.raw.operationCredential!==void 0)throw Error(`Reused Ed25519 Wallet Session must not carry its own credential`);if(pe(e.unlockCredential).walletSessionId!==e.walletSessionId)throw Error(`Wallet unlock Ed25519 session reuses another Wallet Session`);return{sessionKind:t}}function ku(e,t){if(e===null)return null;if(!b(e))throw Error(`Wallet unlock returned invalid Ed25519 session data`);let n=s(e.thresholdSessionId),r=ve(e.authorizationId),i=_e(e.walletSessionId),a=he(e.quotaId),o=Number(e.expiresAtMs),c=Number(e.remainingUses),l=I(e.runtimePolicyScope),u=ce(e.routerAbNormalSigning),d=e.participantIds;if(!n.ok||!r.ok||!i.ok||!a.ok||!Number.isSafeInteger(o)||o<=Date.now()||!Number.isSafeInteger(c)||c<1||!Array.isArray(d)||d.length!==2||!d.every(e=>Number.isSafeInteger(e)&&e>0)||d[0]===d[1])throw Error(`Wallet unlock returned invalid Ed25519 session lifecycle`);let f=Ou({raw:e,walletSessionId:i.value,unlockCredential:t});return{walletId:T(e.walletId,`ed25519Session.walletId`),nearAccountId:T(e.nearAccountId,`ed25519Session.nearAccountId`),nearEd25519SigningKeyId:T(e.nearEd25519SigningKeyId,`ed25519Session.nearEd25519SigningKeyId`),relayerKeyId:T(e.relayerKeyId,`ed25519Session.relayerKeyId`),participantIds:[Number(d[0]),Number(d[1])],thresholdSessionId:n.value,authorizationId:r.value,walletSessionId:i.value,quotaId:a.value,expiresAtMs:o,remainingUses:c,runtimePolicyScope:l,routerAbNormalSigning:u,...f}}function Au(e){let t=e.authorization.record,n=gt(e.ecdsaSession.public_capability.material_activation),r=0;for(let e of t.capabilitySubjects)e.kind===`sign`&&e.keyFamily===`ecdsa_secp256k1`&&p(e.materialActivation,n)&&(r+=1);if(t.walletId!==e.ed25519Session.walletId||t.walletId!==e.ecdsaSession.public_capability.client_id||t.authorizationId!==e.ed25519Session.authorizationId||t.authorizationId!==e.ecdsaSession.session.authorization_id||t.quotaId!==e.ed25519Session.quotaId||t.quotaId!==e.ecdsaSession.session.quota_id||t.expiresAtMs!==e.ed25519Session.expiresAtMs||t.expiresAtMs!==e.ecdsaSession.session.expires_at_ms||e.ed25519Session.walletSessionId!==e.ecdsaSession.session.wallet_session_id||e.authorization.operationCredential.walletSessionId!==e.ed25519Session.walletSessionId||e.ed25519Session.remainingUses!==e.ecdsaSession.session.remaining_uses||r!==1)throw Error(`Passkey ECDSA activation authority does not match its Wallet Session`)}function ju(e){let t=e.authorization.record;if(t.walletId!==e.ed25519Session.walletId||t.authorizationId!==e.ed25519Session.authorizationId||t.quotaId!==e.ed25519Session.quotaId||t.expiresAtMs!==e.ed25519Session.expiresAtMs||e.authorization.operationCredential.walletSessionId!==e.ed25519Session.walletSessionId)throw Error(`Passkey Ed25519 Wallet Session authorization is inconsistent`)}async function Mu(e,t){let n=e.data.walletSession!==void 0;if(n!==(e.data.operationCredential!==void 0))throw Error(`Passkey wallet unlock returned a partial Wallet Session authorization`);if(n){if(e.ed25519Session.sessionKind!==`already_committed_exact_wallet_session`)throw Error(`Passkey wallet unlock returned competing Wallet Session credentials`);let t={record:me(e.data.walletSession),operationCredential:pe(e.data.operationCredential)};return ju({ed25519Session:e.ed25519Session,authorization:t}),t}if(e.ed25519Session.sessionKind!==`issued_exact_wallet_session`)throw Error(`Passkey wallet unlock omitted the exact Wallet Session credential`);let r=await t.read({relayerUrl:e.relayServerUrl,operationCredential:e.ed25519Session.operationCredential},{walletSessionId:e.ed25519Session.walletSessionId,quotaId:e.ed25519Session.quotaId});if(r.status!==`active`||r.walletSessionId!==e.ed25519Session.walletSessionId||r.quotaId!==e.ed25519Session.quotaId||r.expiresAtMs!==e.ed25519Session.expiresAtMs||r.remainingUses!==e.ed25519Session.remainingUses)throw Error(`Passkey wallet unlock returned an inconsistent issued Wallet Session`);let i={record:r.authorization,operationCredential:e.ed25519Session.operationCredential};return ju({ed25519Session:e.ed25519Session,authorization:i}),i}async function Nu(e,t){let n=await Mu(e,t);return Au({ed25519Session:e.ed25519Session,ecdsaSession:e.ecdsaSession,authorization:n}),n}function Pu(e){let t=qn(e)??er(e);return t?{success:!1,kind:`already_committed`,code:t.code,message:t.message,next:t.next,committed:t.committed}:null}async function Fu(e,t,n){try{if(t.type!==`passkey_assertion`)throw Error(`Passkey wallet unlock requires a passkey assertion`);let r=T(t.challengeId,`challengeId`),a=t.webauthn_authentication,o=String(t.expected_origin||``).trim(),s={unlockBackend:`passkey`,challengeId:r,...`walletId`in t&&t.walletId?{walletId:t.walletId}:{},webauthn_authentication:zn(a),ed25519SessionRequest:t.ed25519SessionRequest,...o?{expected_origin:o}:{},...t.ecdsaSessionPolicy?{ecdsaSessionPolicy:dt(t.ecdsaSessionPolicy)}:{}},c=i(e,`/wallet/unlock/verify`),l=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(s)}),u=await l.json().catch(()=>({})),d=b(u)?u:{};if(!l.ok)return Pu(d)||{success:!1,error:typeof d.message==`string`?d.message:`HTTP ${l.status}`};if(d.ok!==!0)return Pu(d)||{success:!1,error:typeof d.message==`string`?d.message:`Wallet unlock verification failed`};let f=t.type===`passkey_assertion`&&t.ecdsaSessionPolicy!==void 0,p=ku(d.ed25519Session,d.operationCredential);if(t.ed25519SessionRequest.kind===`requested`&&!p)throw Error(`Wallet unlock omitted the requested Ed25519 Wallet Session`);if(t.ed25519SessionRequest.kind===`not_requested`&&p)throw Error(`Wallet unlock returned an unrequested Ed25519 Wallet Session`);let m=Tu(d.walletCustody),h,g,_,v;if(f){if(d.ecdsaSession===void 0)throw Error(`Wallet unlock omitted the requested ECDSA Wallet Session activation`);if(h=b(d.ecdsaSession)&&d.ecdsaSession.kind===`router_ab_ecdsa_credential_free_session_activated_v1`?at(d.ecdsaSession):_t(d.ecdsaSession),d.ecdsaActivationReceipt===void 0||d.ecdsaCustody===void 0)throw Error(`Wallet unlock omitted ECDSA custody continuity`);if(_=Tt(d.ecdsaActivationReceipt),v=Du(d.ecdsaCustody),!m)throw Error(`Wallet unlock omitted wallet custody for ECDSA activation`);if(h.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){if(!p)throw Error(`Credential-free ECDSA activation requires an Ed25519 Wallet Session`);g=await Nu({relayServerUrl:e,data:d,ed25519Session:p,ecdsaSession:h},n)}}else if(d.ecdsaSession!==void 0)throw Error(`Wallet unlock returned an unrequested ECDSA Wallet Session activation`);else p&&(g=await Mu({relayServerUrl:e,data:d,ed25519Session:p},n));if(h&&_&&v&&m){if(h.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){if(!g)throw Error(`Credential-free ECDSA activation omitted exact Wallet Session authority`);return{success:!0,ecdsaSession:h,ecdsaActivationReceipt:_,ecdsaCustody:v,ed25519Session:p,walletCustody:m,walletSessionAuthorization:g}}return{success:!0,ecdsaSession:h,ecdsaActivationReceipt:_,ecdsaCustody:v,ed25519Session:p,walletCustody:m}}if(m&&p&&g)return{success:!0,ed25519Session:p,walletCustody:m,walletSessionAuthorization:g};if(m&&!p)return{success:!0,ed25519Session:null,walletCustody:m};throw Error(`Passkey wallet unlock returned incomplete exact session state`)}catch(e){return{success:!1,error:we(e)||`Failed to verify wallet unlock`}}}async function Iu(e,t){try{let n=T(t.challengeId,`challengeId`),r=String(t.expected_origin||``).trim(),a={unlockBackend:`passkey`,challengeId:n,webauthn_authentication:zn(t.webauthn_authentication),ed25519SessionRequest:t.ed25519SessionRequest,...r?{expected_origin:r}:{}},o=await fetch(i(e,`/wallet/unlock/verify`),{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(a)}),s=await o.json().catch(()=>({})),c=b(s)?s:{};if(!o.ok||c.ok!==!0)return Pu(c)||{success:!1,error:typeof c.message==`string`?c.message:`Wallet Session unlock failed (HTTP ${o.status})`};if(c.walletCustody!==void 0&&c.walletCustody!==null)throw Error(`Linked passkey unlock returned custody data`);if(c.ecdsaSession!==void 0&&c.ecdsaSession!==null)throw Error(`Linked passkey unlock returned an ECDSA activation`);let l=ku(c.ed25519Session,c.operationCredential);if(t.ed25519SessionRequest.kind===`requested`&&!l)throw Error(`Linked passkey unlock omitted the requested Ed25519 Wallet Session`);if(t.ed25519SessionRequest.kind===`not_requested`&&l)throw Error(`Linked passkey unlock returned an unrequested Ed25519 Wallet Session`);return{success:!0,walletSession:me(c.walletSession),operationCredential:pe(c.operationCredential),ed25519Session:l}}catch(e){return{success:!1,error:we(e)||`Failed to verify linked passkey Wallet Session`}}}function Lu(e){let t=g(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a session id`);return t.value}function Ru(e){let t=ge(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a Wallet Session mint id`);return t.value}function zu(e){return dt({kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:e.keyHandle,session_policy:{threshold_session_id:Lu(pr(`threshold-ecdsa-registration-recovery`)),wallet_session_mint_id:Ru(pr(`wallet-session-mint`)),ttl_ms:e.sessionPolicy.ttlMs,remaining_uses:e.sessionPolicy.unlockRemainingUses,runtime_policy_scope:e.runtimePolicyScope}})}async function Bu(e){let t=await fetch(i(e.relayerUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:e.walletId,rpId:e.rpId})}),n=E(await t.json().catch(()=>({})),`Passkey unlock challenge response`);if(!t.ok||n.ok!==!0)throw Error(typeof n.message==`string`&&n.message?n.message:`wallet/unlock/challenge failed (HTTP ${t.status})`);return{challengeId:y(n.challengeId,`Passkey unlock challenge ID`),challengeB64u:y(n.challengeB64u,`Passkey unlock challenge`)}}function Vu(e){return e===`ble`||e===`hybrid`||e===`internal`||e===`nfc`||e===`usb`}function Hu(e,t){return{id:e,type:`public-key`,transports:t.filter(Vu)}}function Uu(e){let t=e.session.session.wallet_session;if(t.walletId!==e.pending.walletId||t.authMethodId!==e.pending.walletAuthMethodId||t.authorityId!==e.response.foundingAuthority.authorityId||t.expiresAtMs!==e.session.session.expires_at_ms||t.authorizationId!==e.session.session.authorization_id||t.quotaId!==e.session.session.quota_id||e.session.session.remaining_uses<=0||e.session.session.expires_at_ms<=Date.now()||e.session.session.wallet_session_id!==e.session.session.operation_credential.walletSessionId||!vt(e.session.public_capability,e.walletKey.publicCapability))throw Error(`ECDSA registration unlock did not issue the exact Wallet Session`)}function Wu(e){if(e.signers.length!==e.walletKeys.length)throw Error(`ECDSA registration unlock returned incomplete custody continuity`);let t=new Map;for(let n of e.walletKeys){let e=Re(n.chainTarget);if(t.has(e))throw Error(`ECDSA registration has duplicate custody targets`);t.set(e,n)}for(let n of e.signers){let r=Re(n.chainTarget),i=t.get(r);if(!i)throw Error(`ECDSA registration unlock returned an unknown target`);if(t.delete(r),n.walletKey.walletId!==e.pending.walletId||n.walletKey.keyHandle!==i.keyHandle||n.walletKey.ecdsaThresholdKeyId!==i.ecdsaThresholdKeyId||n.walletKey.signingRootId!==i.signingRootId||n.walletKey.signingRootVersion!==i.signingRootVersion||n.walletKey.relayerKeyId!==i.relayerKeyId||n.walletKey.contextBinding32B64u!==i.contextBinding32B64u||n.walletKey.derivationClientSharePublicKey33B64u!==i.derivationClientSharePublicKey33B64u||!vt(n.walletKey.publicCapability,i.publicCapability)||!Et(n.activationReceipt,e.response.ecdsa.activation))throw Error(`ECDSA registration unlock returned different custody continuity`)}}function Gu(e){new Uint8Array(e).fill(0)}async function Ku(e){if(e.pending.auth.kind!==`passkey`)throw Error(`ECDSA registration passkey unlock has a different pending factor`);let t=e.walletKeys[0];if(!t)throw Error(`ECDSA registration unlock has no primary wallet key`);let n=typeof window<`u`?window.location.origin:``;if(!n)throw Error(`ECDSA registration passkey unlock requires an origin`);Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_CHALLENGE_STARTED,status:`running`,authMethod:`passkey`});let r=await Bu({relayerUrl:e.relayerUrl,walletId:String(e.pending.walletId),rpId:e.pending.auth.rpId});Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`}});let i=await e.signingSurface.getAuthenticationCredentialsSerialized({subjectId:String(e.pending.walletId),challengeB64u:r.challengeB64u,allowCredentials:[Hu(e.pending.auth.credentialIdB64u,e.pending.auth.transports)],includeSecondPrfOutput:!0});if(Tl(i)!==e.pending.auth.credentialIdB64u)throw Error(`ECDSA registration unlock returned a different Passkey credential`);Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let a=wl(i,`ECDSA registration recovery`),o=await Fu(e.relayerUrl,{type:`passkey_assertion`,challengeId:r.challengeId,walletId:String(e.pending.walletId),webauthn_authentication:i,ed25519SessionRequest:{kind:`not_requested`},expected_origin:n,ecdsaSessionPolicy:zu({keyHandle:t.keyHandle,sessionPolicy:e.sessionPolicy,runtimePolicyScope:cl(e.response).ecdsa.runtimePolicyScope})},new fr);if(!o.success)throw Error(o.error||`Passkey ECDSA registration unlock failed`);if(o.ecdsaSession.kind!==`router_ab_ecdsa_post_registration_session_activated_v1`||!o.ecdsaCustody||!o.walletCustody)throw Error(`Passkey ECDSA registration unlock did not issue exact session custody`);Uu({pending:e.pending,response:e.response,session:o.ecdsaSession,walletKey:t}),Wu({pending:e.pending,response:e.response,walletKeys:e.walletKeys,signers:o.ecdsaCustody.signers});let s=Uint8Array.from(R(a)).buffer;try{let n=await e.signingSurface.rejoinWalletCustodyEvmFamilyKeySet({walletId:String(e.pending.walletId),custodyJson:Il(e.pending.localMaterial.custodyCommit),factorSecret:s,evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,applicationBindingDigestB64u:e.response.ecdsa.bootstrap.applicationBindingDigestB64u,registeredClientRootPublicKey33B64u:t.derivationClientSharePublicKey33B64u,relayerPublicIdentityJson:JSON.stringify({relayerKeyId:t.relayerKeyId,relayerPublicKey33B64u:t.relayerVerifyingShareB64u,groupPublicKey33B64u:t.thresholdEcdsaPublicKeyB64u,ethereumAddress:t.thresholdOwnerAddress,relayerShareRetryCounter:t.relayerShareRetryCounter})});return{kind:`passkey`,credential:i,custody:o.walletCustody,session:o.ecdsaSession,readyStateBlobB64u:n.readyStateBlobB64u,publicFacts:n.publicFacts}}finally{Gu(s)}}async function qu(e){if(e.pending.auth.kind!==`email_otp`)throw Error(`ECDSA registration Email OTP unlock has a different pending factor`);let t=e.walletKeys[0];if(!t)throw Error(`ECDSA registration unlock has no primary wallet key`);let n=cl(e.response).ecdsa.runtimePolicyScope,r=await du({walletSession:{walletId:Ie(e.pending.walletId),walletSessionUserId:String(e.pending.walletId)},authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:e.pending.walletAuthMethodId},relayUrl:e.relayerUrl,groupId:oe,routePlan:iu({freshRouteFamily:`login`,operation:We}),workerCtx:e.signingSurface.getSignerWorkerContext(),verification:{kind:`otp`,challengeId:e.exactMethod.challengeId,otpCode:e.exactMethod.otpCode},runtimePolicyScope:n,ecdsaSessionHandleBinding:{keyHandle:t.keyHandle,authSubjectId:e.pending.auth.providerSubject,operation:`wallet_unlock`,chainTarget:t.chainTarget},ecdsaSessionPolicy:zu({keyHandle:t.keyHandle,sessionPolicy:e.sessionPolicy,runtimePolicyScope:n})});if(r.operation!==`wallet_unlock`)throw Error(`Email OTP ECDSA registration unlock returned the wrong operation`);return Uu({pending:e.pending,response:e.response,session:r.ecdsaSession,walletKey:t}),Wu({pending:e.pending,response:e.response,walletKeys:e.walletKeys,signers:r.ecdsaCustody.continuity.signers}),{kind:`email_otp`,session:r.ecdsaSession,readyStateBlobB64u:r.ecdsaCustody.readyStateBlobB64u,publicFacts:r.ecdsaCustody.publicFacts}}async function Ju(e){switch(e.exactMethod.kind){case`passkey`:return await Ku({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,pending:e.pending,response:e.response,walletKeys:e.walletKeys,exactMethod:e.exactMethod,signingSurface:e.signingSurface});case`email_otp`:return await qu({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,pending:e.pending,response:e.response,walletKeys:e.walletKeys,exactMethod:e.exactMethod,signingSurface:e.signingSurface});default:throw e.exactMethod,Error(`Unsupported pending registration unlock method: ${String(e.exactMethod)}`)}}const Yu={listPendingWalletRegistrationCommits:Xu,completeWalletRegistrationNearProvisioning:Qn,publishPendingWalletRegistrationCommit:Zu};async function Xu(){return await V.initialize(),await V.listPendingWalletRegistrationCommits()}async function Zu(e){return await V.publishPendingWalletRegistrationCommit(e)}function Qu(e){return e instanceof Error?e:Error(String(e||`pending registration replay failed`))}function $u(e){return e.operation===`near_provisioning`&&e.phase===`joined`}function ed(e,t){let n=e.localMaterial.ed25519.metadata,r=e.localMaterial.ed25519.localMaterial;return{binding:{kind:Qe,applicationBindingDigestB64u:r.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,participantIds:n.participantIds,stateEpoch:n.stateEpoch,walletId:String(t.walletId),nearAccountId:t.ed25519.nearAccountId,nearEd25519SigningKeyId:t.ed25519.nearEd25519SigningKeyId,signerSlot:t.ed25519.signerSlot,signingWorkerId:n.signingWorkerId,signingWorkerVerifyingShareB64u:n.signingWorkerVerifyingShareB64u},sealed:{ciphertextB64u:r.b64u,nonceB64u:r.nonceB64u}}}function td(e){let t=R(e.localMaterial.ed25519.metadata.registeredPublicKeyB64u);if(t.length!==32)throw Error(`pending registration has an invalid Ed25519 registered public key`);return`ed25519:${Ee(t)}`}function nd(e,t,n){let r=e.localMaterial.ed25519.metadata,i=e.localMaterial.custodyCommit;if(e.auth.kind===`passkey`){if(nl({clientPublicKey:n,finalized:t,expectedRpId:e.auth.rpId,expectedWalletId:e.walletId}).credentialIdB64u!==e.auth.credentialIdB64u)throw Error(`pending registration returned a different Passkey credential`)}else rl({clientPublicKey:n,finalized:t,expectedRegistrationAuthorityId:e.auth.registrationAuthorityId,expectedWalletId:e.walletId});if(t.foundingAuthMethod.walletAuthMethodId!==e.walletAuthMethodId||t.foundingAuthMethod.walletId!==e.walletId||t.foundingAuthority.walletId!==e.walletId||t.ed25519.signerSlot!==r.signerSlot||t.ed25519.nearEd25519SigningKeyId!==r.nearEd25519SigningKeyId||t.ed25519.participantIds[0]!==r.participantIds[0]||t.ed25519.participantIds[1]!==r.participantIds[1]||t.ed25519.routerAbNormalSigning.signingWorkerId!==r.signingWorkerId||t.ed25519.relayerKeyId!==t.ed25519.routerAbNormalSigning.signingWorkerId||t.custodyKeyManifestDigestB64u!==i.keyManifestDigestB64u||i.registeredPublicKeyB64u!==void 0&&i.registeredPublicKeyB64u!==r.registeredPublicKeyB64u)throw Error(`pending registration does not match the committed NEAR projection`);Cn(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function rd(e,t){let n=t.registrationEstablishedSession.session,r=n.tokens.kind===`near_ed25519`||n.tokens.kind===`near_ed25519_and_evm_family_ecdsa`?n.tokens.ed25519:null,i=e.localMaterial.ed25519.metadata;if(n.walletId!==e.walletId||!r||r.nearAccountId!==t.ed25519.nearAccountId||r.nearEd25519SigningKeyId!==t.ed25519.nearEd25519SigningKeyId||r.routerAbNormalSigning.signingWorkerId!==i.signingWorkerId||!p(r.materialActivation,i.materialActivation))throw Error(`pending registration does not match the committed Wallet Session projection`)}function id(e,t){rd(e,t);let n=t.registrationEstablishedSession;if(n.kind===`issued`){if(n.session.walletSession.walletId!==e.walletId||n.session.walletSession.authMethodId!==e.walletAuthMethodId)throw Error(`pending registration issued a Wallet Session for another auth method`);return}if(n.next!==`unlock_exact_method`)throw Error(`pending registration replay has an invalid continuation`)}function ad(e,t,n){if(!t.ok||t.kind!==`near_ed25519`)throw Error(t.ok?`pending registration replay returned a different signer branch`:`pending registration replay failed: ${t.code}`);if(t.walletCustody?.status!==n)throw Error(`pending registration replay did not commit the expected wallet custody`);return nd(e,t,td(e)),t}function od(e,t){let n=ad(e,t,e.signerPlanKind===`near_ed25519`?`committed`:`joined`);if(e.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&(n.registrationEstablishedSession.kind!==`already_committed`||n.registrationEstablishedSession.session.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`))throw Error(`NEAR completion must extend the committed ECDSA session`);return id(e,n),n}async function sd(e,t){let n=td(e),r={walletId:e.walletId,nearAccountId:z(t.ed25519.nearAccountId),nearEd25519SigningKeyId:t.ed25519.nearEd25519SigningKeyId,signerSlot:t.ed25519.signerSlot,operationalPublicKey:n,relayerKeyId:t.ed25519.relayerKeyId,keyVersion:t.ed25519.keyVersion,participantIds:t.ed25519.participantIds,custodyMaterial:ed(e,t)};if(e.auth.kind===`passkey`){if(t.authMethod.kind!==`passkey`)throw Error(`pending Passkey registration replay returned a non-Passkey auth method`);return $e({...r,rpId:e.auth.rpId,credentialIdB64u:e.auth.credentialIdB64u,credentialPublicKeyB64u:t.authMethod.credentialPublicKeyB64u,transports:e.auth.transports})}if(t.authMethod.kind!==`email_otp`)throw Error(`pending Email OTP registration replay returned a non-Email OTP auth method`);let i=lt(t.authority);if(!i)throw Error(`pending Email OTP registration replay returned an invalid authority`);return await tt({...r,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:i})}function cd(e,t,n){return{pending:e,authority:t.authority,foundingAuthority:{authority:t.foundingAuthority,authMethod:t.foundingAuthMethod},request:{operation:e.operation,registrationCeremonyId:e.registrationCeremonyId,idempotencyKey:e.idempotencyKey,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId},ecdsaContinuity:[],walletSessionPublication:t.registrationEstablishedSession.kind===`issued`?{kind:`issued`,walletSession:t.registrationEstablishedSession.session.walletSession,operationCredential:t.registrationEstablishedSession.session.operationCredential}:{kind:`credential_free_projection`,walletSession:t.registrationEstablishedSession.session.walletSession},registration:n}}function ld(e){switch(e.auth.kind){case`passkey`:return{kind:`passkey`};case`email_otp`:return{kind:`email_otp`,enrollment:e.auth.enrollment};default:throw e.auth,Error(`pending registration has an unsupported auth method`)}}function ud(e,t){return{relayerUrl:e,registrationCeremonyId:t.registrationCeremonyId,signedSetup:t.signedSetup,idempotencyKey:t.idempotencyKey,ed25519:{activationReference:t.localMaterial.ed25519.activationReference},auth:ld(t),walletCustodyCommit:t.localMaterial.custodyCommit}}async function dd(e){let t=ud(e.relayerUrl,e.pending),n=await e.ports.completeWalletRegistrationNearProvisioning(t);return od(e.pending,n)}async function fd(e){let t=await Qn({...ud(e.relayerUrl,e.pending),headers:te(e.operationCredential)}),n=od(e.pending,t),r=n.registrationEstablishedSession.session;if(r.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`Persisted mixed registration has no NEAR session`);let i=r.tokens.ed25519,a=Ut({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:e.pending.walletId,nearAccountId:n.ed25519.nearAccountId,nearEd25519SigningKeyId:n.ed25519.nearEd25519SigningKeyId,signerSlot:n.ed25519.signerSlot,thresholdSessionId:i.thresholdSessionId,signingWorkerId:n.ed25519.routerAbNormalSigning.signingWorkerId,participantIds:n.ed25519.participantIds});if(!a.ok)throw Error(a.message);let o=await fetch(`${e.relayerUrl.replace(/\/$/,``)}${Vt}`,{method:`POST`,headers:{...te(e.operationCredential),"Content-Type":`application/json`},body:JSON.stringify(a.value)}),s=await o.json();if(!o.ok||!s||typeof s!=`object`)throw Error(`Persisted NEAR registration activation is unavailable`);let c=Jr(Reflect.get(s,`capability`)),l=e.pending.localMaterial.ed25519.metadata;if(c.registrationContinuity.kind!==`registration`||c.applicationBinding.wallet_id!==e.pending.walletId||c.applicationBinding.near_ed25519_signing_key_id!==l.nearEd25519SigningKeyId||c.lifecycle.lifecycleId!==e.pending.localMaterial.ed25519.activationReference.lifecycle_id||c.lifecycle.thresholdSessionId!==i.thresholdSessionId||c.lifecycle.signingWorkerId!==l.signingWorkerId||c.applicationBinding.key_creation_signer_slot!==l.signerSlot||L(Uint8Array.from(c.registeredPublicKey))!==l.registeredPublicKeyB64u||!p(c.materialActivation,l.materialActivation))throw Error(`Persisted NEAR registration activation changed identity`);let u=c.registrationContinuity;return{joined:{commitPayload:e.pending.localMaterial.custodyCommit,activationReference:e.pending.localMaterial.ed25519.activationReference,localMaterial:e.pending.localMaterial.ed25519.localMaterial,metadata:ma({material:ed(e.pending,n),activation:{materialActivation:c.materialActivation,lifecycleId:c.lifecycle.lifecycleId,signingRootVersion:c.lifecycle.rootShareEpoch,signingRootId:c.applicationBinding.signing_root_id,signerSetId:c.lifecycle.signerSetId,thresholdSessionId:c.lifecycle.thresholdSessionId,activationTranscriptB64u:L(Uint8Array.from(u.activationTranscript)),activationCapabilityBindingB64u:L(Uint8Array.from(c.activeCapabilityBinding))}})},admissionRequest:u.admissionRequest,admissionReceipt:u.admissionReceipt}}async function pd(e){let t=await dd(e),n=await sd(e.pending,t);return await e.ports.publishPendingWalletRegistrationCommit(cd(e.pending,t,n)),{kind:`published`,registrationCeremonyId:e.pending.registrationCeremonyId}}async function md(e){let t=e.ports||Yu,n=await t.listPendingWalletRegistrationCommits(),r=[];for(let i of n){if(ol(i)||sl(i)){r.push({kind:`unlock_required`,registrationCeremonyId:i.registrationCeremonyId,keyFamilies:i.localMaterial.keyFamilies,next:`unlock_exact_method`,reason:`ecdsa_local_finalization`});continue}if(i.operation===`near_provisioning`&&i.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){r.push({kind:`unlock_required`,reason:`near_provisioning`,registrationCeremonyId:i.registrationCeremonyId,next:`unlock_exact_method`});continue}if($u(i))try{r.push(await pd({relayerUrl:e.relayerUrl,pending:i,ports:t}))}catch(e){r.push({kind:`failed`,registrationCeremonyId:i.registrationCeremonyId,error:Qu(e)})}}return r}const hd={activateWalletRegistration:Yn,publishPendingWalletRegistrationCommit:Zu,unlockPendingEcdsaRegistration:Ju};async function gd(e){await V.initialize();let t=null;for(let n of await V.listPendingWalletRegistrationCommits())if(!(n.operation!==`registration_activate`||n.walletId!==e)){if(t)throw Error(`wallet has multiple pending registration activations`);t=n}if(!t)return null;if(!ol(t)&&!sl(t))throw Error(`pending registration commit is not ECDSA-enabled`);return t}async function _d(e){if(e.pending.auth.kind!==e.exactMethod.kind)throw Error(`pending registration requires its exact authentication method`);return await jl({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,pending:e.pending,exactMethod:e.exactMethod,signingSurface:e.signingSurface,ports:hd,nearContext:e.nearContext,nearCompletion:e.nearCompletion,onEvent:e.onEvent})}async function vd(e){let t=performance.now();mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:`started`,startedAtMs:t});try{let n=await e.signingEngine.scheduleRouterAbEcdsaDerivationLoginPresignaturePrefill({walletId:e.walletId,chainTarget:e.chainTarget},e.statusReads);mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:n.status,reason:n.reason,scheduleReason:`schedule`in n?n.schedule.reason:null,walletSessionId:n.walletSessionId,durationMs:performance.now()-t})}catch{mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:`failed`,reason:`unexpected_error`,durationMs:performance.now()-t})}}const yd=new Map,bd=new Set;function xd(e,t){for(let n of bd)try{n(e,t)}catch{}}function Sd(e,t){let n=String(e),r=yd.get(n);if(r)return r;let i={state:{status:`near_pending`,updatedAtMs:t},inFlight:null};return yd.set(n,i),i}function Cd(e){return yd.get(String(e))?.state??null}async function wd(e){let t=yd.get(String(e));return t?t.inFlight?await t.inFlight:t.state:null}function Td(e,t){let n=Sd(e,t.updatedAtMs);n.state.status===`near_ready`&&t.status!==`near_ready`||(n.state=t,xd(e,t))}function Ed(e){return bd.add(e),()=>{bd.delete(e)}}function Dd(e){let t=Sd(e.walletId,e.nowMs());if(t.inFlight)return t.inFlight;if(t.state.status===`near_ready`)return Promise.resolve(t.state);Td(e.walletId,{status:`near_provisioning`,updatedAtMs:e.nowMs()});let n=(async()=>{try{return await e.attempt()}catch(t){return{status:`near_failed_retryable`,updatedAtMs:e.nowMs(),error:t instanceof Error?t.message:String(t),errorCode:`near_provisioning_failed`}}})().then(n=>(t.inFlight=null,Td(e.walletId,n),n));return t.inFlight=n,n}function Od(e){let t=e.registration;if(t.mode!==`managed`)return;let n=String(t.projectEnvironmentId||``).trim(),r=String(t.publishableKey||``).trim();if(!(!n||!r))return{projectEnvironmentId:n,publishableKey:r}}async function kd(e){let t=(await V.listWalletAuthMethodsV2ForWallet(String(e.walletId))).filter(t=>t.kind===`passkey`&&t.status===`active`&&t.walletId===e.walletId&&String(t.rpId)===e.rpId&&String(t.credentialIdB64u)===e.credentialIdB64u),[n]=t;if(t.length!==1||!n)throw Error(`passkey authority requires one exact active V2 auth method`);return n}async function Ad(e){let t=await kd(e);return await ct({authority:{walletId:t.walletId,factor:{kind:`passkey`,credentialIdB64u:t.credentialIdB64u},verifier:{kind:`webauthn`,rpId:t.rpId},bindingId:t.walletAuthMethodId}})}const jd=[`walletId`,`envelopeId`,`factor`,`envelopeRevision`,`binding`,`ownership`];function Md(e){let t=Nd(e.replacement.envelopeBindingJson);if(t.walletId!==e.expectedWalletId)throw Error(`recovery replacement envelope changed the wallet identity`);if(t.envelopeId!==e.replacement.envelopeId)throw Error(`recovery replacement envelope changed the envelope identity`);let n=$t({kind:an,envelopeId:t.envelopeId,walletId:t.walletId,binding:t.binding,factor:t.factor,ownership:en(t.ownership,`recoveryReplacementEnvelope.binding.ownership`),envelopeVersion:an,envelopeRevision:t.envelopeRevision,nonceB64u:e.replacement.envelopeNonceB64u,sealedCustodySecretB64u:e.replacement.sealedCustodySecretB64u,ciphertextDigestB64u:e.replacement.envelopeCiphertextDigestB64u,aadHashB64u:e.replacement.envelopeAadHashB64u,lifecycle:{state:`active`,activatedAtMs:e.activatedAtMs},createdAtMs:e.activatedAtMs,updatedAtMs:e.activatedAtMs},`recoveryReplacementEnvelope`);if(n.binding.kind!==`wallet_custody_seed_v1`)throw Error(`custody envelope must seal the wallet custody seed`);return n}function Nd(e){let t;try{t=JSON.parse(e)}catch{throw Error(`recovery replacement envelope binding is not JSON`)}let n=E(t,`recoveryReplacementEnvelope.binding`);return N(n,jd,`recoveryReplacementEnvelope.binding`),n}const Pd=`passkeyCustodyEnvelopeCacheV1`,Fd=`passkey_custody_envelope_cache_v1`;let Id={kind:`unconfigured`};const Ld=new Map;function Rd(e){throw Error(`unknown passkey custody session cache persistence state: ${String(e)}`)}function zd(){switch(Id.kind){case`configured`:return Id.persistence;case`unconfigured`:throw Error(`passkey custody session cache persistence is not configured`);default:return Rd(Id)}}function Bd(e){Id={kind:`configured`,persistence:e}}function Vd(e,t){let n=String(e||``).trim(),r=String(t||``).trim();if(!n||!r)throw Error(`passkey custody session identity is required`);return`${n}:${r}`}function Hd(){return{kind:Fd,envelopes:[]}}function Ud(e){if(e==null)return Hd();if(typeof e!=`object`||Array.isArray(e))throw Error(`passkey custody envelope cache is invalid`);let t=e;if(t.kind!==Fd||!Array.isArray(t.envelopes))throw Error(`passkey custody envelope cache has an invalid shape`);return{kind:Fd,envelopes:t.envelopes.map(e=>{let t=$t(e);if(!tn(t.binding))throw Error(`generic passkey custody cache cannot contain an Ed25519 export root`);return t})}}async function Wd(){return Ud(await zd().readCacheEntry(Pd))}async function Gd(e){await zd().writeCacheEntry(Pd,e)}async function Kd(e){if(e.envelope.lifecycle.state!==`active`)throw Error(`passkey custody session envelope is not active`);if(!tn(e.envelope.binding))throw Error(`generic passkey custody cache accepts wallet custody seeds only`);if(String(e.envelope.walletId)!==String(e.walletId)||e.envelope.factor.kind!==`passkey`||String(e.envelope.factor.credentialIdB64u)!==String(e.credentialIdB64u))throw Error(`passkey custody session envelope identity changed`);let t=Vd(String(e.walletId),String(e.credentialIdB64u));Ld.set(t,e.envelope);let n=(await Wd()).envelopes.filter(e=>e.factor.kind!==`passkey`||Vd(String(e.walletId),String(e.factor.credentialIdB64u))!==t);n.push(e.envelope),await Gd({kind:Fd,envelopes:n.slice(-32)})}async function qd(e){let t=Vd(String(e.walletId),String(e.credentialIdB64u)),n=Ld.get(t);if(n)return n;let r=(await Wd()).envelopes.find(e=>e.lifecycle.state===`active`&&e.factor.kind===`passkey`&&Vd(String(e.walletId),String(e.factor.credentialIdB64u))===t);return r?(Ld.set(t,r),r):null}function Jd(e){return Math.max(0,Math.round(performance.now()-e))}function Yd(){return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:0,workerRequestRoundTripMs:0,workerResponseValidationMs:0,requestSetupMs:0,promptUserMs:0,promptElementDefineMs:0,promptMountMs:0,promptHostFirstUpdateMs:0,promptHostInteractiveMs:0,promptConfirmEventMs:0,promptDecisionWaitMs:0,credentialCreateStartMs:0,credentialCreateMs:0,credentialSerializeMs:0,duplicateRetryCount:0,mainThreadTotalMs:0}}function Xd(e){let t=performance.now(),n=wl(e.credential,`Passkey registration authority`),r=Jd(t),i=performance.now(),a=Rn(e.credential),o=Jd(i);return{kind:`passkey`,credential:e.credential,webauthnRegistration:a,prfFirstB64u:n,diagnostics:{kind:`passkey_registration_authority_diagnostics_v1`,requestConfirmationMs:e.requestConfirmationMs,prfExtractionMs:r,credentialRedactionMs:o,confirmationWorkerReadyMs:e.diagnostics.workerReadyMs,confirmationWorkerRequestRoundTripMs:e.diagnostics.workerRequestRoundTripMs,confirmationWorkerResponseValidationMs:e.diagnostics.workerResponseValidationMs,confirmationRequestSetupMs:e.diagnostics.requestSetupMs,confirmationPromptUserMs:e.diagnostics.promptUserMs,confirmationPromptElementDefineMs:e.diagnostics.promptElementDefineMs,confirmationPromptMountMs:e.diagnostics.promptMountMs,confirmationPromptHostFirstUpdateMs:e.diagnostics.promptHostFirstUpdateMs,confirmationPromptHostInteractiveMs:e.diagnostics.promptHostInteractiveMs,confirmationPromptConfirmEventMs:e.diagnostics.promptConfirmEventMs,confirmationPromptDecisionWaitMs:e.diagnostics.promptDecisionWaitMs,confirmationCredentialCreateStartMs:e.diagnostics.credentialCreateStartMs,confirmationCredentialCreateMs:e.diagnostics.credentialCreateMs,confirmationCredentialSerializeMs:e.diagnostics.credentialSerializeMs,confirmationDuplicateRetryCount:e.diagnostics.duplicateRetryCount,confirmationMainThreadTotalMs:e.diagnostics.mainThreadTotalMs}}}async function Zd(e){let t=performance.now();return Xd({credential:await e,diagnostics:Yd(),requestConfirmationMs:Jd(t)})}async function Qd(e){let t=performance.now(),n=await e.context.signingEngine.requestRegistrationCredentialConfirmation({walletId:e.walletId,signerSlot:e.signerSlot,confirmerText:e.options.confirmerText,confirmationConfigOverride:e.confirmationConfigOverride,challengeB64u:e.registrationIntentDigestB64u}),r=Jd(t),i=n.registrationDiagnostics??Yd();return Xd({credential:n.credential,diagnostics:i,requestConfirmationMs:r})}function $d(e){let t=e.trim();if(!t)throw Error(`Registration finalize idempotency key is required`);return t}function ef(e){let t=l(e.materialActivation);if(!t.ok)throw Error(`Email OTP Ed25519 material activation is invalid`);let n=String(e.nearAccountId||``).trim(),r=String(e.operationalPublicKey||``).trim(),i=String(e.thresholdSessionId||``).trim(),a=Number(e.signerSlot);if(!n||!r||!i)throw Error(`Email OTP Ed25519 signer identity is incomplete`);if(!Number.isSafeInteger(a)||a<1)throw Error(`Email OTP Ed25519 signer slot is invalid`);let o=ae(e.runtimePolicyScope);if(!o)throw Error(`Email OTP Ed25519 runtime policy scope is invalid`);return{materialActivation:t.value,nearAccountId:n,signerSlot:a,operationalPublicKey:r,thresholdSessionId:i,runtimePolicyScope:o}}function tf(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Email OTP Ed25519 signer selection must be an object`);let t=e;if(t.kind===`absent`)return{kind:`absent`};if(t.kind!==`present`)throw Error(`Email OTP Ed25519 signer selection kind is invalid`);return{kind:`present`,...ef(t)}}function nf(e){let t=of(e,`wallet/email-otp/challenge signerSelection`);if(t.kind===`ed25519_only`)return{kind:`ed25519_only`,...ef(t)};if(t.kind!==`ecdsa`)throw Error(`wallet/email-otp/challenge signerSelection kind is invalid`);return{kind:`ecdsa`,keyHandle:Z(t.keyHandle,`wallet/email-otp/challenge keyHandle`),runtimePolicyScope:I(t.runtimePolicyScope),ed25519:tf(t.ed25519)}}var rf=class extends Error{code;status;retryAfterMs;resetAtMs;constructor(e){super(e.message),this.name=`EmailOtpRouteError`;let t=sf(e.code);t&&(this.code=t),this.status=e.status;let n=Number(e.retryAfterMs);Number.isFinite(n)&&n>=0&&(this.retryAfterMs=Math.floor(n));let r=Number(e.resetAtMs);Number.isFinite(r)&&r>=0&&(this.resetAtMs=Math.floor(r))}};function af(e){let t=e||globalThis.fetch;if(typeof t!=`function`)throw Error(`fetch is unavailable in this runtime`);return t}function of(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} returned invalid JSON`);return e}function Z(e,t){return T(e,t)}function sf(e){return v(e)}function cf(e){let t={"Content-Type":`application/json`},n=String(e.publishableKey||``).trim();return n&&(t.Authorization=`Bearer ${n}`),t}function lf(e){return e.routeFamily===`registration`?eu({routeFamily:`registration`,operation:He}):eu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function uf(e){let t=sf(e.challenge.action);if(t&&t!==e.expectedAction)throw Error(`${e.context} returned ${t}; expected ${e.expectedAction}`)}async function df(e){let t=await af(e.fetchImpl)(e.url,{method:`POST`,headers:cf({publishableKey:e.publishableKey}),credentials:`include`,body:JSON.stringify(e.body)}),n=await t.text(),r=null;try{r=n?JSON.parse(n):null}catch{throw Error(`${e.url} returned non-JSON response (HTTP ${t.status})`)}let i=of(r,e.url);if(!t.ok||i.ok===!1)throw new rf({message:typeof i.message==`string`&&i.message.trim()||`${e.url} failed (HTTP ${t.status})`,status:t.status,code:i.code,retryAfterMs:i.retryAfterMs,resetAtMs:i.resetAtMs});return i}async function ff(e){if(e.restartRegistrationOffer===!0&&e.accountMode!==`register`)throw Error(`restartRegistrationOffer is only valid with register account mode`);let t=await df({url:i(e.relayUrl,`/auth/google/verify`),fetchImpl:e.fetchImpl,publishableKey:Z(e.publishableKey,`publishableKey`),body:{id_token:Z(e.idToken,`idToken`),account_mode:e.accountMode,project_environment_id:Z(e.projectEnvironmentId,`projectEnvironmentId`),...e.loginWalletId?{wallet_id:Z(e.loginWalletId,`loginWalletId`)}:{},...e.restartRegistrationOffer===!0?{restart_registration_offer:!0}:{}}}),n=Z(t.mode,`auth/google/verify mode`),r=Z(t.walletId,`auth/google/verify walletId`),a=Z(t.providerSubject,`auth/google/verify providerSubject`),o=sf(t.email);if(n===`existing_wallet`){if(t.hasEmailOtpEnrollment!==!0)throw Error(`auth/google/verify existing wallet is missing Email OTP enrollment`);if(!o)throw Error(`auth/google/verify existing wallet is missing email`);return{mode:n,walletId:r,providerSubject:a,email:o,hasEmailOtpEnrollment:!0}}if(n!==`register_started`)throw Error(`auth/google/verify returned unsupported mode: ${n}`);if(!o)throw Error(`auth/google/verify registration is missing email`);let s=of(t.offer,`auth/google/verify offer`),c=(Array.isArray(s.candidates)?s.candidates:[]).map(pf),l=c[0];if(!l)throw Error(`auth/google/verify offer has no wallet candidates`);return{mode:n,walletId:r,providerSubject:a,email:o,registrationAttemptId:Z(t.registrationAttemptId,`auth/google/verify registrationAttemptId`),expiresAtMs:mf(t.expiresAtMs,`auth/google/verify expiresAtMs`),offer:{offerId:Z(s.offerId,`auth/google/verify offer.offerId`),selectedCandidateId:Z(s.selectedCandidateId,`auth/google/verify offer.selectedCandidateId`),candidates:[l,...c.slice(1)]}}}function pf(e){let t=of(e,`auth/google/verify offer candidate`);return{candidateId:Z(t.candidateId,`offer candidate candidateId`),walletId:Z(t.walletId,`offer candidate walletId`)}}function mf(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<=Date.now())throw Error(`${t} must be a future timestamp`);return n}async function hf(e){let t=e.operation??`wallet_unlock`;if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpChallenge`,payload:{relayUrl:Z(e.relayUrl,`relayUrl`),walletId:Z(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Z(e.walletAuthMethodId,`walletAuthMethodId`)}:{},routePlan:lf({routeFamily:`login`,operation:t}),otpChannel:Ke,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}});let n=await df({url:i(e.relayUrl,`/wallet/email-otp/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Z(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Z(e.walletAuthMethodId,`walletAuthMethodId`)}:{},otpChannel:e.otpChannel||`email_otp`,operation:t,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}),r=of(n.challenge,`wallet/email-otp/challenge`);uf({challenge:r,expectedAction:Ve.login,context:`wallet/email-otp/challenge`});let a=Ht(n.delivery,`wallet/email-otp/challenge delivery`),o=Number(r.expiresAtMs),s={challengeId:Z(r.challengeId,`wallet/email-otp/challenge challengeId`),otpChannel:Ke,delivery:a,emailHint:a.emailHint,ownerProofBindingDigest:Z(r.ownerProofBindingDigest,`wallet/email-otp/challenge ownerProofBindingDigest`),walletAuthMethodId:Z(n.walletAuthMethodId,`wallet/email-otp/challenge walletAuthMethodId`),signerSelection:nf(n.signerSelection)};return Number.isFinite(o)&&(s.expiresAtMs=o),s}async function gf(e){if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpEnrollmentChallenge`,payload:{relayUrl:Z(e.relayUrl,`relayUrl`),walletId:Z(e.walletId,`walletId`),routePlan:lf({routeFamily:`registration`}),otpChannel:Ke}}});let t=await df({url:i(e.relayUrl,`/wallet/email-otp/registration/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Z(e.walletId,`walletId`),otpChannel:e.otpChannel||`email_otp`}}),n=of(t.challenge,`wallet/email-otp/registration/challenge`);uf({challenge:n,expectedAction:Ve.registration,context:`wallet/email-otp/registration/challenge`});let r=Ht(t.delivery,`wallet/email-otp/registration/challenge delivery`),a=Number(n.expiresAtMs),o={challengeId:Z(n.challengeId,`wallet/email-otp/registration/challenge challengeId`),otpChannel:Ke,delivery:r,emailHint:r.emailHint};return Number.isFinite(a)&&(o.expiresAtMs=a),o}function _f(e,t){let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`${t} is required for Email OTP registration authority`);return n}async function vf(e){let t=_f(e.authMethod.email,`email`).toLowerCase(),n=_f(e.authMethod.providerSubject,`providerSubject`),r=_f(e.relayUrl,`relayUrl`),i=_f(e.walletId,`walletId`),a=_f(e.registrationIntentDigestB64u,`registrationIntentDigestB64u`);if(e.authMethod.proofKind===`google_sso_registration`){let r=_f(e.authMethod.googleEmailOtpRegistrationAttemptId,`googleEmailOtpRegistrationAttemptId`);return{kind:`email_otp`,proof:{version:`email_otp_registration_proof_v1`,proofKind:`google_sso_registration`,providerSubject:n,email:t,googleEmailOtpRegistrationAttemptId:r,googleEmailOtpRegistrationOfferId:_f(e.authMethod.googleEmailOtpRegistrationOfferId,`googleEmailOtpRegistrationOfferId`),googleEmailOtpRegistrationCandidateId:_f(e.authMethod.googleEmailOtpRegistrationCandidateId,`googleEmailOtpRegistrationCandidateId`),registrationIntentDigestB64u:a},registrationAuthorityId:r,providerSubject:n,email:t}}let o=_f(e.authMethod.otpCode,`otpCode`),s=typeof e.authMethod.challengeId==`string`?e.authMethod.challengeId.trim():``,c=s?null:await gf({relayUrl:r,walletId:i,fetchImpl:e.fetchImpl}),l=s||_f(c?.challengeId,`challengeId`);return{kind:`email_otp`,proof:{version:`email_otp_registration_proof_v1`,proofKind:`otp_challenge`,providerSubject:n,email:t,challengeId:l,otpCode:o,otpChannel:Ke,registrationIntentDigestB64u:a},registrationAuthorityId:l,providerSubject:n,email:t}}function yf(e,t,n){if(e!==t)throw Error(`${n} does not match the verified add-signer intent`)}function bf(e,t){if(e.length!==2||e[0]!==t[0]||e[1]!==t[1])throw Error(`Yao participant IDs do not match the verified add-signer intent`)}function xf(e){let t=w(e.verifiedIntent.addSignerIntentGrant,`add-signer intent grant`);return{routerOrigin:w(e.httpTransport.routerOrigin,`Yao Router origin`),routing:{kind:`discovery`},authorization:{kind:`bearer`,value:`Bearer ${t}`},fetch:e.httpTransport.fetch}}async function Sf(e){let t=e.verifiedIntent.intent,n=t.signerSelection.ed25519;yf(String(t.walletId),String(e.verifiedAuthority.walletId),`Passkey authority wallet ID`),yf(e.verifiedIntent.addSignerIntentDigestB64u,e.verifiedAuthority.addSignerIntentDigestB64u,`Passkey authority intent digest`),w(e.verifiedAuthority.credentialIdB64u,`passkey credential ID`);let r=I(t.runtimePolicyScope),i=F(r),a=Pt(e.admissionRequest);if(!a.ok)throw Error(a.message);let o=a.value,s=w(e.verifiedIntent.addSignerCeremonyId,`add-signer ceremony ID`);if(yf(o.scope.lifecycle_id,s,`Yao lifecycle ID`),yf(o.scope.threshold_session_id,s,`Yao Threshold Session ID`),yf(o.scope.account_id,String(t.walletId),`Yao account ID`),yf(o.scope.signer_set_id,String(Oe(n.signerSlot)),`Yao signer-set ID`),yf(o.scope.root_share_epoch,r.signingRootVersion,`Yao root-share epoch`),yf(o.application_binding.wallet_id,String(t.walletId),`Yao application wallet ID`),yf(o.application_binding.signing_root_id,i,`Yao signing-root ID`),o.application_binding.key_creation_signer_slot!==n.signerSlot)throw Error(`Yao signer slot does not match the verified add-signer intent`);bf(n.participantIds,o.participant_ids);let c=await Xt({kind:`wallet_add_signer_implicit_near_ed25519_key_v1`,walletId:t.walletId,signingRootId:i,signingRootVersion:r.signingRootVersion,signerSlot:n.signerSlot,participantIds:n.participantIds,keyPurpose:n.keyPurpose,keyVersion:n.keyVersion,derivationVersion:n.derivationVersion});return yf(o.application_binding.near_ed25519_signing_key_id,String(c),`Yao NEAR signing-key ID`),{kind:`prepared_passkey_ed25519_yao_add_signer_v1`,request:o,transportConfig:xf(e)}}async function Cf(e){let t=await Sf(e),n=await new ra(t.transportConfig).send({kind:`admit`,path:At,body:t.request});if(!n.ok)throw Error(n.message);let r=Rt(n.value);if(!r.ok)throw Error(r.message);return{request:t.request,receipt:r.value}}var wf=class e{kind=`restorable_mpc_material_ref`;durableMaterialRef;protocolProof=!0;constructor(e){this.durableMaterialRef=e,this.protocolProof}static build(t){let n=String(t||``).trim();if(!n)throw Error(`Restorable MPC material reference is required`);return new e(n)}};function Tf(e){return wf.build(e)}const Ef=`router_ab_ed25519_yao_active_client_v1`,Df=`chacha20poly1305-hkdf-sha256-prf-first-v1`,Of=(1n<<64n)-1n;function Q(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required for local Ed25519 material`);return n}function kf(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<1)throw Error(`${t} must be a positive safe integer`);return n}function Af(e,t){let n=s(e);if(!n.ok)throw Error(`${t}: ${n.error.message}`);return n.value}function jf(e,t){let n=Q(e,t);if(R(n).length!==32)throw Error(`${t} must encode 32 bytes`);return n}function Mf(e){if(!Array.isArray(e)||e.length!==2)throw Error(`participantIds must contain exactly two entries`);let t=[kf(e[0],`participantIds[0]`),kf(e[1],`participantIds[1]`)];if(t[0]>65535||t[1]>65535||t[0]===t[1])throw Error(`participantIds must contain two distinct u16 identifiers`);return t}function Nf(e,t){let n=Q(e,t);if(!/^(0|[1-9][0-9]*)$/.test(n)||BigInt(n)>Of)throw Error(`${t} must be a canonical u64`);return n}function Pf(e,t,n){let r=e.signingLane.identity.signer;return{walletId:Q(r.account.wallet.walletId,`walletId`),nearAccountId:Q(r.account.nearAccountId,`nearAccountId`),nearEd25519SigningKeyId:Q(r.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),thresholdSessionId:Af(e.signingLane.identity.thresholdSessionId,`thresholdSessionId`),signerSlot:kf(r.signerSlot,`signerSlot`),rpId:Q(t,`rpId`),credentialIdB64u:Q(n,`credentialIdB64u`),signingRootId:Q(e.signingRootId,`signingRootId`),signingRootVersion:Q(e.signingRootVersion,`signingRootVersion`),signingWorkerId:Q(e.routerAbNormalSigning.signingWorkerId,`signingWorkerId`)}}function Ff(e){let t=e.metadata;if(t.scope.account_id!==e.identity.walletId||t.applicationBinding.wallet_id!==e.identity.walletId||t.applicationBinding.near_ed25519_signing_key_id!==e.identity.nearEd25519SigningKeyId||t.scope.threshold_session_id!==e.identity.thresholdSessionId||t.applicationBinding.key_creation_signer_slot!==e.identity.signerSlot||t.applicationBinding.signing_root_id!==e.identity.signingRootId||t.scope.root_share_epoch!==e.identity.signingRootVersion||t.scope.signing_worker_id!==e.identity.signingWorkerId)throw Error(`Active Ed25519 Client metadata does not match the wallet signing lane`);return{kind:Ef,walletId:e.identity.walletId,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot,rpId:e.identity.rpId,credentialIdB64u:e.identity.credentialIdB64u,lifecycleId:Q(t.scope.lifecycle_id,`lifecycleId`),thresholdSessionId:Af(t.scope.threshold_session_id,`thresholdSessionId`),materialActivation:tr(t),signingRootId:e.identity.signingRootId,signingRootVersion:e.identity.signingRootVersion,signerSetId:Q(t.scope.signer_set_id,`signerSetId`),signingWorkerId:e.identity.signingWorkerId,participantIds:[t.participantIds[0],t.participantIds[1]],registeredPublicKeyB64u:L(t.registeredPublicKey),signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare),stateEpoch:t.stateEpoch.toString(10),activationTranscriptB64u:L(t.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(t.activeCapabilityBinding))}}function If(e){return new TextEncoder().encode(JSON.stringify([e.kind,e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,e.rpId,e.credentialIdB64u,e.lifecycleId,e.thresholdSessionId,e.materialActivation.kind,e.materialActivation.activationId,e.materialActivation.capability,e.materialActivation.materialOwner,e.materialActivation.keyBinding,e.materialActivation.lifecycleBinding,e.materialActivation.signingWorker,e.signingRootId,e.signingRootVersion,e.signerSetId,e.signingWorkerId,e.participantIds[0],e.participantIds[1],e.registeredPublicKeyB64u,e.signingWorkerVerifyingShareB64u,e.stateEpoch,e.activationTranscriptB64u,e.activationCapabilityBindingB64u]))}function Lf(e,t){if(e.walletId!==t.walletId||e.nearAccountId!==t.nearAccountId||e.nearEd25519SigningKeyId!==t.nearEd25519SigningKeyId||e.signerSlot!==t.signerSlot||e.rpId!==t.rpId||e.credentialIdB64u!==t.credentialIdB64u||e.signingRootId!==t.signingRootId||e.signingRootVersion!==t.signingRootVersion||e.signingWorkerId!==t.signingWorkerId)throw Error(`Stored Ed25519 Client material does not match the wallet signing lane`)}function Rf(e){let t=C(e);if(!t||t.kind!==Ef)throw Error(`Stored Ed25519 Client material binding is invalid`);let n=l(t.materialActivation);if(!n.ok)throw Error(n.error.message);let r={kind:Ef,walletId:Q(t.walletId,`binding.walletId`),nearAccountId:Q(t.nearAccountId,`binding.nearAccountId`),nearEd25519SigningKeyId:Q(t.nearEd25519SigningKeyId,`binding.nearEd25519SigningKeyId`),signerSlot:kf(t.signerSlot,`binding.signerSlot`),rpId:Q(t.rpId,`binding.rpId`),credentialIdB64u:Q(t.credentialIdB64u,`binding.credentialIdB64u`),lifecycleId:Q(t.lifecycleId,`binding.lifecycleId`),thresholdSessionId:Af(t.thresholdSessionId,`binding.thresholdSessionId`),materialActivation:n.value,signingRootId:Q(t.signingRootId,`binding.signingRootId`),signingRootVersion:Q(t.signingRootVersion,`binding.signingRootVersion`),signerSetId:Q(t.signerSetId,`binding.signerSetId`),signingWorkerId:Q(t.signingWorkerId,`binding.signingWorkerId`),participantIds:Mf(t.participantIds),registeredPublicKeyB64u:jf(t.registeredPublicKeyB64u,`binding.registeredPublicKeyB64u`),signingWorkerVerifyingShareB64u:jf(t.signingWorkerVerifyingShareB64u,`binding.signingWorkerVerifyingShareB64u`),stateEpoch:Nf(t.stateEpoch,`binding.stateEpoch`),activationTranscriptB64u:jf(t.activationTranscriptB64u,`binding.activationTranscriptB64u`),activationCapabilityBindingB64u:jf(t.activationCapabilityBindingB64u,`binding.activationCapabilityBindingB64u`)};if(r.materialActivation.materialOwner!==r.walletId||r.materialActivation.signingWorker!==r.signingWorkerId)throw Error(`Stored Ed25519 Client material activation does not match its binding`);return r}function zf(e,t){let n=Rf(e);return Lf(n,t),n}function Bf(e){let t=C(e);if(!t)throw Error(`Stored Ed25519 Client stable server scope is invalid`);let n=ae(t.runtimePolicyScope);if(!n)throw Error(`Stored Ed25519 Client server runtime policy scope is invalid`);return{relayerKeyId:Q(t.relayerKeyId,`stableServerScope.relayerKeyId`),participantIds:Mf(t.participantIds),runtimePolicyScope:n,routerAbNormalSigning:ce(t.routerAbNormalSigning)}}async function Vf(e){let t=e.stored.payload,n=C(t);if(!n)throw Error(`Stored Ed25519 Client local material locator is invalid`);let r=Rf(n.binding),i=`ed25519:${Ee(R(r.registeredPublicKeyB64u))}`,a=e.stored.payloadEnvelope;if(e.stored.profileId!==e.target.profileId||e.stored.chainIdKey!==e.target.chainIdKey||e.stored.accountAddress!==e.target.accountAddress||e.stored.keyKind!==Ef||e.stored.schemaVersion!==3||e.stored.publicKey!==i||e.stored.signerId!==r.nearEd25519SigningKeyId||a?.encVersion!==1||a.alg!==Df)throw Error(`Stored Ed25519 Client local material record is invalid`);let o=xt({walletId:r.walletId,factor:{kind:`passkey`,credentialIdB64u:r.credentialIdB64u},verifier:{kind:`webauthn`,rpId:r.rpId},bindingId:e.authority.walletAuthMethodId});if(!o)throw Error(`Stored Ed25519 Client local material authority is invalid`);let s=await ct({authority:o});if(s.authorityDigest!==e.authority.authorityDigest)throw Error(`Stored Ed25519 Client local material authority changed`);return{kind:`passkey_ed25519_yao_local_material_locator_v1`,authority:s,materialActivation:r.materialActivation,sealedMaterial:Tf(JSON.stringify([e.stored.profileId,e.stored.signerSlot,e.stored.chainIdKey,e.stored.keyKind,r.materialActivation.activationId])),stableServerScope:Bf(n.stableServerScope)}}function Hf(e){let t=C(e.stored.payload?.binding);if(e.stored.profileId!==e.target.profileId||e.stored.chainIdKey!==e.target.chainIdKey||e.stored.accountAddress!==e.target.accountAddress||e.stored.signerSlot!==e.input.signerSlot||e.stored.signerId!==e.input.nearEd25519SigningKeyId||e.stored.keyKind!==Ef||t?.kind!==Ef||t.walletId!==e.input.walletId||t.nearAccountId!==e.input.nearAccountId||t.nearEd25519SigningKeyId!==e.input.nearEd25519SigningKeyId||t.signerSlot!==e.input.signerSlot||t.rpId!==e.input.rpId||t.credentialIdB64u!==e.input.credentialIdB64u)throw Error(`Stored Ed25519 Client material locator does not match local custody`)}function Uf(e,t){let n=Q(t,`thresholdSessionId`);return{kind:Ni,scope:{lifecycle_id:e.lifecycleId,root_share_epoch:e.signingRootVersion,account_id:e.walletId,threshold_session_id:n,signer_set_id:e.signerSetId,signing_worker_id:e.signingWorkerId,material_activation:wt(e.materialActivation)},applicationBinding:{wallet_id:e.walletId,near_ed25519_signing_key_id:e.nearEd25519SigningKeyId,signing_root_id:e.signingRootId,key_creation_signer_slot:e.signerSlot},participantIds:e.participantIds,registeredPublicKey:R(e.registeredPublicKeyB64u),signingWorkerVerifyingShare:R(e.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(e.stateEpoch),transcript:R(e.activationTranscriptB64u),activeCapabilityBinding:Array.from(R(e.activationCapabilityBindingB64u)),materialActivation:e.materialActivation}}function Wf(){let e=new Uint8Array(12);return globalThis.crypto.getRandomValues(e),e}function Gf(e){let t=e.identity,n=e.activeClient.metadata(),r=Ff({identity:t,metadata:n}),i=Wf(),a=e.activeClient.sealLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:If(r),nonce:i}),o={binding:r,stableServerScope:e.stableServerScope};switch(e.lifecycle.kind){case`registration_or_rehydration`:break;case`recovery_promotion`:o.lifecycleReceipt=e.lifecycle.promotionReceipt;break;default:e.lifecycle}return{profileId:e.target.profileId,signerSlot:t.signerSlot,chainIdKey:e.target.chainIdKey,accountAddress:e.target.accountAddress,keyKind:Ef,algorithm:`ed25519`,publicKey:`ed25519:${Ee(n.registeredPublicKey)}`,signerId:t.nearEd25519SigningKeyId,payload:o,payloadEnvelope:{encVersion:1,alg:Df,nonce:L(a.nonce),ciphertext:L(a.ciphertext),aad:Ze({profileId:e.target.profileId,signerSlot:t.signerSlot,chainIdKey:e.target.chainIdKey,accountAddress:e.target.accountAddress,keyKind:Ef,schemaVersion:3,signerId:t.nearEd25519SigningKeyId})},timestamp:Date.now(),schemaVersion:3}}async function Kf(e){let t=await bn(e.store,{accountRefs:Bn(e.identity.nearAccountId)});if(!t)throw Error(`Local Ed25519 material requires a persisted wallet profile`);let n=Gf({target:t,activeClient:e.activeClient,identity:e.identity,stableServerScope:e.stableServerScope,ownedPasskeyPrfFirst:R(e.passkeyPrfFirstB64u),lifecycle:{kind:`registration_or_rehydration`}});await e.store.storeKeyMaterial(n)}async function qf(e){let t=Q(e.nearAccountId,`nearAccountId`),n=await bn(e.store,{accountRefs:Bn(t)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,kf(e.signerSlot,`signerSlot`),n.chainIdKey,Ef);return r?(Hf({stored:r,target:n,input:e}),{kind:`available`,locator:await Vf({stored:r,target:n,authority:e.authority})}):{kind:`unavailable`}}function Jf(e){return e.publicLocator.walletId===e.identity.walletId&&e.publicLocator.nearAccountId===e.identity.nearAccountId&&e.publicLocator.signerSlot===e.identity.signerSlot}async function Yf(e){let t=xt({walletId:e.identity.walletId,factor:{kind:`passkey`,credentialIdB64u:e.identity.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.identity.rpId},bindingId:e.authority.walletAuthMethodId});if(!t)throw Error(`Passkey Ed25519 authority is invalid`);let n=await ct({authority:t});if(n.authorityDigest!==e.authority.authorityDigest)throw Error(`Passkey Ed25519 authority does not match the Wallet Session`);return n}function Xf(e){if(!e||e.activeClient.status().kind!==`active`)return{kind:`absent`};let t=tr(e.activeClient.metadata());return{kind:`live`,runtime:Zn(t),materialActivation:t}}function Zf(e){return{kind:`blocked`,plan:e}}async function Qf(e){let t=await Yf(e),n=e.publicLocator.kind===`available`&&!Jf({publicLocator:e.publicLocator,identity:e.identity})?{kind:`conflict`}:e.publicLocator.kind===`available`?{...e.publicLocator,authority:t}:e.publicLocator,r;try{r=await qf({store:e.store,walletId:String(e.identity.walletId),nearAccountId:String(e.identity.nearAccountId),nearEd25519SigningKeyId:String(e.identity.nearEd25519SigningKeyId),signerSlot:e.identity.signerSlot,rpId:e.identity.rpId,credentialIdB64u:e.identity.credentialIdB64u,authority:t})}catch{return{expectedAuthority:t,publicLocator:n,sealed:{kind:`corrupt`}}}return{expectedAuthority:t,publicLocator:n,sealed:r.kind===`available`?{kind:`available`,authority:r.locator.authority,materialActivation:r.locator.materialActivation,sealedMaterial:r.locator.sealedMaterial}:{kind:`missing`}}}function $f(e,t){let n=$n({publicLocator:e,sealed:{kind:`corrupt`},runtime:t,unlockSource:{kind:`unavailable`}});if(n.kind!==`blocked`)throw Error(`Corrupt Near Ed25519 material resolved to an executable hydration plan`);return n}async function ep(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await Qf(e);if(r.kind===`corrupt`)return{kind:`blocked`,plan:$f(n,{kind:`absent`})};let i=$n({publicLocator:n,sealed:r,runtime:{kind:`absent`},unlockSource:{kind:`available`,authority:t}});switch(i.kind){case`rehydrate_material_activation`:return{kind:`prepared`,plan:i};case`blocked`:return{kind:`blocked`,plan:i};case`use_live_runtime`:case`reauthorize_public_anchor`:throw Error(`Sealed Near Ed25519 preparation resolved an invalid hydration plan`);default:throw Error(`Unsupported sealed Near Ed25519 preparation plan`)}}async function tp(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await Qf(e);if(r.kind===`corrupt`)return Zf($f(n,Xf(e.liveMaterial)));let i=e.unlockSource.kind===`available`?{kind:`available`,authority:t}:{kind:`unavailable`},a=$n({publicLocator:n,sealed:r,runtime:Xf(e.liveMaterial),unlockSource:i});switch(a.kind){case`use_live_runtime`:{let t=e.liveMaterial;if(!t||t.activeClient.status().kind!==`active`||!p(a.materialActivation,tr(t.activeClient.metadata())))throw Error(`Near Ed25519 live hydration plan lost its exact runtime`);return{kind:`live`,plan:a}}case`rehydrate_material_activation`:{if(e.unlockSource.kind!==`available`)throw Error(`Near Ed25519 rehydration plan lost its unlock source`);let t=await np({store:e.store,identity:e.identity,passkeyPrfFirstB64u:e.unlockSource.passkeyPrfFirstB64u});if(t.kind!==`rehydrated`)throw Error(`Near Ed25519 rehydration plan lost its sealed material`);let n=tr(t.activeClient.metadata());if(!p(a.materialActivation,n))throw t.activeClient.dispose(),Error(`Near Ed25519 rehydration changed the material activation`);return{kind:`rehydrated`,plan:a,activeClient:t.activeClient}}case`blocked`:return Zf(a);case`reauthorize_public_anchor`:throw Error(`Near Ed25519 material retirement requires explicit reauthorization`);default:throw Error(`Unsupported Near Ed25519 hydration plan`)}}async function np(e){let t=e.identity,n=await bn(e.store,{accountRefs:Bn(t.nearAccountId)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,t.signerSlot,n.chainIdKey,Ef);return r?rp({stored:r,target:n,identity:t,ownedPasskeyPrfFirst:R(e.passkeyPrfFirstB64u)}):{kind:`unavailable`}}async function rp(e){let t=e.identity,n=e.stored,r=e.target,i=n.payloadEnvelope;if(n.profileId!==r.profileId||n.accountAddress!==r.accountAddress||n.signerId!==t.nearEd25519SigningKeyId||n.keyKind!==Ef||n.schemaVersion!==3||i?.encVersion!==1||i.alg!==Df)throw Error(`Stored Ed25519 Client material record is invalid`);let a=zf(n.payload?.binding,t),o=Uf(a,t.thresholdSessionId),s=`ed25519:${Ee(o.registeredPublicKey)}`;if(n.publicKey!==s)throw Error(`Stored Ed25519 Client public key does not match its sealed binding`);return{kind:`rehydrated`,activeClient:(await ua.initializeBundled()).importLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:If(a),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:R(i.nonce),ciphertext:R(i.ciphertext)},metadata:o})}}function ip(e,t){return e.requestWorkerOperation(t)}function ap(e,t,n){return e.requestOperation({kind:`walletCustodyCeremony`,request:{type:t,payload:n}})}function op(e){return ap.bind(void 0,e)}let sp=null,cp=null,lp=null,up=null;function dp(e){up=e}function fp(e){let t=up;if(!t||e.kind!==`unlocked_wallet_ed25519_export_root_capability_v1`)return;let n=e.upgradedEnvelope;if(n!==void 0)try{t({walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,walletSessionId:e.walletSessionId,envelope:n})}catch(e){console.warn(`[walletCustody] the upgraded custody envelope was not forwarded:`,e instanceof Error?e.message:String(e||`unknown error`))}}function pp(e){return{requestOperation:ip.bind(void 0,e)}}function mp(){lp!==null&&(clearTimeout(lp),lp=null)}function hp(){mp(),sp=null,cp=null}function gp(e,t){mp();let n=Math.max(0,e.expiresAtMs-Date.now());lp=setTimeout(()=>{if(lp=null,!(sp!==e||cp!==t)){if(e.expiresAtMs>Date.now()){gp(e,t);return}Cp(t,{kind:`capability`,capabilityHandleId:e.capabilityHandleId})}},Math.min(n,2147483647))}function _p(e){if(!_(e))return null;if(e.kind===`unlocked_linked_device_ed25519_client_root_capability_v1`)return vp(e);let t=Object.keys(e),n=t.includes(`upgradedEnvelope`),r=n?[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`,`upgradedEnvelope`]:[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`];if(t.length!==r.length||t.some(e=>!r.includes(e))||e.kind!==`unlocked_wallet_ed25519_export_root_capability_v1`)return null;let i=u(e.capabilityHandleId),o=a(e.walletId),s=c(e.walletAuthMethodId),l=_e(e.walletSessionId);if(!i.ok||!o.ok||!s.ok||!l.ok)return null;let d;try{d=P(e.expiresAtMs,`unlocked Ed25519 export-root capability expiry`)}catch{return null}let f;if(n)try{f=$t(e.upgradedEnvelope)}catch{}return{kind:`unlocked_wallet_ed25519_export_root_capability_v1`,capabilityHandleId:i.value,walletId:o.value,walletAuthMethodId:s.value,walletSessionId:l.value,expiresAtMs:d,...f?{upgradedEnvelope:f}:{}}}function vp(e){let t=[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`],n=Object.keys(e);if(n.length!==t.length||n.some(e=>!t.includes(e)))return null;let r=u(e.capabilityHandleId),i=a(e.walletId),o=c(e.walletAuthMethodId),s=_e(e.walletSessionId);if(!r.ok||!i.ok||!o.ok||!s.ok)return null;let l;try{l=P(e.expiresAtMs,`unlocked Ed25519 Client-root capability expiry`)}catch{return null}return{kind:`unlocked_linked_device_ed25519_client_root_capability_v1`,capabilityHandleId:r.value,walletId:i.value,walletAuthMethodId:o.value,walletSessionId:s.value,expiresAtMs:l}}async function yp(e,t){let n=t.existingEnvelope.binding;if(!tn(n)&&n.kind!==`ed25519_yao_client_root_v1`)return;let r=t.existingFactorSecret.slice(),i;try{i=await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`establishUnlockedWalletEd25519ExportRootCapability`,payload:{existingEnvelope:t.existingEnvelope,existingFactorSecret:r.buffer,walletId:t.walletId,walletAuthMethodId:t.walletAuthMethodId,walletSessionId:t.walletSessionId,expiresAtMs:t.expiresAtMs},transfer:[r.buffer]}})}finally{r.byteLength>0&&r.fill(0)}let a=_p(i);if(a===null)throw Error(`unlocked Ed25519 export-root capability worker returned no reference`);return mp(),sp=a,cp=e,gp(a,e),fp(a),a}function bp(e){let t=xp(e);return t?.kind===`unlocked_wallet_ed25519_export_root_capability_v1`?t:void 0}function xp(e){let t=sp;if(t&&t.walletId===e){if(t.expiresAtMs<=Date.now()){let e=cp;e?Cp(e,{kind:`capability`,capabilityHandleId:t.capabilityHandleId}):hp();return}return t}}function Sp(){hp()}async function Cp(e,t){let n=sp;n!==null&&(t.kind===`all`||t.kind===`capability`&&t.capabilityHandleId===n.capabilityHandleId||t.kind===`wallet`&&t.walletId===n.walletId||t.kind===`wallet_session`&&t.walletSessionId===n.walletSessionId)&&hp();try{await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`destroyUnlockedWalletEd25519ExportRootCapabilities`,payload:{scope:t}}})}catch{}}function wp(e){let t=r(e);if(!t.ok)throw Error(t.error.message);return t.value}function Tp(e){let t=e.finalized.authMethod;if(!t||t.kind!==`passkey`)throw Error(`Passkey registration finalize returned non-passkey auth material`);let n=String(e.credential.rawId||e.credential.id||``).trim(),r=String(t.credentialIdB64u||``).trim();if(!n||r!==n)throw Error(`Passkey registration finalize returned credential id mismatch`);let i=String(t.credentialPublicKeyB64u||``).trim();if(!i)throw Error(`Passkey registration finalize returned missing credentialPublicKeyB64u`);return i}async function Ep(e){let t=e.configs.signing.emailOtp.authPolicy;return lr({policy:t,retention:`session`,reason:`login`,authority:e.authority})}async function Dp(e){switch(e.authMethod.kind){case`passkey`:if(!e.passkeyAuthority)throw Error(`Passkey registration authority was not collected`);return{kind:`passkey`,rpId:e.authMethod.rpId,credential:e.passkeyAuthority.credential,credentialPublicKeyB64u:Tp({finalized:e.finalized,credential:e.passkeyAuthority.credential})};case`email_otp`:{let t=String(e.email||``).trim(),n=String(e.providerSubject||``).trim(),r=String(e.registrationAuthorityId||``).trim();if(!t||!n||!r)throw Error(`Email OTP registration persistence requires provider identity`);if(!it(e.finalized.authority))throw Error(`Email OTP registration finalize returned a different authority`);if(e.finalized.foundingAuthMethod.kind!==`email_otp`)throw Error(`Email OTP registration finalize returned a different founding method`);let i=lt({...e.finalized.authority,bindingId:e.finalized.foundingAuthMethod.walletAuthMethodId});if(!i)throw Error(`Email OTP registration finalize returned an invalid exact authority`);return{kind:`email_otp`,email:t,registrationAuthorityId:r,emailOtpAuthContext:await Ep({configs:e.configs,authority:i}),authority:i}}default:return q(e.authMethod)}}function Op(e){let[t,...n]=e.walletKeys,[r,...i]=e.expectedChainTargets;if(!t||!r)throw Error(`ECDSA registration persistence requires session, key, and target material`);if(e.walletKeys.length!==e.expectedChainTargets.length)throw Error(`ECDSA registration persistence requires one family session projected to every target`);if(e.session.chainTargets.length!==e.expectedChainTargets.length||!Rc(e.session.chainTargets,e.expectedChainTargets))throw Error(`ECDSA registration family session target projection is incomplete`);return Fc(e.walletKeys),Ic({session:e.session,walletKeys:e.walletKeys}),qc({session:e.session,walletKeys:e.walletKeys}),{kind:`evm_family_ecdsa`,session:e.session,walletKeys:[t,...n],expectedChainTargets:[r,...i]}}function kp(e){let{walletId:t,authority:n,foundingAuthority:r,foundingAuthMethod:i,registrationDiagnostics:a,rpId:o,authMethod:s,custodyKeyManifestDigestB64u:c,ecdsa:l}=e,{activation:u,bootstrap:d,...f}=l,p={ok:!0,walletId:t,authority:n,foundingAuthority:r,foundingAuthMethod:i,...a?{registrationDiagnostics:a}:{},...c===void 0?{}:{custodyKeyManifestDigestB64u:c},kind:`evm_family_ecdsa`,ecdsa:f};if(s.kind===`passkey`){if(!o)throw Error(`Passkey activation is missing its relying-party id`);return{...p,rpId:o,authMethod:s}}if(o!==void 0)throw Error(`Email OTP activation returned a relying-party id`);return{...p,authMethod:s}}function Ap(e){return{kind:`registration_persistence_plan_v1`,walletId:e.walletId,auth:e.auth,ecdsa:e.ecdsa,foundingAuthority:e.foundingAuthority,foundingAuthMethod:e.foundingAuthMethod}}function jp(e){let t=En(e);if(!t)throw Error(`pending wallet registration commit is invalid`);return t}function Mp(e){let t=Ie(e.walletId),n=c(e.walletAuthMethodId);if(!n.ok)throw Error(n.error.message);let r=Np(e.auth),i={kind:`pending_wallet_registration_commit_v1`,registrationCeremonyId:Pp(e.registrationCeremonyId,`registrationCeremonyId`),idempotencyKey:Pp(e.idempotencyKey,`idempotencyKey`),walletId:t,walletAuthMethodId:n.value,signedSetup:Pp(e.signedSetup,`signedSetup`),auth:r,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs};if(e.operation===`registration_activate`)return jp({...i,operation:e.operation,signerPlanKind:e.signerPlanKind,localMaterial:e.localMaterial});if(e.signerPlanKind!==`near_ed25519`&&e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`near provisioning requires a NEAR signer plan`);return jp({...i,operation:e.operation,phase:`joined`,completion:e.completion,signerPlanKind:e.signerPlanKind,localMaterial:e.localMaterial})}function Np(e){if(e.kind===`passkey`){let t=wp(e.rpId),n=d(e.credentialIdB64u);if(!n.ok)throw Error(n.error.message);return{kind:`passkey`,rpId:t,credentialIdB64u:n.value,transports:[...e.transports]}}let t=h(e.email);if(!t.ok)throw Error(t.error.message);let n=f(e.registrationAuthorityId);if(!n.ok)throw Error(n.error.message);let r=m(e.providerSubject);if(!r.ok)throw Error(r.error.message);return{kind:`email_otp`,email:t.value,registrationAuthorityId:n.value,providerSubject:r.value,enrollment:{enrollmentSealKeyVersion:Pp(e.enrollment.enrollmentSealKeyVersion,`enrollment.enrollmentSealKeyVersion`),serverSealedFactorCiphertextB64u:Pp(e.enrollment.serverSealedFactorCiphertextB64u,`enrollment.serverSealedFactorCiphertextB64u`),clientUnlockPublicKeyB64u:Pp(e.enrollment.clientUnlockPublicKeyB64u,`enrollment.clientUnlockPublicKeyB64u`),unlockKeyVersion:Pp(e.enrollment.unlockKeyVersion,`enrollment.unlockKeyVersion`)}}}function Pp(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a non-empty canonical string`);return e}async function Fp(e){e.registrationTiming.record(`ecdsaRegistrationTargetCount`,e.plan.ecdsa.walletKeys.length);let t=performance.now();try{return await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ie(e.plan.walletId),session:e.plan.ecdsa.session,walletKeys:[...e.plan.ecdsa.walletKeys]})}finally{e.registrationTiming.record(`ecdsaRegistrationSessionFinalizeMs`,Ia(t))}}async function Ip(e){if(e.plan.auth.kind===`passkey`){await e.context.signingEngine.finalizeWalletEcdsaRegistration({walletId:e.plan.walletId,rpId:wp(e.plan.auth.rpId),credential:e.plan.auth.credential,credentialPublicKeyB64u:e.plan.auth.credentialPublicKeyB64u,walletKeys:e.walletKeys});return}await e.context.signingEngine.storeWalletEmailOtpEcdsaRegistrationData({walletId:e.plan.walletId,email:e.plan.auth.email,registrationAuthorityId:e.plan.auth.registrationAuthorityId,authority:e.plan.auth.authority,walletKeys:e.walletKeys})}async function Lp(e){let t=await Fp(e),n=performance.now();try{if(await Ip({context:e.context,plan:e.plan,walletKeys:t}),await V.persistFoundingWalletAuthority({authority:e.plan.foundingAuthority,authMethod:e.plan.foundingAuthMethod}),e.plan.auth.kind===`email_otp`){let t=h(e.plan.auth.email);if(!t.ok)throw Error(t.error.message);let n=await V.retainVerifiedEmailOtpLocalPresentation({walletId:e.plan.walletId,walletAuthMethodId:e.plan.foundingAuthMethod.walletAuthMethodId,emailAddress:t.value});if(n.kind!==`retained`)throw Error(`Verified Email OTP presentation was not retained: ${n.reason}`)}}finally{e.registrationTiming.record(`ecdsaRegistrationLocalRecordPersistenceMs`,Ia(n))}await yr(In,e.plan.ecdsa.session.registrationEstablishedSession)}function Rp(e){return Lp.bind(void 0,e)}async function zp(e){await e.registrationTiming.measure(`ecdsaRegistrationPersistenceMs`,Rp(e))}var Bp=e({REGISTRATION_TIMING_LABEL:()=>ya,addSigner:()=>ng,cancelHostedPasskeyRegistration:()=>Em,prepareHostedPasskeyRegistration:()=>Tm,registerPreparedHostedPasskeyRegistration:()=>Om,registerWallet:()=>Uh,resumeNearRegistrationAfterUnlock:()=>xh,startHostedPasskeyRegistrationCredential:()=>Dm});async function Vp(e,t,n,r){if(r.length!==10||new Set(r).size!==10)throw Error(`Wallet custody must issue exactly ten distinct recovery codes`);switch((await Hp({backup:n,context:e,request:{kind:`wallet_recovery_code_backup_request_v1`,walletId:t,recoveryCodes:r,continuation:`registration_may_defer`}}))?.kind){case`wallet_recovery_codes_backed_up_v1`:return;case`wallet_recovery_code_backup_deferred_v1`:await vr.write({walletId:t,recoveryCodes:r});return;default:throw Error(`Wallet recovery-code backup result is invalid`)}}async function Hp(e){if(!e.backup)return{kind:`wallet_recovery_code_backup_deferred_v1`};switch(e.backup.kind){case`defer_to_account_menu`:return{kind:`wallet_recovery_code_backup_deferred_v1`};case`show_builtin_dialog`:return await _r(e.request,e.context.signingEngine.getWalletIframeSurfaceMeasurementBinding());case`custom_handler`:return await e.backup.handler(e.request);default:return q(e.backup)}}function Up(e){e.byteLength>0&&new Uint8Array(e).fill(0)}function Wp(e){let t=e.established.metadata;return{binding:{kind:Qe,applicationBindingDigestB64u:e.established.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:L(t.registeredPublicKey),participantIds:t.participantIds,stateEpoch:String(t.stateEpoch),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,signingWorkerId:t.scope.signing_worker_id,signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:e.established.localMaterial.b64u,nonceB64u:e.established.localMaterial.nonceB64u}}}function Gp(e){let t=e.metadata;return{materialActivation:tr(t),registeredPublicKeyB64u:L(t.registeredPublicKey),signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare),stateEpoch:String(t.stateEpoch),signingWorkerId:t.scope.signing_worker_id,participantIds:t.participantIds,nearEd25519SigningKeyId:t.applicationBinding.near_ed25519_signing_key_id,signerSlot:t.applicationBinding.key_creation_signer_slot}}function Kp(e){let t=e.establishedCustody;if(!t)throw Error(`Mixed registration custody commit is missing its established envelope`);return{bindingJson:t.envelopeBindingJson,nonceB64u:t.envelopeNonceB64u,ciphertextB64u:t.sealedCustodySecretB64u,aadHashB64u:t.envelopeAadHashB64u,ciphertextDigestB64u:t.envelopeCiphertextDigestB64u}}function qp(e){let t=e.commit.establishedCustody;if(!t)throw Error(`Passkey registration custody commit is missing its established envelope`);return Md({expectedWalletId:e.walletId,replacement:t,activatedAtMs:e.activatedAtMs})}async function Jp(e){await e.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:qp({commit:e.commit,walletId:e.walletId,activatedAtMs:Date.now()}),passkeyPrfFirstB64u:e.passkeyPrfFirstB64u,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,walletSessionId:e.walletSessionId,expiresAtMs:e.expiresAtMs})}async function Yp(e){try{await yp(pp(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:qp({commit:e.commit,walletId:e.walletId,activatedAtMs:Date.now()}),existingFactorSecret:e.factorSecret32,walletId:e.walletId,walletAuthMethodId:String(e.emailOtpAuthContext.authority.bindingId),walletSessionId:e.walletSessionId,expiresAtMs:e.expiresAtMs})}catch(e){console.warn(`[registration][email-otp] unlocked Ed25519 export-root capability was not established:`,e instanceof Error?e.message:String(e||`unknown error`))}}async function Xp(e){let t=qp(e);if(t.factor.kind!==`passkey`)throw Error(`Passkey registration custody commit has a non-passkey factor`);await Kd({walletId:e.walletId,credentialIdB64u:t.factor.credentialIdB64u,envelope:t})}function Zp(e){let t=e.joined.metadata,n=s(t.scope.threshold_session_id);if(!n.ok)throw Error(`Registration Ed25519 capability has an invalid threshold session`);return{kind:Bt,session:{walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,authorityScope:{kind:`email_otp`,provider:or(e.authContext),providerUserId:sr(e.authContext)},thresholdSessionId:n.value,authorizationId:e.sessionState.signingWalletSession.authorizationId,walletSessionId:e.sessionState.walletSessionId,quotaId:e.sessionState.quotaId,expiresAtMs:e.sessionState.signingWalletSession.expiresAtMs,participantIds:t.participantIds,remainingUses:e.sessionState.signingWalletSession.remainingUses,signingRootId:e.sessionState.signingRootId,signingRootVersion:e.sessionState.signingRootVersion,runtimePolicyScope:e.sessionState.runtimePolicyScope,routerAbNormalSigning:e.sessionState.routerAbNormalSigning},capability:{kind:`router_ab_ed25519_yao_active_capability_v1`,materialActivation:t.materialActivation,activeCapabilityBinding:t.activeCapabilityBinding,registeredPublicKey:[...t.registeredPublicKey],nearAccountId:e.nearAccountId,applicationBinding:t.applicationBinding,runtimePolicyScope:e.sessionState.runtimePolicyScope,participantIds:t.participantIds,lifecycle:{lifecycleId:t.scope.lifecycle_id,rootShareEpoch:t.scope.root_share_epoch,accountId:t.scope.account_id,thresholdSessionId:n.value,signerSetId:t.scope.signer_set_id,signingWorkerId:t.scope.signing_worker_id},stateEpoch:Number(t.stateEpoch),registrationContinuity:{kind:`registration`,admissionRequest:e.deferredNear.admissionRequest,admissionReceipt:e.admissionReceipt,activationTranscript:[...t.transcript]}}}}const Qp=Symbol(`hostedPasskeyRegistrationPrepared`),$p=new WeakMap;function em(e){let t=je(e);if(!t.ok)throw Error(t.message);return t.value}function tm(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function nm(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`implicit_account`:return t.kind===`implicit_account`&&e.accountIdSource===t.accountIdSource;case`sponsored_named_account`:return t.kind===`sponsored_named_account`&&e.requestedAccountId===t.requestedAccountId&&e.sponsor===t.sponsor;default:return q(e)}}function rm(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`near_ed25519`:return t.kind===`near_ed25519`&&nm(e.accountProvisioning,t.accountProvisioning)&&e.signerSlot===t.signerSlot&&tm(e.participantIds,t.participantIds)&&e.derivationVersion===t.derivationVersion;case`evm_family_ecdsa`:return t.kind===`evm_family_ecdsa`&&tm(e.participantIds,t.participantIds)&&Pe(e.chainTargets)===Pe(t.chainTargets);default:return q(e)}}function im(e,t){if(e.kind!==t.kind||e.signers.length!==t.signers.length)return!1;for(let n=0;n<e.signers.length;n+=1){let r=e.signers[n],i=t.signers[n];if(!r||!i||!rm(r,i))return!1}return!0}function am(e){return e.signingEngine.warmCriticalResources.bind(e.signingEngine,{kind:`none`})}function om(){return Promise.resolve($a())}function sm(e){return e.signers.some(e=>e.kind===`evm_family_ecdsa`)}function cm(e){return e.authMethod.kind!==`email_otp`||!Pr(e.signerSelection)?om:um.bind(void 0,{prewarm:e.context.signingEngine.prewarmEmailOtpYao.bind(e.context.signingEngine)})}function lm(e,t){let n=Ia(t);return{kind:`failed`,elapsedMs:n,workerPrewarmMs:n,yaoWasmInitMs:0,failureStage:`worker_ready`}}function um(e){let t=performance.now();return e.prewarm().catch(e=>lm(e,t))}function dm(e){let[t,n]=e;return{kind:`completed`,diagnostics:{...t,emailOtpWorkerPrewarmMs:n.workerPrewarmMs,emailOtpYaoWasmInitMs:n.yaoWasmInitMs,emailOtpYaoPrewarm:n}}}function fm(e){return{kind:`failed`,error:e}}function pm(e){Hn({relayerUrl:e.relayerUrl,nearEd25519:e.signerSelection.signers.some(e=>e.kind===`near_ed25519`),evmFamilyEcdsa:sm(e.signerSelection)}),Pr(e.signerSelection)&&Yc(e.authMethod,e.context.signingEngine.prewarmNearSigner.bind(e.context.signingEngine));let t=e.recorder.measure(`registrationWarmupMs`,am(e.context)),n=e.recorder.measure(`registrationWarmupEmailOtpYaoWasmInitMs`,cm({context:e.context,authMethod:e.authMethod,signerSelection:e.signerSelection}));return sm(e.signerSelection)&&e.context.signingEngine.prewarmEcdsaRegistrationCrypto?.().catch(()=>{}),Promise.all([t,n]).then(dm,fm)}function mm(e){e.warmup.then(t=>{t.kind===`completed`&&e.recorder.captureWarmupDiagnostics(t.diagnostics)})}function hm(e){return Ne(em(e))?.signerSlot??1}async function gm(e){return e.passkeyExecution?.kind===`use_hosted_preparation`?await e.passkeyExecution.authority:await Qd({context:e.context,walletId:e.walletId,signerSlot:e.signerSlot,registrationIntentDigestB64u:e.registrationIntentDigestB64u,options:e.options,confirmationConfigOverride:e.confirmationConfigOverride})}function _m(e){if(e[Qp]!==!0)throw Error(`Invalid hosted passkey registration preparation`);let t=$p.get(e);if(!t)throw Error(`Hosted passkey registration preparation is unknown`);return t}function vm(e){if(e.lifecycle!==`ready`)throw Error(`Hosted passkey registration preparation is no longer usable`);if(Date.now()>=e.prepared.expiresAtMs)throw Em(e.prepared),Error(`Hosted passkey registration preparation expired`);if(e.controller.signal.aborted)throw Error(`Hosted passkey registration preparation was cancelled`);if(!hr.isLiveReservation({reservation:e.prepared.reservation,owner:e.prepared.owner}))throw Em(e.prepared),Error(`Hosted passkey registration prompt reservation is no longer active`)}function ym(e){return x({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:e.walletId,signerSlot:e.signerSlot,rpId:e.rpId,challengeB64u:e.challengeB64u})}function bm(){return Error(`Hosted passkey registration preparation was cancelled`)}function xm(e){if(e.aborted)throw bm()}function Sm(e){let t=e.cancellation.signal;return xm(t),new Promise((n,r)=>{let i=!1,a=()=>{c(bm())},o=()=>{t.removeEventListener(`abort`,a)},s=e=>{i||(i=!0,o(),n(e))},c=e=>{i||(i=!0,o(),r(e))};t.addEventListener(`abort`,a,{once:!0}),e.operation.then(s,c)})}function Cm(e){switch(e.setup.kind){case`near_ed25519`:return{kind:`not_required`};case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:{let t=e.setup.registrationCeremonyId,n=nh(e.setup.ecdsa),r=e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony({kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:t,registration:n.strictRegistration});return r.catch(()=>void 0),{kind:`started`,ceremonyId:t,operation:r}}default:return q(e.setup)}}function wm(e){e.ceremony.kind!==`not_required`&&zc({context:e.context,ceremonyId:e.ceremony.ceremonyId})}async function Tm(e){let t=e.authMethod,n=wp(String(t.rpId));if(wp(String(e.context.signingEngine.getRpId()||``))!==n)throw Error(`Hosted passkey registration rpId does not match the wallet runtime`);let r=hm(e.signerSelection),i=e.expiresInMs??300*1e3;if(!Number.isSafeInteger(i)||i<=0)throw Error(`Hosted passkey registration expiry must be a positive safe integer`);let a=Date.now()+i,o={kind:`hosted_auth_menu_registration`,authMenuSessionId:e.authMenuSessionId,requestId:e.requestId},s=new AbortController,c=null,l=null,u={kind:`not_required`},d=()=>{s.abort(),c&&Em(c)},f=()=>{e.cancellation.signal.removeEventListener(`abort`,d)};xm(e.cancellation.signal),e.cancellation.signal.addEventListener(`abort`,d,{once:!0});let p=new Qa(performance.now());try{let i=await Sm({operation:Ym({context:e.context,authMethod:t,wallet:e.wallet,signerSelection:e.signerSelection,recorder:p}),cancellation:e.cancellation}),d=tl(i.setup.intent);if(String(d.authMethod.rpId)!==String(n)||!im(d.signerSelection,e.signerSelection))throw Error(`Hosted passkey registration setup changed its authority binding`);let m=qt(String(d.walletId)),h=String(i.setup.registrationIntentDigestB64u||``).trim();if(!h)throw Error(`Hosted passkey registration setup returned no challenge`);if(r!==hm(e.signerSelection))throw Error(`Hosted passkey registration signer slot changed during preparation`);if(u=Cm({context:e.context,setup:i.setup}),mm({recorder:p,warmup:i.registrationWarmup}),Date.now()>=a)throw Error(`Hosted passkey registration preparation expired before reservation`);let g=await hr.reserveRegistrationPrompt({owner:o,expiresAtMs:a,cancellation:e.cancellation});l=g;let _=ym({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:t,walletId:m,signerSlot:r,rpId:n,challengeB64u:h}),v=Object.freeze({kind:`hosted_passkey_registration_prepared_v1`,walletId:m,signerSlot:r,rpId:n,challengeB64u:h,registrationIntentDigestB64u:h,expiresAtMs:a,owner:o,reservation:g,cancellation:{kind:`abort_signal`,signal:s.signal},[Qp]:!0});return $p.set(v,{prepared:v,context:e.context,wallet:e.wallet,signerSelection:e.signerSelection,authMethod:t,options:e.options??{},...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{},setup:i,controller:s,removeExternalCancellationListener:f,binding:_,lifecycle:`ready`,authority:null,registrationStarted:!1,ecdsaClientCeremony:u}),c=v,v}catch(t){throw s.abort(),f(),wm({context:e.context,ceremony:u}),c?Em(c):l&&hr.releaseReservation(l),t}}function Em(e){let t=_m(e);t.lifecycle===`finished`||t.lifecycle===`cancelled`||(t.lifecycle=`cancelled`,t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,wm({context:t.context,ceremony:t.ecdsaClientCeremony}),hr.releaseReservation(e.reservation))}function Dm(e){let t=_m(e);vm(t),t.lifecycle=`consuming`;let n=Zd(t.context.signingEngine.startPreparedPasskeyRegistrationCredential({walletId:String(e.walletId),signerSlot:e.signerSlot,challengeB64u:e.challengeB64u,expectedRpId:String(e.rpId),reservation:e.reservation,owner:e.owner,cancellation:e.cancellation}));return t.authority=n,n.then(()=>{t.lifecycle===`consuming`&&(t.lifecycle=`consumed`)},()=>{Em(e)}),n}async function Om(e){let t=_m(e.prepared);if(t.lifecycle!==`consuming`&&t.lifecycle!==`consumed`||!t.authority)throw Error(`Hosted passkey registration credential must be started by its CTA`);if(t.registrationStarted)throw Error(`Hosted passkey registration continuation was already consumed`);t.registrationStarted=!0;try{return await Vh({context:t.context,authMethod:t.authMethod,wallet:t.wallet,signerSelection:t.signerSelection,options:t.options,authenticatorOptions:jn(t.context.configs.webauthn.authenticatorOptions),...t.confirmationConfigOverride?{confirmationConfigOverride:t.confirmationConfigOverride}:{},passkeyExecution:{kind:`use_hosted_preparation`,prepared:e.prepared,authority:t.authority}})}finally{t.lifecycle=`finished`,wm({context:t.context,ceremony:t.ecdsaClientCeremony}),t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,hr.releaseReservation(e.prepared.reservation)}}async function km(e){return $d(`wallet-registration-near-provisioning:${await S([`wallet-registration-near-provisioning`,e.registrationCeremonyId,e.activationReference.lifecycle_id,e.activationReference.session_id.map(e=>e.toString(16).padStart(2,`0`)).join(``)].join(`:`))}`)}function Am(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return $d(`${e}:${t.randomUUID()}`);let n=new Uint8Array(16);if(!t||typeof t.getRandomValues!=`function`)throw Error(`Secure randomness is required for registration finalization`);return t.getRandomValues(n),$d(`${e}:${[...n].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`)}function jm(e){return e.recorder.measure(`emailOtpEnrollmentMaterialMs`,()=>Nm({context:e.context,authMethod:e.authMethod,relayerUrl:e.relayerUrl,walletId:e.walletId,providerSubject:e.providerSubject,clientSecret32:e.clientSecret32}))}function Mm(e){if(e.emailOtpSessionHandle.kind!==`not_requested`)throw Error(`Strict ECDSA registration received obsolete Email OTP root-share material`)}async function Nm(e){if(e.authMethod.kind!==`email_otp`)throw Error(`Email OTP enrollment material requires Email OTP auth`);try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:e.relayerUrl,walletId:Ie(e.walletId),userId:e.providerSubject,clientSecret32:e.clientSecret32});return Mm(t),t}finally{e.clientSecret32.fill(0)}}function Pm(e){let t=e.event.authMethod,n=Fm(e.accountId);return hn({...e.event,flowId:`registration:${t}:${n}`,accountId:n,authMethod:t})}function Fm(e){let t=String(e||``).trim();if(!t)throw Error(`Registration event account id is required`);return t}function Im(e){return b(e)&&`code`in e?String(e.code||``).trim():``}function Lm(e,t){return Object.assign(Error(e),t?{code:t}:{})}function Rm(e){return Array.isArray(e)?e.filter(e=>{switch(e){case`ble`:case`hybrid`:case`internal`:case`nfc`:case`smart-card`:case`usb`:return!0;default:return!1}}):[]}function $(e,t,n){e?.(Pm({accountId:t,event:n}))}function zm(e,t,n){let r=!1;return async i=>{if(!e||r)return await i;let a=setTimeout(()=>{r||(r=!0,$(e,t,{authMethod:`passkey`,phase:n,status:`running`}))},5e3);try{return await i}finally{clearTimeout(a)}}}async function Bm(e){let t=String(e||``).trim().toLowerCase();if(!t)throw Error(`Email OTP registration auth context requires email`);return S(t)}function Vm(e){switch(e.proofKind){case`otp_challenge`:return`email`;case`google_sso_registration`:return`google`;default:return q(e)}}function Hm(e){switch(e.kind){case`passkey`:return{kind:`passkey`,webauthnRegistration:e.webauthnRegistration};case`email_otp`:return{kind:`email_otp`,emailOtpRegistrationProof:e.emailOtpRegistrationProof};default:return q(e)}}async function Um(e){let t=performance.now();try{let n=await il(e.deferredNear,{routerOrigin:new URL(e.relayerUrl).origin,routing:e.home,authorization:{kind:`bearer`,value:`Bearer ${e.signedSetup}`},fetch:globalThis.fetch,...e.traceContext?{traceContext:e.traceContext}:{}});return wa({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`success`}),{deferredNear:e.deferredNear,admissionReceipt:n}}catch(n){throw wa({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`failure`}),n}}function Wm(e){if(!e)throw Error(`Mixed registration did not start NEAR admission`);return e}function Gm(e,t,n){switch(e.kind){case`passkey`:return{auth:{kind:`passkey`,rpId:pt(e.rpId),credentialIdB64u:t}};case`email_otp`:return{auth:{kind:`email_otp`,providerSubjectId:sr(e.emailOtpAuthContext)},remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs};default:return q(e)}}async function Km(e){let t=ut(x({operation:`wallet_registration_activate_v2`,registrationCeremonyId:e.registrationCeremonyId,activationCorrelationId:e.activationCorrelationId,idempotencyKey:e.idempotencyKey,publicFacts:e.publicFacts}));return{canonicalRequest:t,requestDigest:xe(L(await A(String(t))))}}async function qm(e){let t={authority:e.materialAuthority,targetMemberships:e.chainTargets,evmFamilySigningKeySlotId:Gt(e.ecdsaPrepare.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:ln(e.ecdsaPrepare.prepare.ecdsaThresholdKeyId),signingRootId:ot(e.ecdsaPrepare.prepare.signingRootId),signingRootVersion:mt(e.ecdsaPrepare.prepare.signingRootVersion),runtimePolicyScope:e.ecdsaPrepare.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:sn(e.clientActivation.derivationClientSharePublicKey33B64u),participantIds:[Dt(e.ecdsaPrepare.prepare.participantIds[0]),Dt(e.ecdsaPrepare.prepare.participantIds[1])],relayerKeyId:cn(e.ecdsaPrepare.prepare.relayerKeyId),bindingDigest:pn(e.clientActivation.contextBinding32B64u),journalId:e.activationCorrelationId,requestDigest:e.activationCommand.requestDigest,canonicalRequest:e.activationCommand.canonicalRequest,createdAt:ye(new Date().toISOString())},n=await e.context.signingEngine.persistInitialCanonicalEcdsaActivation({kind:`persist_initial_canonical_ecdsa_activation_v1`,bootstrapOwner:`wallet_custody`,clientActivation:e.clientActivation,ceremonyId:e.ceremonyId,planInput:t});if(!n.ok)throw Error(`Canonical ECDSA activation persistence failed (${n.code}): ${n.message}`);return n}function Jm(e){let t=R(e);if(t.length!==20)throw Error(`ECDSA activation address must contain 20 bytes`);return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function Ym(e){let t=String(e.context.configs.network.relayer.url||``).trim();if(!t)throw Error(`registerWallet requires relayer.url`);let n=e.context.configs.registration,r=String(n?.publishableKey||``).trim(),i=String(n?.projectEnvironmentId||``).trim();if(!r||!i)throw Error(`registerWallet requires registration.publishableKey and registration.projectEnvironmentId`);let a=pm({recorder:e.recorder,context:e.context,relayerUrl:t,authMethod:e.authMethod,signerSelection:e.signerSelection}),o=await e.recorder.measure(`registrationIntentMs`,()=>Wn({relayerUrl:t,request:{...e.wallet.kind===`provided`?{wallet:e.wallet}:{},signerSelection:e.signerSelection,authMethod:e.authMethod},auth:{publishableKey:r,environmentId:i}}));if(!o.ok)throw Lm(o.message,o.code);return{relayerUrl:t,setup:o,registrationWarmup:a}}async function Xm(e){if(e.passkeyExecution.kind===`collect_during_registration`)return await Ym({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:e.recorder});if(e.authMethod.kind!==`passkey`)throw Error(`Hosted passkey preparation requires passkey registration`);let t=_m(e.passkeyExecution.prepared);if(t.context!==e.context||t.lifecycle===`cancelled`)throw Error(`Hosted passkey registration preparation belongs to a different operation`);let n=t.setup,r=tl(n.setup.intent),i=String(n.setup.registrationIntentDigestB64u||``).trim(),a=hm(e.signerSelection);if(ym({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:qt(String(r.walletId)),signerSlot:a,rpId:wp(String(e.authMethod.rpId)),challengeB64u:i})!==t.binding||String(r.walletId)!==String(e.passkeyExecution.prepared.walletId)||i!==e.passkeyExecution.prepared.challengeB64u)throw Error(`Hosted passkey registration preparation binding changed`);return n}function Zm(e){if(e.passkeyExecution.kind===`collect_during_registration`)return{kind:`create_after_authority`};let t=_m(e.passkeyExecution.prepared);if(t.ecdsaClientCeremony.kind!==`started`||t.ecdsaClientCeremony.ceremonyId!==e.ceremonyId)throw Error(`Hosted passkey registration has no matching ECDSA client ceremony`);return{kind:`use_hosted_preparation`,ceremonyId:t.ecdsaClientCeremony.ceremonyId,operation:t.ecdsaClientCeremony.operation}}async function Qm(e){return await e}function $m(e){switch(e.clientCeremony.kind){case`create_after_authority`:return e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony.bind(e.context.signingEngine,{kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:e.ceremonyId,registration:e.registration});case`use_hosted_preparation`:if(e.clientCeremony.ceremonyId!==e.ceremonyId)throw Error(`Prepared ECDSA client ceremony identity changed`);return Qm.bind(void 0,e.clientCeremony.operation);default:return q(e.clientCeremony)}}async function eh(e){let[t,...n]=e.ecdsaPrepare.chainTargets;if(!t)throw Error(`Strict ECDSA ceremony requires at least one EVM-family target`);let r=e.registrationCeremonyId,i=be(r),a=null;try{let o=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientCreateMs`,operation:$m({context:e.context,ceremonyId:r,registration:e.ecdsaPrepare.strictRegistration,clientCeremony:e.clientCeremony})}),s=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Un.bind(void 0,{relayerUrl:e.relayerUrl,headers:jc(e.traceContext),registrationCeremonyId:r,signerPlanKind:e.signerPlanKind,signedSetup:e.signedSetup,ecdsa:{kind:`router_ab_ecdsa_registration_v1`,strictRegistration:o.registrationRequest,requestDigestB64u:o.registrationRequestDigestB64u},...Hm(e.authority),onServerTiming:t=>xa(e.registrationTiming,`respond`,t)})});if(s.kind===`near_ed25519`)throw Error(`ECDSA registration ceremony received an Ed25519-only respond result`);let c=s.kind===`near_ed25519_and_evm_family_ecdsa`?s.ed25519:null,l=c?Um({home:e.home,relayerUrl:e.relayerUrl,registrationCeremonyId:r,signedSetup:e.signedSetup,deferredNear:c,traceContext:e.traceContext}):null;l?.catch(mh);let u=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientProofVerifyMs`,operation:e.context.signingEngine.verifyRouterAbEcdsaRegistrationClientProofs.bind(e.context.signingEngine,{kind:`verify_router_ab_ecdsa_registration_client_proofs_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:s.ecdsa.strictResult.response.bundles}})}),d=await e.resolveActivateEmailOtp(),f=[t,...n],p=e.authority.kind===`passkey`?e.authority.walletCustodyFactorJson:d.walletCustodyFactorJson;if(!p)throw Error(`ECDSA registration has no wallet custody factor binding`);let m=e.authority.walletCustodyFactorSecret,h={},g=await e.context.signingEngine.establishWalletCustodyEvmFamilyKeySet({walletId:e.ecdsaPrepare.prepare.walletId,factorJson:p,factorSecret:m,evmFamilySigningKeySlotId:e.ecdsaPrepare.prepare.evmFamilySigningKeySlotId,applicationBindingDigestB64u:u.applicationBindingDigestB64u,confirmRecoveryCodesBackedUp:e.confirmRecoveryCodesBackedUp,runRelayerRound:async t=>{let n=ht({registrationRequestDigestB64u:u.registrationRequestDigestB64u,proofTranscriptDigestB64u:u.proofTranscriptDigestB64u,contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.clientSharePublicKey33B64u,clientShareRetryCounter:t.clientShareRetryCounter,participantId:1}),o=await Km({registrationCeremonyId:r,activationCorrelationId:i,idempotencyKey:e.idempotencyKey,publicFacts:n}),s=ql(t.preActivationCommitPayload),p={activationJournalId:i,clientActivation:n,activationRequestDigestB64u:o.requestDigest};if(e.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){if(!c)throw Error(`Mixed registration has no NEAR continuation`);await e.persistPendingCommit({signerPlanKind:e.signerPlanKind,localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:s,ecdsa:p},emailOtpEnrollment:d.enrollment,deferredNear:c}),a=e.startDeferredNearCustody({admission:Wm(l),establishedEvmCustodyCommit:t.preActivationCommitPayload}),a.catch(mh)}else await e.persistPendingCommit({signerPlanKind:e.signerPlanKind,localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:s,ecdsa:p},emailOtpEnrollment:d.enrollment});let m=await qm({context:e.context,ceremonyId:r,materialAuthority:e.materialAuthority,ecdsaPrepare:e.ecdsaPrepare,chainTargets:f,activationCorrelationId:i,activationCommand:o,clientActivation:n});if(String(m.journalId)!==String(i))throw Error(`ECDSA activation journal identity changed before activate`);let g=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Yn.bind(void 0,{relayerUrl:e.relayerUrl,headers:jc(e.traceContext),registrationCeremonyId:r,signerPlanKind:e.signerPlanKind,signedSetup:e.signedSetup,idempotencyKey:e.idempotencyKey,ecdsa:{clientActivation:n,activationCorrelationId:i,activationRequestDigestB64u:o.requestDigest},walletCustodyCommit:t.preActivationCommitPayload,...d.enrollment?{emailOtpEnrollment:d.enrollment}:{},onServerTiming:t=>xa(e.registrationTiming,`activate`,t)})});if(g.kind!==`evm_family_ecdsa`||!g.ecdsa)throw Error(`ECDSA registration ceremony received a non-ECDSA activate result`);h.value=g,h.journalId=m.journalId;let _=g.ecdsa.activation.ecdsa_activation.public_identity;return JSON.stringify({relayerKeyId:e.ecdsaPrepare.prepare.relayerKeyId,relayerPublicKey33B64u:_.server_public_key33_b64u,groupPublicKey33B64u:_.threshold_public_key33_b64u,ethereumAddress:Jm(_.ethereum_address20_b64u),relayerShareRetryCounter:_.server_share_retry_counter})}});if(!h.value||!h.journalId)throw Error(`Wallet custody ECDSA activation did not return its committed receipt`);let _=h.value;if(_.walletCustody?.status!==`committed`){let e=_.walletCustody?.status??`not_reported`;throw Error(`Wallet custody did not commit during ECDSA activation (${e})`)}let v=Bc({prepare:e.ecdsaPrepare.prepare,verified:g.clientBootstrap}),y=Gn({clientBootstrap:v,serverBootstrap:_.ecdsa.bootstrap,activationEpoch:_.ecdsa.activation.ecdsa_activation.activation_epoch}),b=await e.context.signingEngine.finalizeRouterAbEcdsaRegistrationActivation({kind:`finalize_router_ab_ecdsa_registration_activation_v1`,bootstrapOwner:`wallet_custody`,journalId:h.journalId,activationReceipt:_.ecdsa.activation,routerAbEcdsaDerivationNormalSigning:y.routerAbEcdsaDerivationNormalSigning,readyStateBlobB64u:g.localMaterial.readyStateBlobB64u,walletCustodyPublicFacts:g.localMaterial.publicFacts});return{session:{chainTargets:[t,...n],clientBootstrap:v,bootstrap:y,activatedThresholdSessionId:_.ecdsa.bootstrap.thresholdSessionId,roleLocalMaterial:b.roleLocalMaterial,authority:await ct({authority:_.authority}),materialActivation:b.materialActivation,clientPublicFacts:b.publicFacts,publicCapability:b.publicCapability,registrationEstablishedSession:Pc(_.registrationEstablishedSession)},activated:_,deferredNear:c,activateEmailOtp:{enrollment:d.enrollment},walletCustody:g,deferredNearCustodyWork:a}}catch(t){throw dh(a),await zc({context:e.context,ceremonyId:r}),t}}function th(e){switch(e.kind){case`evm`:return ze({chain:`evm`,chainId:e.chainId,networkSlug:e.networkSlug});case`tempo`:return ze({chain:`tempo`,chainId:e.chainId,networkSlug:e.networkSlug});default:return q(e)}}function nh(e){let[t,...n]=e.chainTargets;if(!t)throw Error(`Registration setup ECDSA chain targets are required`);return{kind:e.kind,chainTargets:[th(t),...n.map(th)],prepare:e.prepare,strictRegistration:e.strictRegistration}}function rh(e,t){switch(e.kind){case`near_ed25519`:throw Error(`Registration setup returned an Ed25519-only signer branch`);case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:if(e.kind!==t)throw Error(`Registration setup returned a different signer branch`);return e;default:return q(e)}}function ih(e){switch(e.kind){case`evm_family_ecdsa`:return 1;case`near_ed25519_and_evm_family_ecdsa`:return e.ed25519Selection.signerSlot;default:return q(e)}}function ah(e){if(e.authMethod.kind===`passkey`){if(!e.passkeyAuthority)throw Error(`Passkey registration authority was not collected`);return{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:String(e.passkeyAuthority.credential.rawId||e.passkeyAuthority.credential.id||``).trim(),transports:[...e.passkeyAuthority.webauthnRegistration.response.transports]}}return{kind:`email_otp`,email:e.email,registrationAuthorityId:e.registrationAuthorityId,providerSubject:e.providerSubject,enrollment:oh(e.emailOtpEnrollment)}}function oh(e){if(!e)throw Error(`Email OTP registration has no enrollment material for pending recovery`);return e}async function sh(e){let t=Date.now(),n=Mp({...e,createdAtMs:t,updatedAtMs:t});return await V.putPendingWalletRegistrationCommit(n),n}function ch(e){if(!e||e.operation!==`registration_activate`||e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`Mixed registration activation commit was not persisted`);return e}async function lh(e){let t=e.walletKeys;if(e.auth.kind===`passkey`){let n=String(e.auth.credential.rawId||e.auth.credential.id||``).trim();if(!n)throw Error(`Passkey registration publication has no credential id`);return await nt({kind:`passkey`,walletId:e.walletId,rpId:wp(e.auth.rpId),credentialIdB64u:n,credentialPublicKeyB64u:e.auth.credentialPublicKeyB64u,transports:e.auth.credential.response?.transports??[],walletKeys:t})}return await nt({kind:`email_otp`,walletId:e.walletId,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:e.auth.authority,walletKeys:t})}async function uh(e){let t=await Fp({context:e.context,relayerUrl:e.relayerUrl,registrationTiming:e.registrationTiming,plan:e.plan}),n=await lh({auth:e.plan.auth,walletId:e.plan.walletId,walletKeys:t}),r=e.plan.ecdsa.session.registrationEstablishedSession;await V.publishPendingWalletRegistrationCommit({pending:e.pending,authority:e.activated.authority,foundingAuthority:{authority:e.activated.foundingAuthority,authMethod:e.activated.foundingAuthMethod},request:{operation:e.pending.operation,registrationCeremonyId:e.pending.registrationCeremonyId,idempotencyKey:e.pending.idempotencyKey,walletId:e.pending.walletId,walletAuthMethodId:e.pending.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:r.walletSession,operationCredential:r.operationCredential},ecdsaContinuity:[],registration:n})}async function dh(e){if(e)try{Up((await e).factorSecret32)}catch{}}function fh(e){switch(e.auth.kind){case`passkey`:{if(!e.passkeyAuthority)throw Error(`Deferred passkey registration requires authority material`);let t=String(e.passkeyAuthority.credential.rawId||e.passkeyAuthority.credential.id||``).trim(),n=String(e.passkeyAuthority.prfFirstB64u||``).trim();if(!t||!n)throw Error(`Deferred passkey registration requires credential PRF material`);return{kind:`passkey`,rpId:e.auth.rpId,credentialIdB64u:t,prfFirstB64u:n}}case`email_otp`:if(!e.emailOtpEnrollment)throw Error(`Deferred Email OTP registration requires enrollment material`);return{kind:`email_otp`,enrollment:e.emailOtpEnrollment,emailOtpAuthContext:e.auth.emailOtpAuthContext};default:return q(e.auth)}}async function ph(e,t,n){let r=performance.now();await V.advancePendingNearRegistration({expected:e,next:Tn(e,t,n)}),kr(e.registrationCeremonyId,`journal_prepared`,r)}function mh(){}async function hh(e,t){let n=e.factorSecretOwner.value;if(!n)throw Error(`Mixed registration has no NEAR custody factor secret`);e.factorSecretOwner.value=null;let r=performance.now(),i=`failure`;try{let r=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.registrationCeremonyId,operation:`near_provisioning`});if(!r||r.operation!==`near_provisioning`||r.phase!==`planned`)throw Error(`NEAR registration has no planned continuation`);let a;try{let e=await t.admission;if(!zt(e.deferredNear.admissionRequest,r.admissionRequest))throw Error(`NEAR admission changed the authorized request`);a=e.admissionReceipt}catch(e){if(e instanceof Error&&e.message===`NEAR admission changed the authorized request`)throw e;a=void 0}let{joined:o,admissionReceipt:s}=await _h({home:e.home,pending:r,signingEngine:e.context.signingEngine,relayerUrl:e.relayerUrl,credential:e.signedSetup,traceContext:e.traceContext,factorSecret:n,...a?{admitted:a}:{}});return i=`success`,{admissionReceipt:s,joined:o,admissionRequest:r.admissionRequest,envelope:qp({commit:t.establishedEvmCustodyCommit,walletId:r.walletId,activatedAtMs:Date.now()}),factorSecret32:n}}catch(e){throw Up(n),e}finally{wa({ceremonyId:e.registrationCeremonyId,stage:`custody_join`,startedAt:r,outcome:i})}}async function gh(e){return e.pending.phase===`execution_prepared`?e.pending.admissionReceipt:e.admitted?e.admitted:await il({status:`deferred`,admissionRequest:e.pending.admissionRequest},{routerOrigin:new URL(e.relayerUrl).origin,routing:e.home,authorization:{kind:`bearer`,value:`Bearer ${e.credential}`},fetch:globalThis.fetch,traceContext:e.traceContext})}async function _h(e){let t=e.pending;if(t.phase===`joined`&&t.completion.kind!==`encrypted_checkpoint`)throw Error(`Joined material has no encrypted execution checkpoint`);let n=t.phase===`joined`&&t.completion.kind===`encrypted_checkpoint`?t.completion.prepared:t;if(n.phase===`joined`)throw Error(`Invalid NEAR continuation phase`);let r=n.admissionRequest,i=performance.now(),a=await gh({home:e.home,pending:n,relayerUrl:e.relayerUrl,credential:e.credential,traceContext:e.traceContext,...e.admitted?{admitted:e.admitted}:{}});kr(n.registrationCeremonyId,`admission`,i);let o=await e.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:e.home,...n.phase===`planned`?{preparation:{kind:`fresh`},beforeRouterRound:ph.bind(void 0,n,a)}:{preparation:{kind:`checkpoint`,checkpointJson:n.checkpointJson}},custodyJson:Il(n.baseCustodyCommit),factorSecret:e.factorSecret,nearEd25519SigningKeyId:r.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:n.registrationCeremonyId,admissionRequest:r,admissionReceipt:a,participantIds:r.participant_ids,routerOrigin:new URL(e.relayerUrl).origin,authorization:`Bearer ${e.credential}`,traceContext:e.traceContext});if(t.phase===`joined`){if(L(o.metadata.registeredPublicKey)!==t.localMaterial.ed25519.metadata.registeredPublicKeyB64u||JSON.stringify(o.activationReference)!==JSON.stringify(t.localMaterial.ed25519.activationReference))throw Error(`Restored NEAR checkpoint changed the joined key`);return{joined:o,admissionReceipt:a}}let s=performance.now(),c=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:n.registrationCeremonyId,operation:`near_provisioning`});if(!c||c.operation!==`near_provisioning`||c.phase!==`execution_prepared`)throw Error(`NEAR execution checkpoint was not persisted`);let l=Mp({operation:`near_provisioning`,signerPlanKind:`near_ed25519_and_evm_family_ecdsa`,completion:{kind:`encrypted_checkpoint`,prepared:c},registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:await km({registrationCeremonyId:c.registrationCeremonyId,activationReference:o.activationReference}),walletId:c.walletId,walletAuthMethodId:c.walletAuthMethodId,signedSetup:c.signedSetup,auth:c.auth,createdAtMs:c.createdAtMs,updatedAtMs:Date.now(),localMaterial:{keyFamilies:[`ed25519`],custodyCommit:o.commitPayload,ed25519:{activationReference:o.activationReference,localMaterial:o.localMaterial,metadata:Gp(o)}}});if(l.operation!==`near_provisioning`||l.phase!==`joined`)throw Error(`Invalid joined NEAR continuation`);return await V.advancePendingNearRegistration({expected:c,next:l}),kr(n.registrationCeremonyId,`journal_joined`,s),{joined:o,admissionReceipt:a}}function vh(e){return e.chainTarget}function yh(e,t){if(e.auth.kind===`passkey`&&t.kind===`passkey`&&e.auth.rpId===t.rpId&&e.auth.credentialIdB64u===t.credentialIdB64u)return{kind:`passkey`,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u,prfFirstB64u:t.prfFirstB64u};if(e.auth.kind===`email_otp`&&t.kind===`email_otp`&&e.auth.providerSubject===t.providerSubject){let n=lt({walletId:e.walletId,bindingId:e.walletAuthMethodId,factor:{kind:`email_otp`,provider:t.provider,providerUserId:t.providerSubject},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:t.emailHashHex}});if(!n)throw Error(`NEAR continuation requires its founding Email OTP method`);return{kind:`email_otp`,enrollment:e.auth.enrollment,emailOtpAuthContext:lr({policy:`session`,retention:`session`,reason:`login`,authority:n})}}throw Error(`NEAR continuation requires its founding authentication method`)}async function bh(e){if(await wh(e.sessionAuthority),e.pending.phase===`joined`&&e.pending.completion.kind===`sealed_material`){let t=await fd({pending:e.pending,relayerUrl:e.relayerUrl,operationCredential:e.sessionAuthority.operationCredential});return{joined:t.joined,admissionRequest:t.admissionRequest,admissionReceipt:t.admissionReceipt,envelope:e.envelope,factorSecret32:e.factorSecret}}let t=e.pending.phase===`joined`?e.pending.completion.prepared:e.pending;if(!t)throw Error(`NEAR continuation has no encrypted checkpoint`);let n=await _h({home:e.sessionAuthority.operationCredential.home,pending:e.pending,signingEngine:e.context.signingEngine,relayerUrl:e.relayerUrl,credential:e.sessionAuthority.operationCredential.token,traceContext:_n(),factorSecret:e.factorSecret});return{joined:n.joined,admissionReceipt:n.admissionReceipt,admissionRequest:t.admissionRequest,envelope:e.envelope,factorSecret32:e.factorSecret}}async function xh(e){let t=performance.now();try{let n=await V.listPendingWalletRegistrationCommits();for(let r of n){if(r.operation!==`near_provisioning`||r.walletId!==e.sessionAuthority.record.walletId||r.walletAuthMethodId!==e.sessionAuthority.record.authMethodId||r.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`||await V.getPendingWalletRegistrationCommit({registrationCeremonyId:r.registrationCeremonyId,operation:`registration_activate`}))continue;let n=e.context.configs.network.relayer.url,i=yh(r,e.factor),a=bh.bind(void 0,{context:e.context,pending:r,envelope:e.custodyEnvelope,relayerUrl:n,sessionAuthority:e.sessionAuthority,factorSecret:e.ownedFactorSecret});await Nh({context:e.context,walletId:r.walletId,commit:{context:e.context,registrationTiming:null,registrationStartedAt:t,relayerUrl:n,registrationCeremonyId:r.registrationCeremonyId,signedSetup:r.signedSetup,headers:jc(),nearCustodyWork:a,sessionAuthority:e.sessionAuthority,expectedChainTargets:Mr(e.context.configs.network.chains).map(vh),walletId:r.walletId,authMaterial:i}})}}catch(e){console.warn(`[registration] NEAR continuation remains pending`,e instanceof Error?e.message:`continuation failed`)}finally{Up(e.ownedFactorSecret)}}function Sh(e){if(!e)throw Error(`Mixed registration did not start its NEAR custody join`);return e}function Ch(e,t,n,r){if(t.kind!==`already_committed`||t.session.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`NEAR completion must extend the current Wallet Session`);let i=t.session,a=e.record,o=i.walletSession;if(i.walletId!==a.walletId||i.authorizationId!==a.authorizationId||i.quotaId!==a.quotaId||i.walletSessionId!==e.operationCredential.walletSessionId||o.authorityId!==a.authorityId||o.authMethodId!==a.authMethodId||o.issuedAtMs!==a.issuedAtMs||o.expiresAtMs!==a.expiresAtMs||o.authorityRevocationEpoch!==a.authorityRevocationEpoch||o.expiresAtMs<=Date.now()||!fe(a,o)||n.authorityId!==o.authorityId||n.walletId!==o.walletId||n.authorityDigestB64u!==o.authorityDigestB64u||n.revocationEpoch!==o.authorityRevocationEpoch||r.walletAuthMethodId!==o.authMethodId||r.walletId!==o.walletId||r.walletAuthorityId!==o.authorityId)throw Error(`NEAR completion changed the current Wallet Session authority`);return{kind:`registration_established_wallet_session_v2`,walletId:i.walletId,authorizationId:i.authorizationId,walletSessionId:i.walletSessionId,quotaId:i.quotaId,expiresAtMs:i.expiresAtMs,remainingUses:i.remainingUses,walletSession:o,operationCredential:e.operationCredential,tokens:i.tokens}}async function wh(e){let t=await In.readExactWithOperationCredential({walletId:e.record.walletId,authorityId:e.record.authorityId,authMethodId:e.record.authMethodId});if(t.kind!==`found`||t.record.expiresAtMs<=Date.now()||t.record.authorizationId!==e.record.authorizationId||t.record.authorityRevocationEpoch!==e.record.authorityRevocationEpoch||t.operationCredential.token!==e.operationCredential.token)throw Error(`NEAR continuation requires the current unlocked Wallet Session`)}async function Th(e){let t=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.registrationCeremonyId,operation:`near_provisioning`});if(!t||t.operation!==`near_provisioning`||t.phase!==`joined`||t.walletId!==e.walletId||t.walletAuthMethodId!==e.walletAuthMethodId)throw Error(`NEAR joined checkpoint was not persisted`);return t}async function Eh(e){let{metadata:t,materialFacts:n}=e,r={materialActivation:tr(t),lifecycleId:t.scope.lifecycle_id,signingRootVersion:t.scope.root_share_epoch,signingRootId:t.applicationBinding.signing_root_id,signerSetId:t.scope.signer_set_id,thresholdSessionId:n.identity.thresholdSessionId,activationTranscriptB64u:L(t.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(t.activeCapabilityBinding))},i=null;try{i=await ha({material:e.material,activation:r,envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret}),await Kf({store:V,activeClient:i,identity:{walletId:n.identity.walletId,nearAccountId:n.identity.nearAccountId,nearEd25519SigningKeyId:n.identity.nearEd25519SigningKeyId,thresholdSessionId:n.identity.thresholdSessionId,signerSlot:n.identity.signerSlot,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,signingRootId:n.identity.signingRootId,signingRootVersion:n.identity.signingRootVersion,signingWorkerId:n.stableServerScope.routerAbNormalSigning.signingWorkerId},stableServerScope:n.stableServerScope,passkeyPrfFirstB64u:e.passkeyPrfFirstB64u}),await wh(e.sessionAuthority),await e.signingEngine.activateVerifiedNearEd25519YaoMaterial({activeClient:i,facts:{thresholdSessionId:n.identity.thresholdSessionId,signer:cr({walletId:Ie(n.identity.walletId),nearAccountId:z(n.identity.nearAccountId),nearEd25519SigningKeyId:Jt(n.identity.nearEd25519SigningKeyId),signerSlot:n.identity.signerSlot}),signingRootId:n.identity.signingRootId,signingRootVersion:n.identity.signingRootVersion,routerAbNormalSigning:n.stableServerScope.routerAbNormalSigning,runtimePolicyScope:n.stableServerScope.runtimePolicyScope,relayerUrl:e.relayerUrl}}),await wh(e.sessionAuthority),i=null}catch(e){throw i?.dispose(),e}finally{e.ownedFactorSecret.fill(0)}}async function Dh(e){let t=performance.now(),n=`failure`;try{return await e.signingEngine.hydrateSigningSession(e.input),n=`success`,{kind:`completed`}}catch(e){return{kind:`failed`,error:e}}finally{wa({ceremonyId:e.ceremonyId,stage:`session_hydration`,startedAt:t,outcome:n})}}async function Oh(e){let t=performance.now(),n=`failure`;try{return await e.signingEngine.prepareSigningSessionHydration(e.input),n=`success`,{kind:`completed`}}catch(e){return{kind:`failed`,error:e}}finally{wa({ceremonyId:e.ceremonyId,stage:`session_seal_preparation`,startedAt:t,outcome:n})}}function kh(e){let t=s(e.thresholdSessionId);if(!t.ok)throw Error(`Invalid admitted NEAR session identity`);let n=Am(`near-session-client-seal`);return{kind:`preparing`,thresholdSessionId:String(t.value),preparationId:n,result:Oh({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,input:{preparationId:n,thresholdSessionId:String(t.value),prfFirstB64u:e.prfFirstB64u}})}}async function Ah(e){try{await wh(e.sessionAuthority);let t=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.ceremonyId,operation:`near_provisioning`});return!t||t.operation!==`near_provisioning`||t.phase===`joined`||t.walletId!==e.sessionAuthority.record.walletId||t.walletAuthMethodId!==e.sessionAuthority.record.authMethodId?{kind:`none`}:kh({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,thresholdSessionId:t.admissionRequest.scope.threshold_session_id,prfFirstB64u:e.prfFirstB64u})}catch{return{kind:`none`}}}function jh(){return null}async function Mh(e){let t=e.authMaterial,n=performance.now(),r=`failure`,i=null,a=Promise.resolve({kind:`completed`}),o={kind:`none`};try{t.kind===`passkey`&&(o=await Ah({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,sessionAuthority:e.sessionAuthority,prfFirstB64u:t.prfFirstB64u}));let n=await e.nearCustodyWork();i=n.factorSecret32;let s=n.joined,c=`ed25519:${Ee(s.metadata.registeredPublicKey)}`,l=s.activationReference,u=await km({registrationCeremonyId:e.registrationCeremonyId,activationReference:l}),d=await Th({registrationCeremonyId:e.registrationCeremonyId,walletId:e.walletId,walletAuthMethodId:String(e.sessionAuthority.record.authMethodId)});await wh(e.sessionAuthority),t.kind===`passkey`&&o.kind===`none`&&(o=kh({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,thresholdSessionId:s.metadata.scope.threshold_session_id,prfFirstB64u:t.prfFirstB64u}));let f;if(o.kind===`preparing`){let t=performance.now(),n=await o.result;if(wa({ceremonyId:e.registrationCeremonyId,stage:`session_seal_preparation_wait`,startedAt:t,outcome:n.kind===`completed`?`success`:`failure`}),n.kind===`failed`)throw n.error;await wh(e.sessionAuthority);let r=await e.context.signingEngine.readPreparedSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId});f={preparationId:o.preparationId,thresholdSessionId:o.thresholdSessionId,ciphertext:r.ciphertext}}let p=performance.now(),m={relayerUrl:e.relayerUrl,registrationCeremonyId:e.registrationCeremonyId,signedSetup:e.signedSetup,headers:{...e.headers,...te(e.sessionAuthority.operationCredential)},idempotencyKey:u,ed25519:{activationReference:l},walletCustodyCommit:s.commitPayload,onServerTiming:Sa.bind(void 0,e.registrationTiming)},h;if(f){if(e.authMaterial.kind!==`passkey`)throw Error(`Prepared session sealing requires a passkey authority`);h=await Qn({...m,auth:{kind:`passkey`},sessionSeal:{thresholdSessionId:f.thresholdSessionId,ciphertext:f.ciphertext}})}else h=await Qn({...m,auth:e.authMaterial});if(!h.ok)throw Error(`Deferred NEAR provisioning did not complete`);let g=h;if(g.kind!==`near_ed25519`)throw Error(`Deferred Ed25519 finalize returned a different signer branch`);if(g.walletCustody?.status!==`joined`){let e=g.walletCustody?.status??`not_reported`;throw Error(`Deferred NEAR custody join did not commit (${e})`)}if(f&&!g.sessionSeal)throw Error(`Deferred NEAR finalization did not return the prepared session seal`);wa({ceremonyId:e.registrationCeremonyId,stage:`server_finalize`,startedAt:p,outcome:`success`});let _=Ch(e.sessionAuthority,g.registrationEstablishedSession,g.foundingAuthority,g.foundingAuthMethod),v=z(g.ed25519.nearAccountId),y=e.authMaterial.kind===`passkey`?e.authMaterial.credentialIdB64u:``;t.kind===`passkey`?nl({clientPublicKey:c,finalized:g,expectedRpId:t.rpId,expectedWalletId:e.walletId}):rl({clientPublicKey:c,finalized:g,expectedRegistrationAuthorityId:d.auth.kind===`email_otp`?d.auth.registrationAuthorityId:``,expectedWalletId:e.walletId});let b=Qc({admissionRequest:n.admissionRequest,finalized:g.ed25519,walletId:e.walletId,expectedRuntimePolicyScope:I(g.ed25519.runtimePolicyScope)}),x=s.metadata,S=tr(x),C=Wp({established:s,walletId:String(e.walletId),nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,signerSlot:g.ed25519.signerSlot}),w=performance.now(),T=await sd(d,g);await wh(e.sessionAuthority);let E=(await V.publishPendingWalletRegistrationCommitAndRetain({pending:d,ecdsaContinuity:[],authority:g.authority,foundingAuthority:{authority:g.foundingAuthority,authMethod:g.foundingAuthMethod},request:{operation:d.operation,registrationCeremonyId:e.registrationCeremonyId,idempotencyKey:d.idempotencyKey,walletId:e.walletId,walletAuthMethodId:g.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`credential_free_projection`,walletSession:_.walletSession},registration:T})).signerActivations[0];if(!E||E.signerSlot!==g.ed25519.signerSlot)throw Error(`Deferred Ed25519 registration persisted a different signer slot`);let D=new fr;for(let t of e.expectedChainTargets)vd({signingEngine:e.context.signingEngine,walletId:e.walletId,chainTarget:t,trigger:`registration`,statusReads:D});wa({ceremonyId:e.registrationCeremonyId,stage:`local_publication`,startedAt:w,outcome:`success`}),await wh(e.sessionAuthority),e.authMaterial.kind===`passkey`&&_.remainingUses>0&&(a=Dh({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,input:al({session:_,ceremonyId:e.registrationCeremonyId,walletId:String(e.walletId),relayerUrl:e.relayerUrl,prfFirstB64u:e.authMaterial.prfFirstB64u,preparedServerSeal:f&&g.sessionSeal?{preparationId:f.preparationId,...g.sessionSeal}:null,restore:{rpId:e.authMaterial.rpId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,relayerKeyId:g.ed25519.relayerKeyId,participantIds:g.ed25519.participantIds,signerSlot:g.ed25519.signerSlot,credentialIdB64u:e.authMaterial.credentialIdB64u,materialActivation:S}})}));let O=performance.now();await e.context.signingEngine.activateAuthenticatedWalletState({walletId:e.walletId,nearAccountId:v,signerSlot:g.ed25519.signerSlot,nearClient:e.context.nearClient}),await e.context.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:e.walletId,nearAccountId:v,thresholdSessionId:b.identity.thresholdSessionId,runtimePolicyScope:b.stableServerScope.runtimePolicyScope,materialActivation:S,...Gm(t,y,_),nearEd25519SigningKeyId:Jt(g.ed25519.nearEd25519SigningKeyId),signerSlot:g.ed25519.signerSlot}),wa({ceremonyId:e.registrationCeremonyId,stage:`session_install`,startedAt:O,outcome:`success`});let k=performance.now();if(t.kind===`email_otp`&&_.remainingUses>0){let r=await el({registrationEstablishedSession:_,walletId:e.walletId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,thresholdSessionId:b.identity.thresholdSessionId,runtimePolicyScope:b.stableServerScope.runtimePolicyScope,signerSlot:g.ed25519.signerSlot,relayerUrl:e.relayerUrl,emailOtpAuthContext:t.emailOtpAuthContext}),a=Zp({walletId:e.walletId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,sessionState:r,joined:s,deferredNear:{status:`deferred`,admissionRequest:n.admissionRequest},admissionReceipt:n.admissionReceipt,authContext:t.emailOtpAuthContext});await e.context.signingEngine.activateEmailOtpEd25519RegistrationMaterialInternal({walletSession:{walletId:e.walletId,walletSessionUserId:String(e.walletId)},providerSubject:sr(t.emailOtpAuthContext),emailHashHex:ur(t.emailOtpAuthContext),signerSlot:g.ed25519.signerSlot,expectedOperationalPublicKey:c,expectedThresholdSessionId:b.identity.thresholdSessionId,bootstrap:a,material:C,envelope:pa(n.envelope),factorSecret32:i}),i=null}else if(t.kind===`passkey`){if(e.authMaterial.kind!==`passkey`)throw Error(`Deferred passkey registration has no Passkey authorization material`);if(!i)throw Error(`Deferred passkey registration has no custody factor secret`);await Eh({signingEngine:e.context.signingEngine,sessionAuthority:e.sessionAuthority,metadata:x,material:C,materialFacts:b,envelope:pa(n.envelope),ownedFactorSecret:new Uint8Array(i),rpId:e.authMaterial.rpId,credentialIdB64u:e.authMaterial.credentialIdB64u,passkeyPrfFirstB64u:e.authMaterial.prfFirstB64u,relayerUrl:e.relayerUrl}),i=null}e.authMaterial.kind===`passkey`&&await Kd({walletId:String(e.walletId),credentialIdB64u:e.authMaterial.credentialIdB64u,envelope:n.envelope}),wa({ceremonyId:e.registrationCeremonyId,stage:`signer_activation`,startedAt:k,outcome:`success`}),await wh(e.sessionAuthority);let A=performance.now(),j=await a;if(wa({ceremonyId:e.registrationCeremonyId,stage:`session_hydration_wait`,startedAt:A,outcome:j.kind===`completed`?`success`:`failure`}),j.kind===`failed`)throw j.error;await wh(e.sessionAuthority);let M=performance.now();return await V.completePendingNearRegistration({pending:d,walletSession:_.walletSession,operationCredential:_.operationCredential,nearAccountId:String(v)}),wa({ceremonyId:e.registrationCeremonyId,stage:`durable_ready`,startedAt:M,outcome:`success`}),r=`success`,{status:`near_ready`,updatedAtMs:Date.now(),nearAccountId:String(v)}}catch(t){let n=await V.getProfile(String(e.walletId)).catch(jh);if(n?.nearProvisioning?.status===`near_ready`)return n.nearProvisioning;let r=Ph(t);try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:r})}catch{}return{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:Se(t,`registration`,String(e.walletId)),errorCode:r}}finally{await a,o.kind===`preparing`&&(await o.result,await e.context.signingEngine.discardSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}).catch(mh)),i&&Up(i),wa({ceremonyId:e.registrationCeremonyId,stage:`provisioning_total`,startedAt:n,outcome:r}),wa({ceremonyId:e.registrationCeremonyId,stage:`registration_total`,startedAt:e.registrationStartedAt,outcome:r})}}async function Nh(e){try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_provisioning`})}catch(t){let n=Ph(t),r={status:`near_failed_retryable`,updatedAtMs:Date.now(),error:Se(t,`registration`,String(e.walletId)),errorCode:n};try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:n})}catch{}Td(e.walletId,r);return}await Dd({walletId:e.walletId,nowMs:Date.now,attempt:Mh.bind(void 0,e.commit)})}function Ph(e){let t=e instanceof Error?e.message:String(e);return t.includes(`finalize`)?`near_finalize_failed`:t.includes(`seal`)||t.includes(`Yao`)?`near_seal_failed`:t.includes(`wallet session`)?`near_capability_persist_failed`:`near_provisioning_failed`}async function Fh(e){let t=Ph(e.error),n=Se(e.error,`registration`,String(e.walletId));try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:t})}catch{}return Td(e.walletId,{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:n,errorCode:t}),{status:`retryable`,error:n,errorCode:t}}async function Ih(e){try{return await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_pending`}),Td(e.walletId,{status:`near_pending`,updatedAtMs:Date.now()}),{status:`pending`}}catch(t){return await Fh({context:e.context,walletId:e.walletId,error:t})}}async function Lh(e){let{context:t,wallet:n,signerSelection:r}=e,i=e.options||{},{onEvent:a,onError:o,afterCall:s}=i,l=performance.now(),u=new Qa(l),f=_n(),p=null,m=null,h=Fm(n.kind===`provided`?String(n.walletId):`wallet-registration`);$(a,h,{authMethod:e.authMethod.kind,phase:B.STEP_01_STARTED,status:`started`});try{let o=Am(`wallet-registration-finalize`),h=await Xm({context:t,authMethod:e.authMethod,wallet:n,signerSelection:r,recorder:u,passkeyExecution:e.passkeyExecution});e.authMethod.kind===`email_otp`&&mm({recorder:u,warmup:h.registrationWarmup});let{relayerUrl:g,setup:_}=h,v=nh(rh(_,e.kind).ecdsa),y=Zm({passkeyExecution:e.passkeyExecution,ceremonyId:_.registrationCeremonyId}),b={intent:_.intent,registrationIntentDigestB64u:_.registrationIntentDigestB64u},x=b.intent.walletId,S=Fm(String(x)),C=null,w=``,T=``,E=``,D=null,O=null,k=null,A;if(e.authMethod.kind===`passkey`){$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_create`,overlay:`show`}});let n={uiMode:`modal`,behavior:`requireClick`,...e.confirmationConfigOverride??i?.confirmationConfig??{}};k=await u.measure(`authProofMs`,()=>gm({context:t,walletId:x,signerSlot:ih(e),registrationIntentDigestB64u:b.registrationIntentDigestB64u,options:i,confirmationConfigOverride:n,passkeyExecution:e.passkeyExecution})),u.capturePasskeyAuthDiagnostics(k.diagnostics),p=performance.now();let r=d(String(k.credential.rawId||k.credential.id||``).trim());if(!r.ok)throw Error(`passkey credential id ${r.error.message}`);A={kind:`passkey`,webauthnRegistration:k.webauthnRegistration,walletCustodyFactorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Qt({rpId:wp(e.authMethod.rpId),credentialIdB64u:r.value}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId}),walletCustodyFactorSecret:R(k.prfFirstB64u).buffer},$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_create`,overlay:`hide`}})}else{let n=e.authMethod,r=crypto.getRandomValues(new Uint8Array(32));m=r.slice(),O=r.slice().buffer;let i=await u.measure(`authProofMs`,()=>vf({authMethod:n,relayUrl:g,walletId:String(x),registrationIntentDigestB64u:b.registrationIntentDigestB64u}));C=jm({recorder:u,context:t,authMethod:n,relayerUrl:g,walletId:String(x),providerSubject:i.providerSubject,clientSecret32:r}),w=i.registrationAuthorityId,T=i.email,E=i.providerSubject,D=Vm(i.proof),A={kind:`email_otp`,emailOtpRegistrationProof:i.proof,walletCustodyFactorSecret:O}}let j=c(_.walletAuthMethodId);if(!j.ok)throw Error(`Registration setup auth-method identity is invalid: ${j.error.message}`);let M;if(e.authMethod.kind===`passkey`){if(!k)throw Error(`ECDSA registration is missing its verified passkey authority`);M=await ct({authority:{...Xc({walletId:x,rpId:e.authMethod.rpId,credential:k.credential}),bindingId:j.value}})}else{if(!D)throw Error(`Email OTP registration is missing its verified provider`);M=await ct({authority:{...Ot({walletId:x,provider:D,providerUserId:E,emailHashHex:await Bm(T)}),bindingId:j.value}})}$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_STARTED,status:`running`});let N={value:e.kind===`near_ed25519_and_evm_family_ecdsa`?A.walletCustodyFactorSecret.slice(0):null},ee=null,P;try{P=await u.measure(`ecdsaRegistrationTotalMs`,()=>eh({home:_.home,context:t,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signerPlanKind:e.kind,signedSetup:_.signedSetup,ecdsaPrepare:v,clientCeremony:y,authority:A,materialAuthority:M,idempotencyKey:o,resolveActivateEmailOtp:async()=>{let t=null,n=null;if(e.authMethod.kind===`email_otp`){let e=await Zc({material:C,operation:`activate`});t=e.emailOtpEnrollment??null,n=JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Zt({enrollmentId:e.enrollmentId,enrollmentSealKeyVersion:e.enrollmentSealKeyVersion}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId})}return{enrollment:t,walletCustodyFactorJson:n}},traceContext:f,registrationTiming:u,confirmRecoveryCodesBackedUp:Vp.bind(void 0,t,String(x),i.recoveryCodeBackup),persistPendingCommit:async t=>{let n={operation:`registration_activate`,registrationCeremonyId:_.registrationCeremonyId,idempotencyKey:o,walletId:String(x),walletAuthMethodId:String(b.intent.foundingWalletAuthMethodId),signedSetup:String(_.signedSetup),auth:ah({authMethod:e.authMethod,passkeyAuthority:k,email:T,registrationAuthorityId:w,providerSubject:E,emailOtpEnrollment:t.emailOtpEnrollment})};if(t.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){let e=Date.now(),r=ch(Mp({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial,createdAtMs:e,updatedAtMs:e})),i=yn(r,t.deferredNear.admissionRequest);await V.putPendingWalletRegistrationCommits([r,i]),ee=r;return}ee=await sh({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial})},startDeferredNearCustody:hh.bind(void 0,{home:_.home,context:t,factorSecretOwner:N,registrationCeremonyId:_.registrationCeremonyId,relayerUrl:g,signedSetup:String(_.signedSetup),traceContext:f})}))}finally{Up(A.walletCustodyFactorSecret),N.value&&=(Up(N.value),null)}let te=P.session;if(P.activated.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration activate returned a different signer branch`);let F=kp(P.activated),ne=P.activateEmailOtp.enrollment;if(F.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration finalize returned a different signer branch`);if(e.authMethod.kind===`email_otp`&&!nr(F))throw Error(`Email OTP registration finalize returned a different auth method`);u.captureRouteDiagnostics(F.registrationDiagnostics);let re=F.ecdsa.walletKeys;if(re.length===0)throw Error(`Wallet registration finalize did not return ECDSA wallet keys`);let I=await Dp({authMethod:e.authMethod,configs:t.configs,walletId:Ie(F.walletId),finalized:F,passkeyAuthority:k,email:T,providerSubject:E,registrationAuthorityId:w}),L=Ap({walletId:Ie(F.walletId),auth:I,foundingAuthority:F.foundingAuthority,foundingAuthMethod:F.foundingAuthMethod,ecdsa:Op({session:te,walletKeys:re,expectedChainTargets:te.chainTargets})});$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`}),$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let ie=Ie(F.walletId),ae={status:`pending`};e.kind===`near_ed25519_and_evm_family_ecdsa`?(await uh({context:t,relayerUrl:g,registrationTiming:u,pending:ch(ee),plan:L,activated:P.activated}),ae=await Ih({context:t,walletId:ie})):await zp({context:t,relayerUrl:g,registrationTiming:u,plan:L});let oe=fr.fromRegistration(g,L.ecdsa.session.registrationEstablishedSession);for(let e of te.chainTargets)vd({signingEngine:t.signingEngine,walletId:ie,chainTarget:e,trigger:`registration`,statusReads:oe});let se=L.ecdsa.walletKeys[0];if(e.authMethod.kind===`passkey`){if(!k)throw Error(`Passkey registration authority was not collected`);let n=L.ecdsa.session.registrationEstablishedSession;try{await Jp({signingEngine:t.signingEngine,commit:P.walletCustody.commitPayload,passkeyPrfFirstB64u:k.prfFirstB64u,walletId:String(x),walletAuthMethodId:String(L.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(n.walletSessionId),expiresAtMs:n.expiresAtMs})}catch(n){if(e.kind!==`near_ed25519_and_evm_family_ecdsa`)throw n;ae=await Fh({context:t,walletId:ie,error:n})}}else{if(I.kind!==`email_otp`||!m)throw Error(`Email OTP registration has no custody capability material`);let e=L.ecdsa.session.registrationEstablishedSession;await Yp({context:t,commit:P.walletCustody.commitPayload,factorSecret32:m,emailOtpAuthContext:I.emailOtpAuthContext,walletId:String(x),walletSessionId:String(e.walletSessionId),expiresAtMs:e.expiresAtMs})}if(e.kind===`near_ed25519_and_evm_family_ecdsa`){let e=fh({auth:L.auth,emailOtpEnrollment:ne,passkeyAuthority:k});try{Nh({context:t,walletId:ie,commit:{context:t,registrationTiming:u,registrationStartedAt:l,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signedSetup:_.signedSetup,headers:jc(f),nearCustodyWork:Sh.bind(void 0,P.deferredNearCustodyWork),sessionAuthority:{record:L.ecdsa.session.registrationEstablishedSession.walletSession,operationCredential:L.ecdsa.session.registrationEstablishedSession.operationCredential},expectedChainTargets:L.ecdsa.expectedChainTargets,walletId:ie,authMaterial:e}})}catch(e){let t=Ph(e);ae={status:`retryable`,error:Se(e,`registration`,String(ie)),errorCode:t},Td(ie,{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:ae.error,errorCode:t})}}e.kind===`evm_family_ecdsa`&&await V.deletePendingWalletRegistrationCommit({registrationCeremonyId:_.registrationCeremonyId,operation:`registration_activate`});let ce=e.kind===`near_ed25519_and_evm_family_ecdsa`?{success:!0,kind:`ecdsa_wallet_registered_near_pending`,walletId:F.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}],nearProvisioning:ae}:{success:!0,kind:`wallet_registered`,walletId:F.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}]};if($(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_11_COMPLETED,status:`succeeded`}),p!==null){let e=performance.now();ro({callback:i.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-p,traceContext:f}),ro({callback:i.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:f})}return no(eo({recorder:u,authMethod:e.authMethod.kind,signerSet:Pa(e.signerPlan)})),Hh(e.context,ce,e.authMethod.kind),s?.(!0,ce),ce}catch(t){let n=Im(t),r=Se(t,`registration`,h);p!==null&&ro({callback:i.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-p,traceContext:f});let c=Lm(r,n);o?.(c),$(a,h,{authMethod:e.authMethod.kind,phase:B.FAILED,status:`failed`,message:r,interaction:{kind:`passkey_create`,overlay:`hide`},error:{...n?{code:n}:{},message:r}});let l={success:!1,error:r,...n?{errorCode:n}:{}};return no(to({recorder:u,authMethod:e.authMethod.kind,signerSet:Pa(e.signerPlan),errorCode:n||null})),s?.(!1),l}finally{m?.fill(0)}}async function Rh(e){let{context:t,options:n}=e,r=Fm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),i=new Qa(performance.now()),a=null;$(n.onEvent,r,{authMethod:`email_otp`,phase:B.STEP_01_STARTED,status:`started`});try{let r=await Ym({context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:i});mm({recorder:i,warmup:r.registrationWarmup});let{relayerUrl:o,setup:s}=r,c=s.intent.walletId,l=Fm(String(c)),u=await i.measure(`authProofMs`,vf.bind(void 0,{authMethod:e.authMethod,relayUrl:o,walletId:String(c),registrationIntentDigestB64u:s.registrationIntentDigestB64u})),d=crypto.getRandomValues(new Uint8Array(32));a=d.slice();let f=d.slice().buffer,p=jm({recorder:i,context:t,authMethod:e.authMethod,relayerUrl:o,walletId:String(c),providerSubject:u.providerSubject,clientSecret32:d});$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_05_ED25519_SIGNER_PREPARE_STARTED,status:`running`});let m=await i.measure(`walletRegisterStartMs`,Un.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:s.signedSetup,headers:{...jc(),...j(s.home)},kind:`email_otp`,emailOtpRegistrationProof:u.proof}));if(m.kind!==`near_ed25519`)throw Error(`Ed25519-only registration respond returned a different signer branch`);let h=await Zc({material:p,operation:`finalize`}),g;try{g=await t.signingEngine.establishWalletCustodyNearEd25519KeySet({home:s.home,walletId:String(c),factor:{factorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Zt({enrollmentId:h.enrollmentId,enrollmentSealKeyVersion:h.enrollmentSealKeyVersion}),walletAuthMethodId:s.intent.foundingWalletAuthMethodId}),factorSecret:f},nearEd25519SigningKeyId:m.ed25519.admissionRequest.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:s.registrationCeremonyId,admissionRequest:m.ed25519.admissionRequest,admissionReceipt:m.ed25519.admissionReceipt,participantIds:m.ed25519.admissionRequest.participant_ids,routerOrigin:new URL(o).origin,authorization:`Bearer ${String(s.signedSetup)}`})}finally{Up(f)}await Vp(t,String(c),n.recoveryCodeBackup,g.recoveryCodes);let _=rn(g.commitPayload);if(!g.localMaterial)throw Error(`Email OTP registration produced no sealed local custody material`);let v=await km({registrationCeremonyId:s.registrationCeremonyId,activationReference:g.activationReference}),y=await sh({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:v,walletId:String(c),walletAuthMethodId:String(s.intent.foundingWalletAuthMethodId),signedSetup:String(s.signedSetup),auth:{kind:`email_otp`,email:u.email,registrationAuthorityId:u.registrationAuthorityId,providerSubject:u.providerSubject,enrollment:h.emailOtpEnrollment},localMaterial:{keyFamilies:[`ed25519`],custodyCommit:_,ed25519:{activationReference:g.activationReference,localMaterial:g.localMaterial,metadata:Gp(g)}}}),b=`ed25519:${Ee(g.metadata.registeredPublicKey)}`,x=await i.measure(`walletRegisterFinalizeMs`,Qn.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signedSetup:s.signedSetup,headers:{...jc(),...j(s.home)},idempotencyKey:v,ed25519:{activationReference:g.activationReference},auth:{kind:`email_otp`,enrollment:h.emailOtpEnrollment},walletCustodyCommit:_}));if(!x.ok)throw Error(`Deferred NEAR provisioning did not complete`);if(i.captureRouteDiagnostics(x.registrationDiagnostics),x.kind!==`near_ed25519`)throw Error(`Wallet registration finalize returned a different signer branch`);if(!nr(x))throw Error(`Email OTP registration finalize returned a different auth method`);if(x.walletCustody?.status!==`committed`){let e=x.walletCustody?.status??`not_reported`;throw Error(`Wallet custody did not commit (${e})`)}if(x.ed25519.signerSlot!==e.ed25519Selection.signerSlot)throw Error(`Ed25519 Yao finalize returned a different signer slot`);let S=Pc(x.registrationEstablishedSession);rl({clientPublicKey:b,finalized:x,expectedRegistrationAuthorityId:u.registrationAuthorityId,expectedWalletId:c});let C=await Dp({authMethod:e.authMethod,configs:t.configs,walletId:Ie(x.walletId),finalized:x,passkeyAuthority:null,email:u.email,providerSubject:u.providerSubject,registrationAuthorityId:u.registrationAuthorityId});if(C.kind!==`email_otp`)throw Error(`Email OTP Ed25519 registration produced a different persistence authority`);$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_05_ED25519_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let w=Qc({admissionRequest:m.ed25519.admissionRequest,finalized:x.ed25519,walletId:c,expectedRuntimePolicyScope:I(s.intent.runtimePolicyScope)}),T=g.metadata,E=z(x.ed25519.nearAccountId),D=Wp({established:g,walletId:String(x.walletId),nearAccountId:String(E),nearEd25519SigningKeyId:x.ed25519.nearEd25519SigningKeyId,signerSlot:x.ed25519.signerSlot}),O=await tt({walletId:x.walletId,nearAccountId:E,nearEd25519SigningKeyId:x.ed25519.nearEd25519SigningKeyId,email:C.email,registrationAuthorityId:C.registrationAuthorityId,authority:C.authority,signerSlot:x.ed25519.signerSlot,operationalPublicKey:b,relayerKeyId:x.ed25519.relayerKeyId,keyVersion:x.ed25519.keyVersion,participantIds:[...x.ed25519.participantIds],custodyMaterial:D}),k=await V.publishPendingWalletRegistrationCommit({pending:y,ecdsaContinuity:[],authority:x.authority,foundingAuthority:{authority:x.foundingAuthority,authMethod:x.foundingAuthMethod},request:{operation:`near_provisioning`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:v,walletId:x.walletId,walletAuthMethodId:x.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:S.walletSession,operationCredential:S.operationCredential},registration:O});fr.acceptRegistrationSession(o,S);let A=k.signerActivations[1];if(!A||A.signerSlot!==x.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);if(await t.signingEngine.activateAuthenticatedWalletState({walletId:x.walletId,nearAccountId:E,signerSlot:x.ed25519.signerSlot,nearClient:t.nearClient}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:x.walletId,nearAccountId:E,thresholdSessionId:w.identity.thresholdSessionId,runtimePolicyScope:w.stableServerScope.runtimePolicyScope,materialActivation:tr(T),auth:{kind:`email_otp`,providerSubjectId:u.providerSubject},nearEd25519SigningKeyId:Jt(x.ed25519.nearEd25519SigningKeyId),signerSlot:x.ed25519.signerSlot,remainingUses:S.remainingUses,expiresAtMs:S.expiresAtMs}),!a)throw Error(`Email OTP registration has no custody capability material`);await Yp({context:t,commit:_,factorSecret32:a,emailOtpAuthContext:C.emailOtpAuthContext,walletId:String(x.walletId),walletSessionId:String(S.walletSessionId),expiresAtMs:S.expiresAtMs}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_11_COMPLETED,status:`succeeded`});let M={success:!0,kind:`wallet_registered`,walletId:x.walletId,capabilities:[{kind:`near_ed25519`,accountProvisioning:x.accountProvisioning,resolvedAccount:x.resolvedAccount,nearEd25519SigningKeyId:Jt(x.ed25519.nearEd25519SigningKeyId),operationalPublicKey:b,nearAccountId:z(x.ed25519.nearAccountId),transactionId:x.resolvedAccount.kind===`sponsored_named_account`?x.resolvedAccount.transactionHash:null}]};return no(eo({recorder:i,authMethod:`email_otp`,signerSet:Pa(e.signerPlan)})),Hh(t,M,`email_otp`),n.afterCall?.(!0,M),M}catch(t){let a=Im(t),o=Se(t,`registration`,r);n.onError?.(Lm(o,a)),$(n.onEvent,r,{authMethod:`email_otp`,phase:B.FAILED,status:`failed`,message:o,error:{...a?{code:a}:{},message:o}});let s={success:!1,error:o,...a?{errorCode:a}:{}};return no(to({recorder:i,authMethod:`email_otp`,signerSet:Pa(e.signerPlan),errorCode:a||null})),n.afterCall?.(!1),s}finally{a?.fill(0)}}function zh(){}async function Bh(e){let{context:t,options:n}=e,r=Fm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),i=_n(),a=null,o={kind:`none`};$(n.onEvent,r,{authMethod:`passkey`,phase:B.STEP_01_STARTED,status:`started`});try{let r=new Qa(performance.now()),{relayerUrl:s,setup:c}=await Xm({context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:r,passkeyExecution:e.passkeyExecution});r.markNearStage(c.registrationCeremonyId,`near_only.setup`);let l=tl(c.intent),u=Fm(String(l.walletId));$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_create`,overlay:`show`}});let f=c.kind===`near_ed25519`&&c.ed25519.status===`described`?c.ed25519:null,p=gm({context:t,walletId:l.walletId,signerSlot:e.ed25519Selection.signerSlot,registrationIntentDigestB64u:c.registrationIntentDigestB64u,options:n,confirmationConfigOverride:{uiMode:`modal`,behavior:`requireClick`,...e.confirmationConfigOverride??n.confirmationConfig??{}},passkeyExecution:e.passkeyExecution}).then(e=>(a=performance.now(),r.capturePasskeyAuthDiagnostics(e.diagnostics),r.markNearStage(c.registrationCeremonyId,`near_only.authentication`),$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_create`,overlay:`hide`}}),e)),m=zm(n.onEvent,u,B.STEP_05_ED25519_SIGNER_PROVISION_DELAYED),h=async(e,t)=>{let n=await m(Un({relayerUrl:s,registrationCeremonyId:c.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:c.signedSetup,headers:{...jc(i),...j(c.home)},kind:`passkey`,webauthnRegistration:e.webauthnRegistration,...t?{ed25519Execution:t}:{},onServerTiming:Sa.bind(void 0,r)}));if(r.markNearStage(c.registrationCeremonyId,`near_only.respond`),n.kind!==`near_ed25519`)throw Error(`Ed25519-only registration respond returned a different signer branch`);return n.ed25519},g=e=>{let t=d(String(e.credential.rawId||e.credential.id||``).trim());if(!t.ok)throw Error(`passkey credential id ${t.error.message}`);return t.value},_=null,v=t=>(_=R(t.prfFirstB64u).buffer,{factorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Qt({rpId:wp(e.authMethod.rpId),credentialIdB64u:g(t)}),walletAuthMethodId:c.intent.foundingWalletAuthMethodId}),factorSecret:_}),y=(e,n)=>kh({signingEngine:t.signingEngine,ceremonyId:c.registrationCeremonyId,thresholdSessionId:n,prfFirstB64u:e.prfFirstB64u}),b=e=>({home:c.home,walletId:String(l.walletId),nearEd25519SigningKeyId:e.admissionRequest.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:c.registrationCeremonyId,admissionRequest:e.admissionRequest,admissionReceipt:e.admissionReceipt,participantIds:e.admissionRequest.participant_ids,routerOrigin:new URL(s).origin,authorization:`Bearer ${String(c.signedSetup)}`,traceContext:i}),x,S,C;try{if(f){S=f;let e=t.signingEngine.establishWalletCustodyNearEd25519KeySet({...b(f),factor:{factorAfterRouterRound:async()=>v(await p)},executeWithProof:async e=>{let t=await h(await p,JSON.parse(e));if(!Nt(t.admissionReceipt.binding,f.admissionReceipt.binding))throw Error(`Registration respond issued another admission than setup described`);return t.status===`executed`?JSON.stringify(t.activationResult):null}});e.catch(zh),x=await p,o=y(x,f.admissionRequest.scope.threshold_session_id),C=await m(e)}else x=await p,S=await h(x),o=y(x,S.admissionRequest.scope.threshold_session_id),C=await m(t.signingEngine.establishWalletCustodyNearEd25519KeySet({...b(S),factor:v(x)}))}finally{_&&Up(_)}let w={value:g(x)};r.markNearStage(c.registrationCeremonyId,`near_only.custody`),await Vp(t,String(l.walletId),n.recoveryCodeBackup,C.recoveryCodes);let T=rn(C.commitPayload);if(!C.localMaterial)throw Error(`Passkey registration produced no sealed local custody material`);let E=await km({registrationCeremonyId:c.registrationCeremonyId,activationReference:C.activationReference}),D=await sh({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:E,walletId:String(l.walletId),walletAuthMethodId:String(c.intent.foundingWalletAuthMethodId),signedSetup:String(c.signedSetup),auth:{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:w.value,transports:[...x.webauthnRegistration.response.transports]},localMaterial:{keyFamilies:[`ed25519`],custodyCommit:T,ed25519:{activationReference:C.activationReference,localMaterial:C.localMaterial,metadata:Gp(C)}}}),O=`ed25519:${Ee(C.metadata.registeredPublicKey)}`;if(r.markNearStage(c.registrationCeremonyId,`near_only.provision_checkpoint`),o.kind!==`preparing`)throw Error(`NEAR registration session seal preparation is missing`);let k=await o.result;if(k.kind===`failed`)throw k.error;let A=await t.signingEngine.readPreparedSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}),M=await zm(n.onEvent,u,B.STEP_06_RELAY_BOOTSTRAP_DELAYED)(Qn({relayerUrl:s,registrationCeremonyId:c.registrationCeremonyId,signedSetup:c.signedSetup,headers:{...jc(i),...j(c.home)},idempotencyKey:E,ed25519:{activationReference:C.activationReference},auth:{kind:`passkey`},sessionSeal:{thresholdSessionId:o.thresholdSessionId,ciphertext:A.ciphertext},walletCustodyCommit:T}));if(r.markNearStage(c.registrationCeremonyId,`near_only.finalize`),!M.ok||M.kind!==`near_ed25519`)throw Error(`Deferred NEAR provisioning returned a different signer branch`);if(!M.sessionSeal)throw Error(`NEAR finalization did not return the prepared session seal`);if(C.commitPayload&&M.walletCustody?.status!==`committed`){let e=M.walletCustody?.status??`not_reported`,t=M.walletCustody?.status===`rejected`?`: ${M.walletCustody.reason}`:``;throw Error(`Wallet custody did not commit (${e})${t}. The recovery codes shown are not usable.`)}let N=Pc(M.registrationEstablishedSession),ee=nl({clientPublicKey:O,finalized:M,expectedRpId:e.authMethod.rpId,expectedWalletId:l.walletId}),P=z(M.ed25519.nearAccountId),te=Tp({finalized:M,credential:x.credential}),F=Qc({admissionRequest:S.admissionRequest,finalized:M.ed25519,walletId:l.walletId,expectedRuntimePolicyScope:I(l.runtimePolicyScope)}),ne=C.metadata,re=Wp({established:C,walletId:String(M.walletId),nearAccountId:String(P),nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,signerSlot:M.ed25519.signerSlot});await Xp({commit:C.commitPayload,walletId:String(M.walletId),activatedAtMs:Date.now()}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:M.walletId,nearAccountId:z(M.ed25519.nearAccountId),thresholdSessionId:F.identity.thresholdSessionId,runtimePolicyScope:F.stableServerScope.runtimePolicyScope,materialActivation:tr(ne),auth:{kind:`passkey`,rpId:pt(ee.rpId),credentialIdB64u:ee.credentialIdB64u},nearEd25519SigningKeyId:Jt(M.ed25519.nearEd25519SigningKeyId),signerSlot:M.ed25519.signerSlot});let L=et({walletId:M.walletId,nearAccountId:P,nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,rpId:wp(ee.rpId),credential:x.credential,credentialPublicKeyB64u:te,signerSlot:M.ed25519.signerSlot,operationalPublicKey:O,relayerKeyId:M.ed25519.relayerKeyId,keyVersion:M.ed25519.keyVersion,participantIds:[...M.ed25519.participantIds],custodyMaterial:re}),ie=await V.publishPendingWalletRegistrationCommit({pending:D,ecdsaContinuity:[],authority:M.authority,foundingAuthority:{authority:M.foundingAuthority,authMethod:M.foundingAuthMethod},request:{operation:`near_provisioning`,registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:E,walletId:M.walletId,walletAuthMethodId:M.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:N.walletSession,operationCredential:N.operationCredential},registration:L});fr.acceptRegistrationSession(s,N);let ae=ie.signerActivations[1];if(!ae||ae.signerSlot!==M.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);r.markNearStage(c.registrationCeremonyId,`near_only.publication`);let oe=await Dh({signingEngine:t.signingEngine,ceremonyId:c.registrationCeremonyId,input:al({session:N,ceremonyId:c.registrationCeremonyId,walletId:String(M.walletId),relayerUrl:s,prfFirstB64u:x.prfFirstB64u,preparedServerSeal:{preparationId:o.preparationId,...M.sessionSeal},restore:{rpId:ee.rpId,nearAccountId:String(P),nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,relayerKeyId:M.ed25519.relayerKeyId,participantIds:M.ed25519.participantIds,signerSlot:M.ed25519.signerSlot,credentialIdB64u:ee.credentialIdB64u,materialActivation:tr(ne)}})});if(oe.kind===`failed`)throw oe.error;if(o={kind:`consumed`},r.markNearStage(c.registrationCeremonyId,`near_only.session_hydration`),await Eh({signingEngine:t.signingEngine,sessionAuthority:{record:N.walletSession,operationCredential:N.operationCredential},metadata:ne,material:re,materialFacts:F,envelope:Kp(C.commitPayload),ownedFactorSecret:R(x.prfFirstB64u),rpId:ee.rpId,credentialIdB64u:ee.credentialIdB64u,passkeyPrfFirstB64u:x.prfFirstB64u,relayerUrl:s}),r.markNearStage(c.registrationCeremonyId,`near_only.material_activation`),await Jp({signingEngine:t.signingEngine,commit:C.commitPayload,passkeyPrfFirstB64u:x.prfFirstB64u,walletId:String(M.walletId),walletAuthMethodId:String(M.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(N.walletSessionId),expiresAtMs:N.expiresAtMs}),r.markNearStage(c.registrationCeremonyId,`near_only.export_capability`),await t.signingEngine.activateAuthenticatedWalletState({walletId:M.walletId,nearAccountId:P,signerSlot:M.ed25519.signerSlot,nearClient:t.nearClient}),$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),a!==null){let e=performance.now();ro({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-a,traceContext:i}),ro({callback:n.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:i})}r.markNearStage(c.registrationCeremonyId,`near_only.wallet_ready`),no(eo({recorder:r,authMethod:`passkey`,signerSet:Pa(e.signerPlan)}));let se={success:!0,kind:`wallet_registered`,walletId:M.walletId,capabilities:[{kind:`near_ed25519`,accountProvisioning:M.accountProvisioning,resolvedAccount:M.resolvedAccount,nearEd25519SigningKeyId:Jt(M.ed25519.nearEd25519SigningKeyId),operationalPublicKey:O,nearAccountId:z(M.ed25519.nearAccountId),transactionId:M.resolvedAccount.kind===`sponsored_named_account`?M.resolvedAccount.transactionHash:null}]};return Hh(t,se,`passkey`),n.afterCall?.(!0,se),se}catch(e){let t=Im(e),o=Se(e,`registration`,r);a!==null&&ro({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-a,traceContext:i}),n.onError?.(Lm(o,t)),$(n.onEvent,r,{authMethod:`passkey`,phase:B.FAILED,status:`failed`,message:o,interaction:{kind:`passkey_create`,overlay:`hide`},error:{...t?{code:t}:{},message:o}});let s={success:!1,error:o,...t?{errorCode:t}:{}};return n.afterCall?.(!1),s}finally{o.kind===`preparing`&&(await o.result,await t.signingEngine.discardSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}).catch(mh))}}async function Vh(e){let t=em(e.signerSelection),n=Ne(t);if(n){let r=Me(t);if(r)return await Lh({kind:`near_ed25519_and_evm_family_ecdsa`,context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,ecdsaSelection:r,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}});if(e.authMethod.kind===`email_otp`){if(e.passkeyExecution.kind!==`collect_during_registration`)throw Error(`Prepared registration authority requires passkey authentication`);return await Rh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,options:e.options,passkeyExecution:e.passkeyExecution})}return await Bh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}})}let r=Me(t);if(!r)throw Error(`Wallet registration requires an ECDSA signer branch`);return await Lh({kind:`evm_family_ecdsa`,context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ecdsaSelection:r,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}})}function Hh(e,t,n){e.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.walletId,authMethod:n})}async function Uh(e){try{return await Vh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,options:e.options,authenticatorOptions:e.authenticatorOptions,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{},passkeyExecution:{kind:`collect_during_registration`}})}finally{e.context.signingEngine.closeRegistrationPreparationModal()}}function Wh(e,t,n){try{$(e,t,n)}catch{}}function Gh(e,t){try{e?.(t)}catch{}}function Kh(e,t,n){try{t&&n?e?.(!0,n):e?.(!1)}catch{}}function qh(e){let t=[];for(let n of e){let e=String(n.credentialId||``).trim();e&&t.push({id:e,type:`public-key`,transports:Rm(n.transports)})}if(t.length===0)throw Error(`Wallet add-signer requires an existing passkey credential`);return t}function Jh(e,t){let n=String(e.id||``).trim(),r=String(e.rawId||``).trim();if(!n||!r||n!==r)throw Error(`Wallet add-signer selected an invalid passkey credential identity`);for(let e of t)if(e.id===r)return r;throw Error(`Wallet add-signer selected a passkey outside the authorized wallet`)}async function Yh(e){if(e.started.intent.walletId!==e.walletId)throw Error(`Wallet add-signer start returned a different wallet`);if(await gr(e.started.intent)!==e.expectedDigestB64u)throw Error(`Wallet add-signer start returned a different intent`);if(!String(e.started.addSignerCeremonyId||``).trim())throw Error(`Wallet add-signer start returned an invalid ceremony ID`)}function Xh(e,t){return e.length===2&&t.length===2&&e[0]===t[0]&&e[1]===t[1]}function Zh(e){let t=e.started.intent.signerSelection;if(t.mode!==`ed25519`)throw Error(`Wallet add-signer start intent changed signer branch`);let n=t.ed25519,r=e.started.ed25519.admissionRequest,i=e.finalized,a=i.ed25519,o=De(e.clientPublicKey);if(i.walletId!==e.walletId||i.rpId!==e.rpId||i.credentialIdB64u!==e.credentialIdB64u||a.publicKey!==e.clientPublicKey||a.nearAccountId!==o||a.signerSlot!==n.signerSlot||a.keyVersion!==n.keyVersion||a.recoveryExportCapable!==!0||!Xh(a.participantIds,n.participantIds)||a.nearEd25519SigningKeyId!==r.application_binding.near_ed25519_signing_key_id||a.relayerKeyId!==r.scope.signing_worker_id||r.application_binding.wallet_id!==e.walletId||r.application_binding.key_creation_signer_slot!==n.signerSlot)throw Error(`Wallet add-signer finalize returned mismatched Ed25519 Yao identity`);return i}function Qh(e){let t=e.intent.signerSelection;if(t.mode!==`ed25519`)throw Error(`Wallet add-signer start intent changed signer branch`);return{version:e.intent.version,walletId:e.intent.walletId,signerSelection:t,...e.intent.runtimePolicyScope?{runtimePolicyScope:e.intent.runtimePolicyScope}:{},nonceB64u:e.intent.nonceB64u}}async function $h(e){if(e.started.intent.signerSelection.mode!==`ed25519`)throw Error(`Wallet add-signer start returned a different signer branch`);let t=null,n=null,r=null;try{if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody Ed25519 add-signer requires WebAuthn authorization`);let i=await Cf({kind:`verified_passkey_ed25519_yao_add_signer_input_v1`,verifiedIntent:{kind:`verified_passkey_ed25519_add_signer_intent_v1`,intent:Qh(e.started),addSignerIntentDigestB64u:e.intentResponse.addSignerIntentDigestB64u,addSignerIntentGrant:e.intentResponse.addSignerIntentGrant,addSignerCeremonyId:e.started.addSignerCeremonyId},verifiedAuthority:{kind:`verified_passkey_ed25519_add_signer_authority_v1`,walletId:e.walletId,addSignerIntentDigestB64u:e.intentResponse.addSignerIntentDigestB64u,credentialIdB64u:e.credentialIdB64u},admissionRequest:e.started.ed25519.admissionRequest,httpTransport:{kind:`passkey_ed25519_yao_http_transport_v1`,routerOrigin:new URL(e.relayerUrl).origin,fetch:globalThis.fetch}}),a=Ac(e.started.ed25519.custodyEnvelope);if(!a.ok)throw Error(a.reason);r=Uint8Array.from(R(e.passkeyPrfFirstB64u)).buffer;let o=await e.context.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:{kind:`discovery`},preparation:{kind:`fresh`},custodyJson:a.custodyJson,factorSecret:r,nearEd25519SigningKeyId:i.request.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:e.started.addSignerCeremonyId,admissionRequest:i.request,admissionReceipt:i.receipt,participantIds:i.request.participant_ids,routerOrigin:new URL(e.relayerUrl).origin,authorization:`Bearer ${String(e.intentResponse.addSignerIntentGrant)}`}),c=`ed25519:${Ee(o.metadata.registeredPublicKey)}`,l=await rr({relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:Am(`wallet-ed25519-add-signer-finalize`),kind:`near_ed25519`,ed25519:{activationReference:o.activationReference},custodyKeySet:{kind:`near_ed25519_v1`,keyManifestDigestB64u:o.commitPayload.keyManifestDigestB64u,registeredPublicKeyB64u:L(o.metadata.registeredPublicKey)}});if(l.kind!==`near_ed25519`)throw Error(`Wallet add-signer finalize returned a different signer branch`);let u=Zh({finalized:l,started:e.started,walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,clientPublicKey:c});Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let d=await e.context.signingEngine.finalizeWalletEd25519SignerRegistration({walletId:e.walletId,nearAccountId:z(u.ed25519.nearAccountId),nearEd25519SigningKeyId:u.ed25519.nearEd25519SigningKeyId,auth:{kind:`passkey`,credential:e.credential},signerSlot:u.ed25519.signerSlot,operationalPublicKey:c,relayerKeyId:u.ed25519.relayerKeyId,keyVersion:u.ed25519.keyVersion,participantIds:[...u.ed25519.participantIds]});if(d.signerSlot!==u.ed25519.signerSlot)throw Error(`Wallet add-signer persisted a different Ed25519 signer slot`);t=d.rollbackReceipt;let f=e.started.ed25519.admissionRequest,p=s(f.scope.threshold_session_id);if(!p.ok)throw Error(`Wallet add-signer threshold-session identity is invalid`);let m=o.metadata;return await e.context.signingEngine.persistWalletCustodyEd25519Material({binding:{kind:Qe,applicationBindingDigestB64u:o.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:L(m.registeredPublicKey),participantIds:m.participantIds,stateEpoch:String(m.stateEpoch),walletId:String(u.walletId),nearAccountId:String(u.ed25519.nearAccountId),nearEd25519SigningKeyId:u.ed25519.nearEd25519SigningKeyId,signerSlot:u.ed25519.signerSlot,signingWorkerId:m.scope.signing_worker_id,signingWorkerVerifyingShareB64u:L(m.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:o.localMaterial.b64u,nonceB64u:o.localMaterial.nonceB64u}}),n={nearAccountId:u.ed25519.nearAccountId,signerSlot:u.ed25519.signerSlot},await e.context.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:u.walletId,nearAccountId:z(u.ed25519.nearAccountId),thresholdSessionId:p.value,runtimePolicyScope:I(e.started.intent.runtimePolicyScope),materialActivation:tr(m),auth:{kind:`passkey`,rpId:pt(e.rpId),credentialIdB64u:e.credentialIdB64u},nearEd25519SigningKeyId:Jt(u.ed25519.nearEd25519SigningKeyId),signerSlot:u.ed25519.signerSlot}),t=null,Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),{success:!0,kind:`wallet_signer_added`,walletId:u.walletId,capabilities:[{kind:`near_ed25519`,nearEd25519SigningKeyId:Jt(u.ed25519.nearEd25519SigningKeyId),operationalPublicKey:c,nearAccountId:z(u.ed25519.nearAccountId)}]}}catch(r){let i=[];if(n)try{await e.context.signingEngine.deleteWalletCustodyEd25519Material({nearAccountId:n.nearAccountId,signerSlot:n.signerSlot})}catch(e){i.push(e instanceof Error?e.message:String(e))}if(t)try{await e.context.signingEngine.rollbackWalletEd25519SignerRegistration(t)}catch(e){i.push(e instanceof Error?e.message:String(e))}if(i.length>0){let e=r instanceof Error?r.message:String(r);throw Error(`${e}; add-signer cleanup failed: ${i.join(`; `)}`)}throw r}finally{r&&Up(r)}}async function eg(e){if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody ECDSA add-signer requires WebAuthn authorization`);let t=await Ad({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}),n=Uint8Array.from(R(e.passkeyPrfFirstB64u)).buffer,r;try{r=await Wc({context:e.context,relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,started:e.started.ecdsa,custodyEnvelope:e.started.ecdsa.custodyEnvelope,factorSecret:n,authority:t,registrationTiming:null})}finally{Up(n)}let i={relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:Am(`wallet-add-signer-finalize`),kind:`evm_family_ecdsa`,ecdsa:{expectedKeyHandles:[r.bootstrap.keyHandle]},custodyKeySet:r.custodyKeySet},a;try{a=await rr(i)}catch(e){if(!(e instanceof TypeError))throw e;a=await rr(i)}if(a.kind!==`evm_family_ecdsa`||a.walletId!==e.walletId||a.rpId!==e.rpId)throw Error(`Wallet add-signer finalize returned a different ECDSA identity`);let o=a.ecdsa.walletKeys,s=o[0];if(!s)throw Error(`Wallet add-signer finalize did not return ECDSA wallet keys`);let c=await Gc({context:e.context,pending:r});Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let l=await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ie(e.walletId),session:c,walletKeys:[s,...o.slice(1)]});return await e.context.signingEngine.storeWalletEcdsaSignerRecords({walletId:e.walletId,walletKeys:l}),await V.adoptAddedEcdsaSignerAuthority({authority:a.authority,materialActivation:c.materialActivation}),Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),{success:!0,kind:`wallet_signer_added`,walletId:e.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:s.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:s.thresholdEcdsaPublicKeyB64u}]}}async function tg(e){switch(e.signerSelection.mode){case`ed25519`:if(e.started.kind!==`near_ed25519`)throw Error(`Wallet add-signer start returned a different signer branch`);return await $h({context:e.input.context,walletId:e.input.walletId,rpId:e.input.rpId,relayerUrl:e.input.relayerUrl,intentResponse:e.input.intentResponse,credential:e.input.credential,credentialIdB64u:e.input.credentialIdB64u,passkeyPrfFirstB64u:e.input.passkeyPrfFirstB64u,eventAccountId:e.input.eventAccountId,onEvent:e.input.onEvent,started:e.started});case`ecdsa`:if(e.started.kind!==`evm_family_ecdsa`)throw Error(`Wallet add-signer start returned a different signer branch`);return await eg({context:e.input.context,walletId:e.input.walletId,rpId:e.input.rpId,relayerUrl:e.input.relayerUrl,intentResponse:e.input.intentResponse,credential:e.input.credential,credentialIdB64u:e.input.credentialIdB64u,passkeyPrfFirstB64u:e.input.passkeyPrfFirstB64u,eventAccountId:e.input.eventAccountId,onEvent:e.input.onEvent,started:e.started});default:return q(e.signerSelection)}}async function ng(e){let{context:t,signerSelection:n}=e,r=e.options||{},i=qt(String(e.walletId||``).trim()),a=Fm(String(i)),o=wp(String(e.rpId||``).trim());Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_01_STARTED,status:`started`});try{let e=String(t.configs.network.relayer.url||``).trim();if(!e)throw Error(`addSigner requires relayer.url`);let s=Od(t.configs);if(!s)throw Error(`addSigner requires registration.publishableKey and registration.projectEnvironmentId`);let c=await Xn({relayerUrl:e,walletId:i,request:{walletId:i,rpId:o,signerSelection:n},auth:{publishableKey:s.publishableKey,environmentId:s.projectEnvironmentId}});if(await gr(c.intent)!==c.addSignerIntentDigestB64u)throw Error(`Add-signer intent digest mismatch`);Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_assert`,overlay:`show`}});let l=qh(await V.listProfileAuthenticators(String(i))),u=await t.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(i),challengeB64u:c.addSignerIntentDigestB64u,allowCredentials:l,includeSecondPrfOutput:!1}),d=Jh(u,l),f=wl(u,`Wallet add-signer authorization`);Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let p=await Vn({relayerUrl:e,walletId:i,addSignerIntentGrant:c.addSignerIntentGrant,addSignerIntentDigestB64u:c.addSignerIntentDigestB64u,intent:c.intent,auth:{kind:`webauthn_assertion`,rpId:o,credential:zn(u),expectedChallengeDigestB64u:c.addSignerIntentDigestB64u}});await Yh({started:p,walletId:i,expectedDigestB64u:c.addSignerIntentDigestB64u});let m=await tg({input:{context:t,walletId:i,rpId:o,relayerUrl:e,intentResponse:c,credential:u,credentialIdB64u:d,passkeyPrfFirstB64u:f,eventAccountId:a,onEvent:r.onEvent},signerSelection:n,started:p});return Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),Kh(r.afterCall,!0,m),m}catch(e){let t=Im(e),n=Se(e,`registration`,a);Gh(r.onError,Lm(n,t)),Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.FAILED,status:`failed`,message:n,interaction:{kind:`passkey_assert`,overlay:`hide`},error:{...t?{code:t}:{},message:n}});let i={success:!1,error:n,...t?{errorCode:t}:{}};return Kh(r.afterCall,!1),i}}export{cu as $,Jr as $t,Ad as A,qs as At,Iu as B,Eo as Bt,vf as C,oc as Ct,qd as D,hc as Dt,Bd as E,dc as Et,Ed as F,Xs as Ft,mu as G,va as Gt,xu as H,so as Ht,vd as I,Us as It,du as J,fa as Jt,lu as K,ga as Kt,gd as L,Hs as Lt,Od as M,Ls as Mt,wd as N,Is as Nt,Kd as O,_c as Ot,Cd as P,Ps as Pt,iu as Q,ra as Qt,_d as R,zs as Rt,Tf as S,Dc as St,ff as T,rc as Tt,wu as U,co as Ut,Fu as V,ho as Vt,Cu as W,_a as Wt,au as X,Ni as Xt,pu as Y,pa as Yt,ou as Z,ua as Zt,Pf as _,Ac as _t,Uh as a,Nr as an,Zl as at,ep as b,Cc as bt,Cp as c,Hl as ct,xp as d,Pl as dt,Ir as en,ru as et,bp as f,Nl as ft,op as g,Jc as gt,ip as h,wl as ht,Om as i,Mr as in,Rl as it,kd as j,Rs as jt,Md as k,Ys as kt,Sp as l,Ql as lt,pp as m,Cl as mt,Em as n,Pr as nn,Ll as nt,Bp as o,Vl as ot,dp as p,Tl as pt,fu as q,ha as qt,Tm as r,Vr as rn,Fl as rt,Dm as s,Xl as st,ng as t,Fr as tn,eu as tt,yp as u,Ml as ut,tp as v,bc as vt,hf as w,ic as wt,qf as x,Sc as xt,Kf as y,xc as yt,md as z,ss as zt};
|
|
1
|
+
import{n as e}from"./chunk-dVx5-UGu.js";import{D as t,I as n,M as r,N as i,O as a,R as o,S as s,T as c,h as l,i as u,j as d,o as f,r as p,s as m,w as h,x as g}from"./domainIds-C3fUa33Q.js";import{C as _,M as v,O as y,S as b,c as x,d as S,f as C,g as w,j as T,k as E,l as D,n as O,t as k,u as A}from"./chains-CPmd4s9f.js";import{O as j,S as M,_ as N,b as ee,c as P,k as te,v as F,w as ne,x as re,y as I}from"./primitives-CTmDwMNc.js";import{i as L,r as R}from"./base64-BmKR3UqU.js";import{r as ie}from"./secureRandomId-8LSc91aN.js";import{s as ae}from"./walletDbName-BxWApBQF.js";import{c as oe,d as se,f as ce,l as le,s as ue,u as de}from"./signingSessionSeal-DqbjG8c8.js";import{a as fe,i as pe,n as me}from"./activeWalletSession-BpbnpU9s.js";import{d as he,g as ge,h as _e,m as ve}from"./capabilityKinds-D0Yrp9uf.js";import{i as ye,n as be,r as xe}from"./canonicalPrimitives-BMP5yILS.js";import{n as Se,o as Ce,t as we}from"./errors-ADOZT8oV.js";import{c as Te,d as Ee,r as De,t as z}from"./accountIds-Cpvlkvbe.js";import{c as Oe,d as ke,i as Ae,l as je,n as Me,r as Ne,s as Pe}from"./registrationSignerPlan-BHkqlian.js";import{a as Fe,c as Ie,i as Le,o as Re,r as ze,s as Be}from"./ecdsaChainTarget-DkOrgv4y.js";import{c as Ve,d as He,h as Ue,m as We,n as Ge,s as Ke}from"./signerDomain-BFqRQ0Jl.js";import{i as qe,n as Je,r as Ye,t as Xe}from"./singletons-CAsc9LvA.js";import{L as Ze,M as Qe,d as $e,f as et,p as tt,u as nt}from"./accountLifecycle-fLNUdjct.js";import{d as rt}from"./walletAuthority-BY3kyKQ-.js";import{Et as it,H as at,Jt as ot,K as st,Nt as ct,Ot as lt,Pt as ut,Q as dt,St as ft,T as pt,Yt as mt,at as ht,en as gt,et as _t,gt as vt,ht as yt,jt as bt,kt as xt,nn as St,q as Ct,tn as wt,tt as Tt,vt as Et,w as Dt,xt as Ot,yt as kt}from"./emailOtpEcdsaDerivationIdentity-CupWCKNg.js";import{D as At,F as jt,I as Mt,J as Nt,K as Pt,P as Ft,S as It,T as Lt,U as Rt,X as zt,b as Bt,k as Vt,n as Ht,q as Ut,x as Wt}from"./challengeDelivery-CG2J5Qxs.js";import{l as Gt}from"./digestEncoding-aC4dSf_x.js";import{r as Kt}from"./walletAuthMethodRecord-CWdqdY_s.js";import{a as qt,i as Jt,r as Yt,t as Xt}from"./registrationIds-B1OpqRAt.js";import{a as Zt,c as Qt,d as $t,f as en,h as tn,l as nn,n as rn,r as an,u as on}from"./passkey-custody-Ba-NQ_4C.js";import{A as sn,B as cn,I as ln,N as un,P as dn,i as fn,j as pn}from"./ecdsaCapabilityManifest-DRc423SV.js";import{g as mn,i as B,p as hn,s as gn}from"./sdkSentEvents-DujYAPEM.js";import{C as _n,S as vn,b as yn,c as bn,g as xn,r as Sn,u as V,v as Cn,w as wn,x as Tn,y as En}from"./walletCustodyEcdsaContinuity-mGh1Ysko.js";import{t as Dn}from"./signerSlot-FJAGOhmg.js";import{c as On,o as kn,s as An}from"./wallet-recovery-DFaS3geI.js";import{n as jn}from"./authenticatorOptions-2_XK8aXv.js";import{X as Mn,j as Nn}from"./walletOwnershipGeneration-DSGfjuV2.js";import{c as Pn,r as Fn}from"./types-CQTWmtqu.js";import{o as In}from"./walletSessionAuthorizationStore-DnUMtkev.js";import{l as Ln,o as Rn,u as zn}from"./helpers-DS0bksx9.js";import{i as Bn}from"./profileAccountProjection-BNVJLOt2.js";import{A as Vn,C as Hn,E as Un,O as Wn,S as Gn,T as Kn,c as qn,d as Jn,f as Yn,h as Xn,n as Zn,p as Qn,r as $n,s as er,t as tr,x as nr,y as rr}from"./nearEd25519YaoMaterialActivation-DgWDGRI_.js";import{A as ir,a as ar,d as or,f as sr,j as cr,o as lr,u as ur}from"./nearEd25519YaoSigningPreparation-yKDLQXBS.js";import{n as dr}from"./lanes-BzU7cv2T.js";import{t as fr}from"./walletSessionAuthorizationStatus-ONPRiEbK.js";import{n as pr}from"./prfCache-BAFh1skJ.js";import{u as mr}from"./trace-CsRMlSh1.js";import{t as hr}from"./webauthnPromptCoordinator-9bVeHcTZ.js";import{t as gr}from"./intentDigest-Rh5Mg8X7.js";import{n as _r,t as vr}from"./pendingWalletRecoveryCodeBackup-DOeIn_Qj.js";import{n as yr}from"./walletSessionAuthorizationProjection-DuU6w0FP.js";function br(){return Reflect.get(globalThis,`__SEAMS_REGISTRATION_BENCHMARK_DIAGNOSTICS`)===!0}function xr(){}function Sr(e){if(e.keySet!==`near_ed25519_v1`)throw Error(`The custody worker began an EVM run for a NEAR request`);return e}function Cr(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker began a NEAR run for an EVM request`);return e}function wr(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker completed a NEAR run for an EVM request`);return e}function Tr(e){switch(e.origin){case`establish`:case`establish_factor_after_round`:return{origin:`establish`,walletId:e.walletId};case`join`:return{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret};case`recover`:return{origin:`recover`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode};case`recover_and_reseal`:return{origin:`recover_and_reseal`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode,replacementFactorJson:e.replacementFactorJson,replacementFactorSecret:e.replacementFactorSecret};default:return Dr(e)}}async function Er(e){switch(e.origin){case`establish`:return{kind:`establish`,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:e.recoveryCodesJson};case`establish_factor_after_round`:{let t=await e.factor();return{kind:`establish`,factorJson:t.factorJson,factorSecret:t.factorSecret,recoveryCodesJson:e.recoveryCodesJson}}case`join`:case`recover`:return{kind:`existing`};case`recover_and_reseal`:return{kind:`recover_reseal`,replacementFactorJson:e.replacementFactorJson,replacementFactorSecret:e.replacementFactorSecret};default:return Dr(e)}}function Dr(e){throw Error(`Unsupported wallet custody origin: ${String(e)}`)}function Or(e,t){if(e.walletId!==t.activation.walletId)throw Error(`EVM custody activation changed the wallet identity`);if(e.keyManifestDigestB64u!==t.activation.keyManifestDigestB64u)throw Error(`EVM custody activation changed the key manifest digest`);if(e.clientRootPublicKey33B64u!==t.activation.clientRootPublicKey33B64u)throw Error(`EVM custody activation changed the client root public key`)}function kr(e,t,n){if(br())try{console.info(`[WalletCustody] timing `+JSON.stringify({event:`wallet_custody_timing`,ceremonyId:e,stage:`custody.${t}`,durationMs:Math.round((performance.now()-n)*10)/10,outcome:`success`}))}catch{}}async function Ar(e){let t=e.ceremonyId||ie(`wallet-custody-ceremony`,32,`wallet custody ceremony IDs`),{custody:n,keySetRun:r}=e,i=!1;try{if(r.keySet===`near_ed25519_v1`){let a=performance.now(),o;if(r.checkpointJson!==void 0){if(n.origin!==`join`)throw Error(`Checkpoint restoration requires existing custody`);o=(await e.runStep(`restoreNearRegistration`,{ceremonyId:t,custodyJson:n.custodyJson,factorSecret:n.factorSecret,checkpointJson:r.checkpointJson})).yaoExecuteRequestJson}else o=Sr(await e.runStep(`beginWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`near_ed25519_v1`,custody:Tr(n),protocolInputsJson:r.protocolInputsJson})).yaoExecuteRequestJson;if(kr(t,`begin`,a),i=!0,r.beforeRouterRound){a=performance.now();let n=await e.runStep(`checkpointNearRegistration`,{ceremonyId:t});kr(t,`checkpoint`,a),await r.beforeRouterRound(n.checkpointJson)}a=performance.now();let s=await r.runRouterRound(o);kr(t,`router_round`,a),a=performance.now(),await e.runStep(`completeWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`near_ed25519_v1`,protocolResultJson:s,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u}),kr(t,`complete`,a),await r.afterRouterRoundCompleted?.(s),a=performance.now();let c=await e.runStep(`finishWalletCustodyKeySetRun`,{ceremonyId:t,finish:await Er(n)});return kr(t,`finish`,a),c}if(n.origin===`establish_factor_after_round`)throw Error(`An EVM custody run seals under its factor before the relayer round`);let a=await e.runStep(`beginWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`evm_family_ecdsa_v1`,custody:n,protocolInputsJson:r.protocolInputsJson,evmFamilySigningKeySlotId:r.evmFamilySigningKeySlotId,recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});i=!0;let o=Cr(a);await r.beforeRelayerRound();let s=await r.runRelayerRound({contextBinding32B64u:o.ecdsaContextBinding32B64u,clientSharePublicKey33B64u:o.ecdsaClientSharePublicKey33B64u,clientShareRetryCounter:o.ecdsaClientShareRetryCounter,preActivationCommitPayload:o.preActivationCommitPayload}),c=wr(await e.runStep(`completeWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`evm_family_ecdsa_v1`,protocolResultJson:s}));return Or(o.preActivationCommitPayload,c),{...o.preActivationCommitPayload,clientRootPublicKey33B64u:c.activation.clientRootPublicKey33B64u,ecdsaReadyStateBlobB64u:c.activation.ecdsaReadyStateBlobB64u,ecdsaPublicFacts:c.activation.ecdsaPublicFacts}}catch(n){throw i&&await e.runStep(`discardWalletCustodyCeremony`,{ceremonyId:t}).catch(xr),n}}const jr=[1,2];function Mr(e){let t=[],n=new Set;for(let r of e){let e=k(r.network);if(e!==`evm`&&e!==`tempo`)continue;let i=Le(r),a=Re(i);n.has(a)||(n.add(a),t.push({chainTarget:i}))}return t}function Nr(e){let t=[],n=new Set;for(let r of e.chains){let i=k(r.network);if(i!==`evm`&&i!==`tempo`||!(i===`tempo`?e.signerOptions.tempo:e.signerOptions.evm).enabled)continue;let a=Le(r),o=Re(a);n.has(o)||(n.add(o),t.push({chainTarget:a}))}return t}function Pr(e){for(let t of e.signers)if(t.kind===`near_ed25519`)return!0;return!1}function Fr(e){let t=e.ecdsaChainTargets??Lr(e.configs,e.options);return Rr(e.accountProvisioning??Ae(),t)}function Ir(e){let t=null;for(let n of e.configs.network.chains)if(O(n.network)){t=Vr(e);break}return Rr(t,Lr(e.configs,e.options))}function Lr(e,t){let n=Nr({signerOptions:t.signerOptions??e.signing.thresholdEcdsa.provisioningDefaults,chains:e.network.chains}),r=[];for(let e of n)r.push(e.chainTarget);return r}function Rr(e,t){let n=[];if(e&&n.push({kind:`near_ed25519`,accountProvisioning:e,signerSlot:1,participantIds:[...M],derivationVersion:1}),t.length&&n.push({kind:`evm_family_ecdsa`,chainTargets:[...t],participantIds:[...jr]}),!n.length)throw Error(`Wallet registration requires at least one configured, enabled signer`);return{kind:`signer_set`,signers:n}}function zr(e){let t=Te(e);if(!t.ok)throw Error(t.message);return ke(t.value)}function Br(e){let t=String(e.walletId||``).trim(),n=String(e.relayerAccountId||``).trim();if(!t)throw Error(`Relayer named NEAR registration requires walletId`);if(!n)throw Error(`Relayer named NEAR registration requires relayer accountId`);return zr(`${t}.${n}`)}function Vr(e){let t=e.preference??e.configs.registration.nearAccountProvisioning;switch(t.kind){case`implicit_account`:return Ae();case`relayer_named_subaccount`:if(e.wallet.kind!==`provided`)throw Error(`Relayer named NEAR registration requires a provided walletId`);return Br({walletId:e.wallet.walletId,relayerAccountId:e.configs.network.relayer.accountId});default:return t}}function Hr(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function Ur(e,t){let n=s(e);if(!n.ok)throw Error(`${t} is invalid`);return n.value}function Wr(e,t){if(!Array.isArray(e)||e.length!==32)throw Error(`${t} must contain exactly 32 bytes`);let n=[];for(let r of e){if(typeof r!=`number`||!Number.isInteger(r)||r<0||r>255)throw Error(`${t} must contain exactly 32 bytes`);n.push(r)}return Object.freeze(n)}function Gr(e,t){if(!Array.isArray(e)||e.length===0)throw Error(`${t} must contain bytes`);return e.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`${t} must contain bytes`);return e})}function Kr(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||e[0]<1||e[1]<1||e[0]===e[1])throw Error(`participantIds must contain two distinct positive integers`);return[Number(e[0]),Number(e[1])]}function qr(e){let t=E(e,`capability.registrationContinuity`);if(t.kind===`recovery`)return{kind:`recovery`,activationTranscript:Gr(t.activationTranscript,`capability.registrationContinuity.activationTranscript`)};if(t.kind!==`registration`)throw Error(`capability.registrationContinuity kind is invalid`);let n=Pt(t.admissionRequest),r=Rt(t.admissionReceipt);if(!n.ok)throw Error(`capability registration continuity transcript is invalid: ${n.message}`);if(!r.ok)throw Error(`capability registration continuity transcript is invalid: ${r.message}`);return{kind:`registration`,admissionRequest:n.value,admissionReceipt:r.value,activationTranscript:Gr(t.activationTranscript,`capability.registrationContinuity.activationTranscript`)}}function Jr(e){let t=E(e,`capability`);if(t.kind!==`router_ab_ed25519_yao_active_capability_v1`)throw Error(`Yao recovery capability kind is invalid`);let n=E(t.applicationBinding,`capability.applicationBinding`),r=E(t.lifecycle,`capability.lifecycle`),i;try{i=gt(t.materialActivation)}catch(e){throw Error(`capability.materialActivation is invalid: ${e instanceof Error?e.message:String(e)}`)}return{materialActivation:i,activeCapabilityBinding:Wr(t.activeCapabilityBinding,`capability.activeCapabilityBinding`),registeredPublicKey:Wr(t.registeredPublicKey,`capability.registeredPublicKey`),nearAccountId:z(T(t.nearAccountId,`capability.nearAccountId`)),applicationBinding:{wallet_id:T(n.wallet_id,`applicationBinding.wallet_id`),near_ed25519_signing_key_id:T(n.near_ed25519_signing_key_id,`applicationBinding.near_ed25519_signing_key_id`),signing_root_id:T(n.signing_root_id,`applicationBinding.signing_root_id`),key_creation_signer_slot:Hr(n.key_creation_signer_slot,`applicationBinding.key_creation_signer_slot`)},participantIds:Kr(t.participantIds),runtimePolicyScope:I(E(t.runtimePolicyScope,`capability.runtimePolicyScope`)),lifecycle:{lifecycleId:T(r.lifecycleId,`lifecycle.lifecycleId`),rootShareEpoch:T(r.rootShareEpoch,`lifecycle.rootShareEpoch`),accountId:T(r.accountId,`lifecycle.accountId`),thresholdSessionId:Ur(T(r.thresholdSessionId,`lifecycle.thresholdSessionId`),`lifecycle.thresholdSessionId`),signerSetId:T(r.signerSetId,`lifecycle.signerSetId`),signingWorkerId:T(r.signingWorkerId,`lifecycle.signingWorkerId`)},stateEpoch:Hr(t.stateEpoch,`capability.stateEpoch`),registrationContinuity:qr(t.registrationContinuity)}}var Yr=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,oi.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,oi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmactivatedclientv1_free(e,0)}create_signing_share(e,t,n,r,i){let a=H(n,K.__wbindgen_malloc),o=G,s=U(r,K.__wbindgen_malloc,K.__wbindgen_realloc),c=G,l=H(i,K.__wbindgen_malloc),u=G,d=K.wasmactivatedclientv1_create_signing_share(this.__wbg_ptr,e,t,a,o,s,c,l,u);if(d[2])throw W(d[1]);return Xr.__wrap(d[0])}static import_linked_material(t,n,r,i){let a=H(t,K.__wbindgen_malloc),o=G,s=U(i,K.__wbindgen_malloc,K.__wbindgen_realloc),c=G,l=K.wasmactivatedclientv1_import_linked_material(a,o,n,r,s,c);if(l[2])throw W(l[1]);return e.__wrap(l[0])}static import_local_material(t,n,r,i,a,o,s,c,l){let u=H(t,K.__wbindgen_malloc),d=G,f=H(n,K.__wbindgen_malloc),p=G,m=H(r,K.__wbindgen_malloc),h=G,g=H(i,K.__wbindgen_malloc),_=G,v=H(a,K.__wbindgen_malloc),y=G,b=H(l,K.__wbindgen_malloc),x=G,S=K.wasmactivatedclientv1_import_local_material(u,d,f,p,m,h,g,_,v,y,o,s,c,b,x);if(S[2])throw W(S[1]);return e.__wrap(S[0])}registered_public_key(){let e=K.wasmactivatedclientv1_registered_public_key(this.__wbg_ptr);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}seal_local_material(e,t,n){let r=H(e,K.__wbindgen_malloc),i=G,a=H(t,K.__wbindgen_malloc),o=G,s=H(n,K.__wbindgen_malloc),c=G,l=K.wasmactivatedclientv1_seal_local_material(this.__wbg_ptr,r,i,a,o,s,c);if(l[3])throw W(l[2]);var u=vi(l[0],l[1]).slice();return K.__wbindgen_free(l[0],l[1]*1,1),u}state_epoch(){let e=K.wasmactivatedclientv1_state_epoch(this.__wbg_ptr);return BigInt.asUintN(64,e)}};Symbol.dispose&&(Yr.prototype[Symbol.dispose]=Yr.prototype.free);var Xr=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,si.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,si.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmclientsigningsharev1_free(e,0)}client_commitments_json(){let e,t;try{let n=K.wasmclientsigningsharev1_client_commitments_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}client_signature_share_b64u(){let e,t;try{let n=K.wasmclientsigningsharev1_client_signature_share_b64u(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}client_verifying_share(){let e=K.wasmclientsigningsharev1_client_verifying_share(this.__wbg_ptr);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}};Symbol.dispose&&(Xr.prototype[Symbol.dispose]=Xr.prototype.free);var Zr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ci.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e,0)}complete(e){let t=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),n=G,r=K.wasmed25519yaoclientrootexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw W(r[1]);return ti.__wrap(r[0])}execute_request_json(){let e,t;try{let n=K.wasmed25519yaoclientrootexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),m=G,h=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),g=G,_=H(i,K.__wbindgen_malloc),v=G,y=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),b=G,x=H(o,K.__wbindgen_malloc),S=G,C=H(s,K.__wbindgen_malloc),w=G,T=H(c,K.__wbindgen_malloc),E=G,D=H(l,K.__wbindgen_malloc),O=G,k=H(u,K.__wbindgen_malloc),A=G,j=H(d,K.__wbindgen_malloc),M=G,N=H(f,K.__wbindgen_malloc),ee=G,P=K.wasmed25519yaoclientrootexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee);if(P[2])throw W(P[1]);return this.__wbg_ptr=P[0],ci.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(Zr.prototype[Symbol.dispose]=Zr.prototype.free);var Qr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,li.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaolaneclientv1_free(e,0)}complete(e){let t=K.wasmed25519yaolaneclientv1_complete(this.__wbg_ptr,e);if(t[2])throw W(t[1]);return W(t[0])}execute_request_json(){let e,t;try{let i=K.wasmed25519yaolaneclientv1_execute_request_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}constructor(){return this.__wbg_ptr=K.wasmed25519yaolaneclientv1_new(),li.register(this,this.__wbg_ptr,this),this}prepare(e,t,n,r,i,a,o,s,c,l){gi(a,$r);let u=H(o,K.__wbindgen_malloc),d=G,f=H(s,K.__wbindgen_malloc),p=G,m=H(c,K.__wbindgen_malloc),h=G,g=H(l,K.__wbindgen_malloc),_=G,v=K.wasmed25519yaolaneclientv1_prepare(this.__wbg_ptr,e,t,n,r,i,a.__wbg_ptr,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return W(v[0])}};Symbol.dispose&&(Qr.prototype[Symbol.dispose]=Qr.prototype.free);var $r=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,ui.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ui.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaolanesourcev1_free(e,0)}constructor(e,t,n,r,i,a){let o=H(e,K.__wbindgen_malloc),s=G,c=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),l=G,u=H(n,K.__wbindgen_malloc),d=G,f=H(r,K.__wbindgen_malloc),p=G,m=H(i,K.__wbindgen_malloc),h=G,g=H(a,K.__wbindgen_malloc),_=G,v=K.wasmed25519yaolanesourcev1_new(o,s,c,l,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return this.__wbg_ptr=v[0],ui.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&($r.prototype[Symbol.dispose]=$r.prototype.free);var ei=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,di.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmed25519yaosourcepreservingregistrationsessionv1_free(e,0)}constructor(e,t,n,r,i,a,o,s,c){gi(i,$r);let l=H(a,K.__wbindgen_malloc),u=G,d=H(o,K.__wbindgen_malloc),f=G,p=H(s,K.__wbindgen_malloc),m=G,h=H(c,K.__wbindgen_malloc),g=G,_=K.wasmed25519yaosourcepreservingregistrationsessionv1_new(e,t,n,r,i.__wbg_ptr,l,u,d,f,p,m,h,g);if(_[2])throw W(_[1]);return this.__wbg_ptr=_[0],di.register(this,this.__wbg_ptr,this),this}take_execute_request_json(){let e,t;try{let i=K.wasmed25519yaosourcepreservingregistrationsessionv1_take_execute_request_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(ei.prototype[Symbol.dispose]=ei.prototype.free);var ti=class e{static __wrap(t){let n=Object.create(e.prototype);return n.__wbg_ptr=t,fi.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,fi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmexporteded25519seedv1_free(e,0)}take_export_artifact_json(){let e,t;try{let i=K.wasmexporteded25519seedv1_take_export_artifact_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,W(i[2]);return e=n,t=r,xi(n,r)}finally{K.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(ti.prototype[Symbol.dispose]=ti.prototype.free);var ni=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,pi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmordinaryed25519activationclientmaterialv1_free(e,0)}destroy(){K.wasmordinaryed25519activationclientmaterialv1_destroy(this.__wbg_ptr)}constructor(e,t,n,r,i,a){let o=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),s=G,c=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),l=G,u=U(n,K.__wbindgen_malloc,K.__wbindgen_realloc),d=G,f=H(r,K.__wbindgen_malloc),p=G,m=U(i,K.__wbindgen_malloc,K.__wbindgen_realloc),h=G,g=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),_=G,v=K.wasmordinaryed25519activationclientmaterialv1_new(o,s,c,l,u,d,f,p,m,h,g,_);if(v[2])throw W(v[1]);return this.__wbg_ptr=v[0],pi.register(this,this.__wbg_ptr,this),this}take_client_material(){let e=K.wasmordinaryed25519activationclientmaterialv1_take_client_material(this.__wbg_ptr);if(e[3])throw W(e[2]);var t=vi(e[0],e[1]).slice();return K.__wbindgen_free(e[0],e[1]*1,1),t}};Symbol.dispose&&(ni.prototype[Symbol.dispose]=ni.prototype.free);var ri=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,mi.unregister(this),e}free(){let e=this.__destroy_into_raw();K.__wbg_wasmwalletcustodyseedexportsessionv1_free(e,0)}complete(e){let t=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),n=G,r=K.wasmwalletcustodyseedexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw W(r[1]);return ti.__wrap(r[0])}execute_request_json(){let e,t;try{let n=K.wasmwalletcustodyseedexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],xi(n[0],n[1])}finally{K.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=U(e,K.__wbindgen_malloc,K.__wbindgen_realloc),m=G,h=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),g=G,_=H(i,K.__wbindgen_malloc),v=G,y=U(a,K.__wbindgen_malloc,K.__wbindgen_realloc),b=G,x=H(o,K.__wbindgen_malloc),S=G,C=H(s,K.__wbindgen_malloc),w=G,T=H(c,K.__wbindgen_malloc),E=G,D=H(l,K.__wbindgen_malloc),O=G,k=H(u,K.__wbindgen_malloc),A=G,j=H(d,K.__wbindgen_malloc),M=G,N=H(f,K.__wbindgen_malloc),ee=G,P=K.wasmwalletcustodyseedexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,ee);if(P[2])throw W(P[1]);return this.__wbg_ptr=P[0],mi.register(this,this.__wbg_ptr,this),this}};Symbol.dispose&&(ri.prototype[Symbol.dispose]=ri.prototype.free);function ii(e,t,n,r,i,a,o,s,c,l,u,d,f,p){let m=H(e,K.__wbindgen_malloc),h=G,g=U(t,K.__wbindgen_malloc,K.__wbindgen_realloc),_=G,v=H(n,K.__wbindgen_malloc),y=G,b=H(r,K.__wbindgen_malloc),x=G,S=H(i,K.__wbindgen_malloc),C=G,w=H(a,K.__wbindgen_malloc),T=G,E=H(o,K.__wbindgen_malloc),D=G,O=H(s,K.__wbindgen_malloc),k=G,A=H(d,K.__wbindgen_malloc),j=G,M=H(f,K.__wbindgen_malloc),N=G,ee=H(p,K.__wbindgen_malloc),P=G,te=K.openWalletCustodyEd25519MaterialV1(m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,c,l,u,A,j,M,N,ee,P);if(te[2])throw W(te[1]);return Yr.__wrap(te[0])}function ai(){let e={__proto__:null,__wbg_Error_92b29b0548f8b746:function(e,t){return Error(xi(e,t))},__wbg_Number_9a4e0ecb0fa16705:function(e){return Number(e)},__wbg_String_8564e559799eccda:function(e,t){let n=U(String(t),K.__wbindgen_malloc,K.__wbindgen_realloc),r=G;bi().setInt32(e+4,r,!0),bi().setInt32(e+0,n,!0)},__wbg___wbindgen_bigint_get_as_i64_d968e41184ae354f:function(e,t){let n=t,r=typeof n==`bigint`?n:void 0;bi().setBigInt64(e+8,Ti(r)?BigInt(0):r,!0),bi().setInt32(e+0,!Ti(r),!0)},__wbg___wbindgen_boolean_get_fa956cfa2d1bd751:function(e){let t=e,n=typeof t==`boolean`?t:void 0;return Ti(n)?16777215:n?1:0},__wbg___wbindgen_debug_string_c25d447a39f5578f:function(e,t){let n=U(_i(t),K.__wbindgen_malloc,K.__wbindgen_realloc),r=G;bi().setInt32(e+4,r,!0),bi().setInt32(e+0,n,!0)},__wbg___wbindgen_in_aca499c5de7ff5e5:function(e,t){return e in t},__wbg___wbindgen_is_bigint_2f76dc55065b4273:function(e){return typeof e==`bigint`},__wbg___wbindgen_is_function_1ff95bcc5517c252:function(e){return typeof e==`function`},__wbg___wbindgen_is_object_a27215656b807791:function(e){let t=e;return typeof t==`object`&&!!t},__wbg___wbindgen_is_string_ea5e6cc2e4141dfe:function(e){return typeof e==`string`},__wbg___wbindgen_is_undefined_c05833b95a3cf397:function(e){return e===void 0},__wbg___wbindgen_jsval_eq_e659fcf7b0e32763:function(e,t){return e===t},__wbg___wbindgen_jsval_loose_eq_db4c3b15f63fc170:function(e,t){return e==t},__wbg___wbindgen_number_get_394265ed1e1b84ee:function(e,t){let n=t,r=typeof n==`number`?n:void 0;bi().setFloat64(e+8,Ti(r)?0:r,!0),bi().setInt32(e+0,!Ti(r),!0)},__wbg___wbindgen_string_get_b0ca35b86a603356:function(e,t){let n=t,r=typeof n==`string`?n:void 0;var i=Ti(r)?0:U(r,K.__wbindgen_malloc,K.__wbindgen_realloc),a=G;bi().setInt32(e+4,a,!0),bi().setInt32(e+0,i,!0)},__wbg___wbindgen_throw_344f42d3211c4765:function(e,t){throw Error(xi(e,t))},__wbg_call_8a2dd23819f8a60a:function(){return wi(function(e,t){return e.call(t)},arguments)},__wbg_call_a6e5c5dce5018821:function(){return wi(function(e,t,n){return e.call(t,n)},arguments)},__wbg_crypto_38df2bab126b63dc:function(e){return e.crypto},__wbg_done_89b2b13e91a60321:function(e){return e.done},__wbg_entries_015dc610cd81ede0:function(e){return Object.entries(e)},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return wi(function(e,t){e.getRandomValues(t)},arguments)},__wbg_get_507a50627bffa49b:function(e,t){return e[t>>>0]},__wbg_get_78f252d074a84d0b:function(){return wi(function(e,t){return Reflect.get(e,t)},arguments)},__wbg_get_c7eb1f358a7654df:function(){return wi(function(e,t){return Reflect.get(e,t)},arguments)},__wbg_get_unchecked_6e0ad6d2a41b06f6:function(e,t){return e[t>>>0]},__wbg_get_with_ref_key_6412cf3094599694:function(e,t){return e[t]},__wbg_instanceof_ArrayBuffer_4480b9e0068a8adb:function(e){let t;try{t=e instanceof ArrayBuffer}catch{t=!1}return t},__wbg_instanceof_Map_e5b5e3db98422fcc:function(e){let t;try{t=e instanceof Map}catch{t=!1}return t},__wbg_instanceof_Uint8Array_309b927aaf7a3fc7:function(e){let t;try{t=e instanceof Uint8Array}catch{t=!1}return t},__wbg_isArray_0677c962b281d01a:function(e){return Array.isArray(e)},__wbg_isSafeInteger_04f36e4056f1b851:function(e){return Number.isSafeInteger(e)},__wbg_iterator_6f722e4a93058b71:function(){return Symbol.iterator},__wbg_length_1f0964f4a5e2c6d8:function(e){return e.length},__wbg_length_370319915dc99107:function(e){return e.length},__wbg_msCrypto_bd5a034af96bcba6:function(e){return e.msCrypto},__wbg_new_cd45aabdf6073e84:function(e){return new Uint8Array(e)},__wbg_new_da52cf8fe3429cb2:function(){return{}},__wbg_new_with_length_e6785c33c8e4cce8:function(e){return new Uint8Array(e>>>0)},__wbg_next_6dbf2c0ac8cde20f:function(e){return e.next},__wbg_next_71f2aa1cb3d1e37e:function(){return wi(function(e){return e.next()},arguments)},__wbg_node_84ea875411254db1:function(e){return e.node},__wbg_process_44c7a14e11e9f69e:function(e){return e.process},__wbg_prototypesetcall_4770620bbe4688a0:function(e,t,n){Uint8Array.prototype.set.call(vi(e,t),n)},__wbg_randomFillSync_6c25eac9869eb53c:function(){return wi(function(e,t){e.randomFillSync(t)},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return wi(function(){return module.require},arguments)},__wbg_set_6be42768c690e380:function(e,t,n){e[t]=n},__wbg_set_8535240470bf2500:function(){return wi(function(e,t,n){return Reflect.set(e,t,n)},arguments)},__wbg_static_accessor_GLOBAL_4ef717fb391d88b7:function(){let e=typeof global>`u`?null:global;return Ti(e)?0:hi(e)},__wbg_static_accessor_GLOBAL_THIS_8d1badc68b5a74f4:function(){let e=typeof globalThis>`u`?null:globalThis;return Ti(e)?0:hi(e)},__wbg_static_accessor_SELF_146583524fe1469b:function(){let e=typeof self>`u`?null:self;return Ti(e)?0:hi(e)},__wbg_static_accessor_WINDOW_f2829a2234d7819e:function(){let e=typeof window>`u`?null:window;return Ti(e)?0:hi(e)},__wbg_subarray_3ed232c8a6baee09:function(e,t,n){return e.subarray(t>>>0,n>>>0)},__wbg_value_a5d5488a9589444a:function(e){return e.value},__wbg_versions_276b2795b1c6a219:function(e){return e.versions},__wbindgen_cast_0000000000000001:function(e){return e},__wbindgen_cast_0000000000000002:function(e){return e},__wbindgen_cast_0000000000000003:function(e,t){return vi(e,t)},__wbindgen_cast_0000000000000004:function(e,t){return xi(e,t)},__wbindgen_cast_0000000000000005:function(e){return BigInt.asUintN(64,e)},__wbindgen_init_externref_table:function(){let e=K.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}};return{__proto__:null,"./router_ab_ed25519_yao_client_bg.js":e}}const oi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmactivatedclientv1_free(e,1)),si=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmclientsigningsharev1_free(e,1)),ci=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e,1)),li=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaolaneclientv1_free(e,1)),ui=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaolanesourcev1_free(e,1)),di=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmed25519yaosourcepreservingregistrationsessionv1_free(e,1)),fi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmexporteded25519seedv1_free(e,1)),pi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmordinaryed25519activationclientmaterialv1_free(e,1)),mi=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>K.__wbg_wasmwalletcustodyseedexportsessionv1_free(e,1));function hi(e){let t=K.__externref_table_alloc();return K.__wbindgen_externrefs.set(t,e),t}function gi(e,t){if(!(e instanceof t))throw Error(`expected instance of ${t.name}`)}function _i(e){let t=typeof e;if(t==`number`||t==`boolean`||e==null)return`${e}`;if(t==`string`)return`"${e}"`;if(t==`symbol`){let t=e.description;return t==null?`Symbol`:`Symbol(${t})`}if(t==`function`){let t=e.name;return typeof t==`string`&&t.length>0?`Function(${t})`:`Function`}if(Array.isArray(e)){let t=e.length,n=`[`;t>0&&(n+=_i(e[0]));for(let r=1;r<t;r++)n+=`, `+_i(e[r]);return n+=`]`,n}let n=/\[object ([^\]]+)\]/.exec(toString.call(e)),r;if(n&&n.length>1)r=n[1];else return toString.call(e);if(r==`Object`)try{return`Object(`+JSON.stringify(e)+`)`}catch{return`Object`}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}function vi(e,t){return e>>>=0,Ci().subarray(e/1,e/1+t)}let yi=null;function bi(){return(yi===null||yi.buffer.detached===!0||yi.buffer.detached===void 0&&yi.buffer!==K.memory.buffer)&&(yi=new DataView(K.memory.buffer)),yi}function xi(e,t){return Oi(e>>>0,t)}let Si=null;function Ci(){return(Si===null||Si.byteLength===0)&&(Si=new Uint8Array(K.memory.buffer)),Si}function wi(e,t){try{return e.apply(this,t)}catch(e){let t=hi(e);K.__wbindgen_exn_store(t)}}function Ti(e){return e==null}function H(e,t){let n=t(e.length*1,1)>>>0;return Ci().set(e,n/1),G=e.length,n}function U(e,t,n){if(n===void 0){let n=ki.encode(e),r=t(n.length,1)>>>0;return Ci().subarray(r,r+n.length).set(n),G=n.length,r}let r=e.length,i=t(r,1)>>>0,a=Ci(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=Ci().subarray(i+o,i+r),a=ki.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return G=o,i}function W(e){let t=K.__wbindgen_externrefs.get(e);return K.__externref_table_dealloc(e),t}let Ei=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});Ei.decode();let Di=0;function Oi(e,t){return Di+=t,Di>=2146435072&&(Ei=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),Ei.decode(),Di=t),Ei.decode(Ci().subarray(e,e+t))}const ki=new TextEncoder;`encodeInto`in ki||(ki.encodeInto=function(e,t){let n=ki.encode(e);return t.set(n),{read:e.length,written:n.length}});let G=0,K;function Ai(e,t){return K=e.exports,yi=null,Si=null,K.__wbindgen_start(),K}async function ji(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function Mi(e){if(K!==void 0)return K;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`)),e===void 0&&(e=new URL(`router_ab_ed25519_yao_client_bg.wasm`,import.meta.url));let t=ai();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await ji(await e,t);return Ai(n,r)}const Ni=`router_ab_ed25519_yao_active_client_v1`;function Pi(e){switch(e.authorization.kind){case`passkey`:return{protocol:e.protocol,authorization:{kind:`passkey`,webauthnAuthentication:zn(e.authorization.webauthnAuthentication)}};case`email_otp_factor`:return{protocol:e.protocol,authorization:{kind:`email_otp_factor`,providerSubjectId:e.authorization.providerSubjectId,walletAuthMethodId:e.authorization.walletAuthMethodId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode}}}}const Fi=Symbol(`router-ab-ed25519-yao-active-client-construction`);function Ii(e,t){if(!(e instanceof Uint8Array)||e.length!==32)throw Error(`${t} must contain 32 bytes`);return e}function Li(e){return e.authorization.kind===`passkey`}function Ri(e){switch(e.kind){case`wallet_custody_seed_v1`:return ri;case`ed25519_yao_client_root_v1`:return Zr;default:return Gi(e.kind)}}function zi(e){let t=[JSON.stringify(e.admission),JSON.stringify(e.applicationBinding),e.participantIds[0],e.participantIds[1],e.custodyEnvelope.factorSecret,e.custodyEnvelope.bindingJson,e.custodyEnvelope.nonce,e.custodyEnvelope.ciphertext,e.custodyEnvelope.aadHash,e.custodyEnvelope.ciphertextDigest,e.entropy.recipientKeyMaterial,e.entropy.deriverASealSeed,e.entropy.deriverBSealSeed];return new(Ri(e.custodyEnvelope))(...t)}function Bi(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Object.keys(e);if(t.length!==4||![`kind`,`challengeId`,`loginGrant`,`expiresAtMs`].every(e=>t.includes(e))||Reflect.get(e,`kind`)!==`email_otp_login_grant`)return null;let n=Reflect.get(e,`challengeId`),r=Reflect.get(e,`loginGrant`),i=Reflect.get(e,`expiresAtMs`);return typeof n!=`string`||n.trim().length===0||typeof r!=`string`||r.trim().length===0||typeof i!=`number`||!Number.isSafeInteger(i)||i<=0?null:{kind:`email_otp_login_grant`,challengeId:n,loginGrant:r}}function Vi(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Router export admission response must be an object`);let t=Object.keys(e),n=t.length===1&&t[0]===`protocol`,r=t.length===2&&t.includes(`protocol`)&&t.includes(`factorRelease`);if(!n&&!r)throw Error(`Router export admission response contains unexpected fields`);let i=Ft(Reflect.get(e,`protocol`));if(!i.ok)throw Error(i.message);return n?{kind:`protocol_only`,protocol:i.value}:{kind:`protocol_with_factor_release`,protocol:i.value,factorRelease:Bi(Reflect.get(e,`factorRelease`))}}function Hi(){return{recipientKeyMaterial:qi(),deriverASealSeed:qi(),deriverBSealSeed:qi()}}function Ui(e){e.recipientKeyMaterial.fill(0),e.deriverASealSeed.fill(0),e.deriverBSealSeed.fill(0)}function Wi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function Gi(e){throw Error(`Unhandled Ed25519 Yao Client lifecycle: ${String(e)}`)}function Ki(e){switch(e.kind){case`active`:return e.activated;case`disposed`:throw Error(`Ed25519 Yao Client state is disposed`);default:return Gi(e)}}function qi(){let e=new Uint8Array(32);do globalThis.crypto.getRandomValues(e);while(e.every(Ji));return e}function Ji(e){return e===0}function Yi(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Client commitments must be an object`);let n=Object.keys(t);if(n.length!==2||!n.includes(`hiding`)||!n.includes(`binding`))throw Error(`Client commitments contain unexpected fields`);let r=Reflect.get(t,`hiding`),i=Reflect.get(t,`binding`);if(typeof r!=`string`||typeof i!=`string`)throw Error(`Client commitments must contain hiding and binding strings`);return{hiding:r,binding:i}}function Xi(e,t){let n=t.binding.ceremony.lifecycle;return n.lifecycle_id===e.scope.lifecycle_id&&n.root_share_epoch===e.scope.root_share_epoch&&n.account_id===e.scope.account_id&&n.session_id===e.scope.threshold_session_id&&n.signer_set_id===e.scope.signer_set_id&&n.selected_server_id===e.scope.signing_worker_id&&St(t.binding.ceremony.material_activation,e.scope.material_activation)&&t.binding.state_epoch===e.state_epoch&&Wi(t.binding.registered_public_key,e.registered_public_key)&&Wi(t.binding.runtime_policy_binding,e.runtime_policy_binding)&&Wi(t.binding.authorization_digest,e.authorization.authorization_digest)}function Zi(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Ed25519 Yao export artifact must be an object`);let n=Object.keys(t).sort(),r=[`artifactKind`,`privateKey`,`publicKey`];if(n.length!==r.length||n.some((e,t)=>e!==r[t]))throw Error(`Ed25519 Yao export artifact contains unexpected fields`);if(Reflect.get(t,`artifactKind`)!==`near-ed25519-seed-v1`||typeof Reflect.get(t,`publicKey`)!=`string`||typeof Reflect.get(t,`privateKey`)!=`string`||!String(Reflect.get(t,`publicKey`)).startsWith(`ed25519:`)||!String(Reflect.get(t,`privateKey`)).startsWith(`ed25519:`))throw Error(`Ed25519 Yao export artifact is invalid`);let i=Reflect.get(t,`publicKey`),a=Reflect.get(t,`privateKey`);if(typeof i!=`string`||typeof a!=`string`)throw Error(`Ed25519 Yao export artifact is invalid`);return{artifactKind:`near-ed25519-seed-v1`,publicKey:i,privateKey:a}}function Qi(e){let t=new URL(e.routerOrigin);if(t.protocol!==`http:`&&t.protocol!==`https:`||t.pathname!==`/`)throw Error(`Router origin must be an HTTP origin without a path`);if(t.search||t.hash)throw Error(`Router origin must not contain query or hash`);if(typeof e.fetch!=`function`)throw Error(`Router fetch is required`);switch(e.authorization.kind){case`bearer`:if(!e.authorization.value.trim())throw Error(`Router bearer authorization is required`);break;case`recovery_challenge`:if(!e.authorization.challengeId.trim())throw Error(`Router recovery challenge ID is required`);break;case`cookies`:break}return{routerOrigin:t.origin,routing:e.routing,authorization:e.authorization,fetch:e.fetch,traceContext:$i(e.traceContext)}}function $i(e){if(!e)return _n();if(e.kind!==`router_ab_trace_context_v1`)throw Error(`Router trace context kind is invalid`);let t=wn(e.value);if(!t.ok)throw Error(t.message);return t.value}async function ea(e){let t=e.headers.get(`Server-Timing`),n;try{n=await e.json()}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}if(e.ok){let r=t||ta(e.url);return{ok:!0,value:n,...r?{serverTiming:r}:{}}}let r=C(n)?.code;return{ok:!1,message:JSON.stringify(n),...typeof r==`string`?{code:r}:{}}}function ta(e){if(!e||typeof performance>`u`||typeof performance.getEntriesByName!=`function`)return null;let t=performance.getEntriesByName(e,`resource`);for(let e=t.length-1;e>=0;--e){let n=t[e];if(!n||n.entryType!==`resource`)continue;let r=na(Reflect.get(n,`serverTiming`));if(r)return r}return null}function na(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=String(Reflect.get(n,`name`)||``).trim(),r=Number(Reflect.get(n,`duration`));/^[a-z0-9_]+$/.test(e)&&(!Number.isFinite(r)||r<0||t.push(`${e};dur=${r}`))}return t.length>0?t.join(`, `):null}var ra=class{config;constructor(e){this.config=Qi(e)}async send(e){let t;try{let n=!(e.kind===`export_admit`||e.kind===`export_execute`)&&this.config.authorization.kind===`bearer`?this.config.authorization.value:null,r=e.kind===`recovery_admit`&&this.config.authorization.kind===`recovery_challenge`?this.config.authorization.challengeId:null,i=this.config.authorization.kind===`cookies`;t=await this.config.fetch.call(globalThis,new URL(e.path,this.config.routerOrigin),{method:`POST`,headers:{...da(this.config.routing),...n?{authorization:n}:{},...r?{[Lt]:r}:{},"content-type":`application/json`,[vn]:this.config.traceContext.value},credentials:i?`include`:`omit`,body:JSON.stringify(e.body)})}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}return ea(t)}},ia=class{activeMetadata;lifecycle;constructor(e){if(e[Fi]!==!0)throw Error(`Ed25519 Yao Client state requires verified WASM completion`);this.activeMetadata={kind:e.metadata.kind,scope:{lifecycle_id:e.metadata.scope.lifecycle_id,root_share_epoch:e.metadata.scope.root_share_epoch,account_id:e.metadata.scope.account_id,threshold_session_id:e.metadata.scope.threshold_session_id,signer_set_id:e.metadata.scope.signer_set_id,signing_worker_id:e.metadata.scope.signing_worker_id,material_activation:e.metadata.scope.material_activation},applicationBinding:{wallet_id:e.metadata.applicationBinding.wallet_id,near_ed25519_signing_key_id:e.metadata.applicationBinding.near_ed25519_signing_key_id,signing_root_id:e.metadata.applicationBinding.signing_root_id,key_creation_signer_slot:e.metadata.applicationBinding.key_creation_signer_slot},participantIds:[e.metadata.participantIds[0],e.metadata.participantIds[1]],registeredPublicKey:e.metadata.registeredPublicKey.slice(),signingWorkerVerifyingShare:e.metadata.signingWorkerVerifyingShare.slice(),stateEpoch:e.metadata.stateEpoch,transcript:e.metadata.transcript.slice(),activeCapabilityBinding:[...e.metadata.activeCapabilityBinding],materialActivation:e.metadata.materialActivation},this.lifecycle={kind:`active`,activated:e.activated}}sealLocalMaterial(e){let t=Ki(this.lifecycle);try{return{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:e.nonce.slice(),ciphertext:t.seal_local_material(Ii(e.ownedPasskeyPrfFirst,`passkey PRF.first`),e.binding,e.nonce)}}finally{e.ownedPasskeyPrfFirst.fill(0)}}async createSigningShare(e){let t=Ki(this.lifecycle),n=Ii(e.admittedDigest,`admitted digest`),r=Ii(e.signingWorkerVerifyingShare,`SigningWorker verifying share`);if(!Wi(r,this.activeMetadata.signingWorkerVerifyingShare))throw Error(`SigningWorker verifying share does not match activated Client state`);let i=t.create_signing_share(this.activeMetadata.participantIds[0],this.activeMetadata.participantIds[1],n,JSON.stringify(e.signingWorkerCommitments),r);try{return{clientCommitments:Yi(i.client_commitments_json()),clientVerifyingShare:i.client_verifying_share(),clientSignatureShareB64u:i.client_signature_share_b64u()}}finally{i.free()}}metadata(){return{kind:this.activeMetadata.kind,scope:{lifecycle_id:this.activeMetadata.scope.lifecycle_id,root_share_epoch:this.activeMetadata.scope.root_share_epoch,account_id:this.activeMetadata.scope.account_id,threshold_session_id:this.activeMetadata.scope.threshold_session_id,signer_set_id:this.activeMetadata.scope.signer_set_id,signing_worker_id:this.activeMetadata.scope.signing_worker_id,material_activation:this.activeMetadata.scope.material_activation},applicationBinding:{wallet_id:this.activeMetadata.applicationBinding.wallet_id,near_ed25519_signing_key_id:this.activeMetadata.applicationBinding.near_ed25519_signing_key_id,signing_root_id:this.activeMetadata.applicationBinding.signing_root_id,key_creation_signer_slot:this.activeMetadata.applicationBinding.key_creation_signer_slot},participantIds:[this.activeMetadata.participantIds[0],this.activeMetadata.participantIds[1]],registeredPublicKey:this.activeMetadata.registeredPublicKey.slice(),signingWorkerVerifyingShare:this.activeMetadata.signingWorkerVerifyingShare.slice(),stateEpoch:this.activeMetadata.stateEpoch,transcript:this.activeMetadata.transcript.slice(),activeCapabilityBinding:[...this.activeMetadata.activeCapabilityBinding],materialActivation:this.activeMetadata.materialActivation}}status(){switch(this.lifecycle.kind){case`active`:return{kind:`active`};case`disposed`:return{kind:`disposed`};default:return Gi(this.lifecycle)}}dispose(){switch(this.lifecycle.kind){case`active`:{let e=this.lifecycle.activated;this.lifecycle={kind:`disposed`},e.free();return}case`disposed`:return;default:return Gi(this.lifecycle)}}};function aa(e){let t=null;try{return t=Yr.import_local_material(Ii(e.ownedPasskeyPrfFirst,`passkey PRF.first`),e.binding,e.sealed.nonce,e.sealed.ciphertext,e.metadata.registeredPublicKey,e.metadata.stateEpoch,e.metadata.participantIds[0],e.metadata.participantIds[1],e.metadata.signingWorkerVerifyingShare),new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedPasskeyPrfFirst.fill(0)}}function oa(e){let t=null;try{if(t=Yr.import_linked_material(Ii(e.ownedClientScalarShare,`linked-device Ed25519 Client share`),e.metadata.participantIds[0],e.metadata.participantIds[1],JSON.stringify(e.publicReceipt)),t.state_epoch()!==e.metadata.stateEpoch||!Wi(t.registered_public_key(),e.metadata.registeredPublicKey)||!Wi(e.publicReceipt.signing_worker_verifying_share,e.metadata.signingWorkerVerifyingShare))throw Error(`linked-device Ed25519 material metadata does not match its receipt`);return new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedClientScalarShare.fill(0)}}function sa(e){let t=null;try{return t=ii(e.ownedFactorSecret,e.envelope.bindingJson,e.envelope.nonce,e.envelope.ciphertext,e.envelope.aadHash,e.envelope.ciphertextDigest,e.applicationBindingDigest,e.metadata.registeredPublicKey,e.metadata.stateEpoch,e.metadata.participantIds[0],e.metadata.participantIds[1],e.metadata.signingWorkerVerifyingShare,e.sealed.nonce,e.sealed.ciphertext),new ia({[Fi]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedFactorSecret.fill(0)}}let ca=null;function la(e){throw ca=null,e}var ua=class e{constructor(){}static async initializeBundled(){return ca??=Mi().catch(la),await ca,new e}importLocalMaterial(e){return aa(e)}importLinkedMaterial(e){return oa(e)}openCustodyCache(e){return sa(e)}async exportSeed(e){let t=await e.transport.send({kind:`export_admit`,path:Wt,body:Pi({protocol:e.request,authorization:e.authorization})});if(!t.ok)return t;let n;try{n=Vi(t.value)}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}if(!Xi(e.request,n.protocol))return{ok:!1,message:`Router export admission does not match the requested exact capability`};let r;if(Li(e)){if(n.kind!==`protocol_only`)return{ok:!1,message:`Passkey export admission returned an Email OTP factor release`};r=e.custodyEnvelope}else{if(n.kind!==`protocol_with_factor_release`)return{ok:!1,message:`Email OTP export admission did not return the matching factor release`};let t=n.factorRelease;if(!t||t.challengeId!==e.authorization.challengeId)return{ok:!1,message:`Email OTP export admission did not return the matching factor release`};try{r=await e.resolveCustodyEnvelope(t)}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}let i=Hi(),a;try{a=zi({admission:n.protocol,applicationBinding:e.request.application_binding,participantIds:e.request.participant_ids,custodyEnvelope:r,entropy:i})}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}finally{r.factorSecret.fill(0),Ui(i)}try{let t=jt(JSON.parse(a.execute_request_json()));if(!t.ok)return{ok:!1,message:t.message};let n=await e.transport.send({kind:`export_execute`,path:It,body:{protocol:t.value}});if(!n.ok)return n;let r=Mt(n.value);if(!r.ok)return{ok:!1,message:r.message};let i=a.complete(JSON.stringify(r.value));try{return{ok:!0,artifact:Zi(i.take_export_artifact_json())}}finally{i.free()}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}finally{a.free()}}};function da(e){switch(e.kind){case`discovery`:return{};case`direct`:case`regional`:return j(e);default:return Gi(e)}}function fa(e){return{materialActivation:e.materialActivation,lifecycleId:e.scope.lifecycle_id,signingRootVersion:e.scope.root_share_epoch,signingRootId:e.applicationBinding.signing_root_id,signerSetId:e.scope.signer_set_id,thresholdSessionId:e.scope.threshold_session_id,activationTranscriptB64u:L(e.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(e.activeCapabilityBinding))}}function pa(e){if(!tn(e.binding))throw Error(`wallet custody cache accepts wallet custody seed envelopes only`);return{bindingJson:nn(e),nonceB64u:e.nonceB64u,ciphertextB64u:e.sealedCustodySecretB64u,aadHashB64u:e.aadHashB64u,ciphertextDigestB64u:e.ciphertextDigestB64u}}function ma(e){let{binding:t}=e.material,{activation:n}=e;return{kind:Ni,scope:{lifecycle_id:n.lifecycleId,root_share_epoch:n.signingRootVersion,account_id:t.walletId,threshold_session_id:n.thresholdSessionId,signer_set_id:n.signerSetId,signing_worker_id:t.signingWorkerId,material_activation:wt(n.materialActivation)},applicationBinding:{wallet_id:t.walletId,near_ed25519_signing_key_id:t.nearEd25519SigningKeyId,signing_root_id:n.signingRootId,key_creation_signer_slot:t.signerSlot},participantIds:t.participantIds,registeredPublicKey:R(t.registeredPublicKeyB64u),signingWorkerVerifyingShare:R(t.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(t.stateEpoch),transcript:R(n.activationTranscriptB64u),activeCapabilityBinding:Array.from(R(n.activationCapabilityBindingB64u)),materialActivation:n.materialActivation}}async function ha(e){let t=ma({material:e.material,activation:e.activation});return(await ua.initializeBundled()).openCustodyCache({ownedFactorSecret:e.ownedFactorSecret,envelope:{bindingJson:e.envelope.bindingJson,nonce:R(e.envelope.nonceB64u),ciphertext:R(e.envelope.ciphertextB64u),aadHash:R(e.envelope.aadHashB64u),ciphertextDigest:R(e.envelope.ciphertextDigestB64u)},applicationBindingDigest:R(e.material.binding.applicationBindingDigestB64u),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:R(e.material.sealed.nonceB64u),ciphertext:R(e.material.sealed.ciphertextB64u)},metadata:t})}async function ga(e){let t=await e.loadCachedMaterial();return t.kind===`found`?{kind:`opened`,activeClient:await ha({material:t.material,activation:e.activation,envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret})}:(e.ownedFactorSecret.fill(0),{kind:`rejoin_required`})}function _a(e){let t=String(e.rpId).trim(),n=String(e.nearAccountId).trim(),r=String(e.nearEd25519SigningKeyId).trim(),i=String(e.relayerKeyId).trim(),a=String(e.credentialIdB64u).trim(),o=ne(e.participantIds),s=Math.floor(Number(e.signerSlot));if(!t||!n||!r||!i||!a||!o||!Number.isSafeInteger(s)||s<1)throw Error(`Passkey Ed25519 sealed restore metadata is incomplete`);return{rpId:t,nearAccountId:n,nearEd25519SigningKeyId:r,relayerKeyId:i,participantIds:[...o],runtimePolicyScope:e.runtimePolicyScope,signerSlot:s,routerAbNormalSigning:e.routerAbNormalSigning,credentialIdB64u:a,materialActivation:e.materialActivation}}async function va(e){let t=String(e.session.thresholdSessionId||``).trim(),n=String(e.session.walletSessionAuth.walletSessionToken||``).trim(),r=String(e.session.signingLane.identity.signer.account.wallet.walletId||``).trim(),i=String(e.prfFirstB64u||``).trim(),a=Math.floor(Number(e.session.signingWalletSession.expiresAtMs)||0),o=Math.floor(Number(e.session.remainingUses)),s=e.session.signingLane.identity.auth;if(s.kind!==`passkey`)throw Error(`Ed25519 Yao sealed refresh persistence requires a passkey lane`);if(!t||!n||!r||!i||a<=0||!Number.isSafeInteger(o)||o<0)throw Error(`Ed25519 Yao sealed refresh persistence received an invalid session`);let c=e.session.signingLane.identity.signer;if(r!==String(c.account.wallet.walletId)||e.ed25519Restore.nearAccountId!==String(c.account.nearAccountId)||e.ed25519Restore.nearEd25519SigningKeyId!==String(c.nearEd25519SigningKeyId)||e.ed25519Restore.signerSlot!==c.signerSlot||e.ed25519Restore.rpId!==String(s.rpId)||e.ed25519Restore.credentialIdB64u!==s.credentialIdB64u||!p(e.ed25519Restore.materialActivation,e.materialActivation)||e.ed25519Restore.routerAbNormalSigning?.signingWorkerId!==e.session.routerAbNormalSigning.signingWorkerId)throw Error(`Ed25519 Yao sealed refresh metadata does not match the exact session`);let l={curve:`ed25519`,authMethod:`passkey`,walletId:r,relayerUrl:e.session.relayerUrl,walletSessionToken:n,ed25519Restore:e.ed25519Restore};await e.persistence.hydrateSigningSession({thresholdSessionId:t,prfFirstB64u:i,expiresAtMs:a,remainingUses:o,transport:l})}const ya=`[Registration] wallet timing summary`,ba=new Map(Object.entries({yao_credential_digest:`yaoServerCredentialDigestMs`,yao_d1_admission_read:`yaoServerD1AdmissionReadMs`,yao_router_execution:`yaoServerRouterExecutionMs`,yao_result_reconstruction:`yaoServerResultReconstructionMs`,yao_router_prepare_pair:`yaoServerRouterPreparePairMs`,yao_router_role_execution:`yaoServerRouterRoleExecutionMs`,yao_router_signing_worker_delivery:`yaoServerRouterSigningWorkerDeliveryMs`,ecdsa_respond_d1_claim:`ecdsaRespondD1ClaimMs`,ecdsa_respond_reconcile:`ecdsaRespondReconcileMs`,ecdsa_respond_router:`ecdsaRespondRouterMs`,ecdsa_respond_d1_commit:`ecdsaRespondD1CommitMs`,ecdsa_respond_total:`ecdsaRespondTotalMs`,ecdsa_activate_d1_claim:`ecdsaActivateD1ClaimMs`,ecdsa_activate_reconcile:`ecdsaActivateReconcileMs`,ecdsa_activate_router:`ecdsaActivateRouterMs`,ecdsa_activate_bootstrap:`ecdsaActivateBootstrapMs`,ecdsa_activate_session_provision:`ecdsaActivateSessionProvisionMs`,ecdsa_activate_d1_commit:`ecdsaActivateD1CommitMs`,ecdsa_activate_policy_lookup:`ecdsaActivatePolicyLookupMs`,ecdsa_activate_jwt_mint:`ecdsaActivateJwtMintMs`,ecdsa_activate_total:`ecdsaActivateTotalMs`,ecdsa_rt_authorize:`ecdsaRtAuthorizeMs`,ecdsa_rt_admission:`ecdsaRtAdmissionMs`,ecdsa_rt_derivers:`ecdsaRtDeriversMs`,ecdsa_rt_deriver_a:`ecdsaRtDeriverAMs`,ecdsa_rt_deriver_b:`ecdsaRtDeriverBMs`,ecdsa_rt_completion:`ecdsaRtCompletionMs`,ecdsa_rt_total:`ecdsaRtTotalMs`,ecdsa_rt_act_session:`ecdsaRtActSessionMs`,ecdsa_rt_act_worker:`ecdsaRtActWorkerMs`,ecdsa_rt_act_total:`ecdsaRtActTotalMs`,ecdsa_a_parse:`ecdsaDeriverAParseMs`,ecdsa_a_preload:`ecdsaDeriverAPreloadMs`,ecdsa_a_execute:`ecdsaDeriverAExecuteMs`,ecdsa_a_total:`ecdsaDeriverATotalMs`,ecdsa_b_parse:`ecdsaDeriverBParseMs`,ecdsa_b_preload:`ecdsaDeriverBPreloadMs`,ecdsa_b_execute:`ecdsaDeriverBExecuteMs`,ecdsa_b_total:`ecdsaDeriverBTotalMs`,ecdsa_sw_parse:`ecdsaSigningWorkerParseMs`,ecdsa_sw_activate:`ecdsaSigningWorkerActivateMs`,ecdsa_sw_total:`ecdsaSigningWorkerTotalMs`,near_finalize_authority:`nearFinalizeAuthorityMs`,near_finalize_fingerprint:`nearFinalizeFingerprintMs`,near_finalize_side_effect:`nearFinalizeSideEffectMs`,near_finalize_cleanup:`nearFinalizeCleanupMs`,near_finalize_session_projection:`nearFinalizeSessionProjectionMs`,near_finalize_session_seal:`nearFinalizeSessionSealMs`,near_finalize_total:`nearFinalizeTotalMs`}));function xa(e,t,n){br()&&console.info(`[Registration] ECDSA Server-Timing header presence`,{leg:t,present:!!n?.trim()}),Sa(e,n)}function Sa(e,t){if(e)for(let[n,r]of Ca(t))e.record(n,r)}function Ca(e){if(!e)return[];let t=[];for(let n of e.split(`,`)){let e=n.split(`;`),r=String(e[0]||``).trim(),i=ba.get(r);if(i)for(let n of e.slice(1)){let[e,r]=n.split(`=`);if(String(e||``).trim()!==`dur`)continue;let a=Number(String(r||``).trim());if(!Number.isFinite(a)||a<0)break;t.push([i,a]);break}}return t}function wa(e){Ea({ceremonyId:e.ceremonyId,stage:e.stage,durationMs:Math.max(0,performance.now()-e.startedAt),outcome:e.outcome})}function Ta(e,t,n){Ea({ceremonyId:e,stage:`session_hydration.${t}`,durationMs:n,outcome:`success`})}function Ea(e){if(br())try{console.info(`[Registration] NEAR timing`,JSON.stringify({event:`near_registration_timing`,ceremonyId:e.ceremonyId,stage:e.stage,durationMs:e.durationMs,outcome:e.outcome}))}catch{}}const Da=[`passkeyAuthConfirmationMs`,`passkeyAuthPrfExtractionMs`,`passkeyAuthCredentialRedactionMs`,`passkeyAuthWorkerReadyMs`,`passkeyAuthWorkerRequestRoundTripMs`,`passkeyAuthWorkerResponseValidationMs`,`passkeyAuthRequestSetupMs`,`passkeyAuthPromptUserMs`,`passkeyAuthPromptElementDefineMs`,`passkeyAuthPromptMountMs`,`passkeyAuthPromptHostFirstUpdateMs`,`passkeyAuthPromptHostInteractiveMs`,`passkeyAuthPromptConfirmEventMs`,`passkeyAuthPromptDecisionWaitMs`,`passkeyAuthCredentialCreateStartMs`,`passkeyAuthCredentialCreateMs`,`passkeyAuthCredentialSerializeMs`,`passkeyAuthDuplicateRetryCount`,`passkeyAuthMainThreadTotalMs`],Oa=[`emailOtpYaoEnrollmentMaterialWaitMs`,`emailOtpYaoWorkerRegistrationMs`,`emailOtpYaoTotalMs`],ka=[`ecdsaClientBootstrapMs`,`ecdsaRegistrationTotalMs`,`ecdsaRegistrationClientCreateMs`,`ecdsaRegistrationGatewayRespondMs`,`ecdsaRegistrationClientProofVerifyMs`,`ecdsaRegistrationGatewayActivateMs`,`ecdsaRegistrationClientActivationFinalizeMs`],Aa=[`ecdsaRegistrationPersistenceMs`,`ecdsaRegistrationSessionFinalizeMs`,`ecdsaRegistrationLocalRecordPersistenceMs`,`ecdsaRegistrationTargetCount`,`ecdsaRegistrationClientFinalizeMs`,`ecdsaRegistrationClientMaterialStoreMs`,`ecdsaRegistrationServerBootstrapMs`,`ecdsaRegistrationPasskeyBootstrapStoreMs`,`ecdsaRegistrationRoleLocalRecordPersistenceMs`,`ecdsaRegistrationWarmSessionHydrationMs`,`ecdsaRegistrationWarmSessionWorkerReadyMs`,`ecdsaRegistrationWarmSessionWorkerPutMs`,`ecdsaRegistrationWarmSessionSealedRecordPersistMs`,`ecdsaRegistrationWarmSessionSealResolveTransportMs`,`ecdsaRegistrationWarmSessionSealExistingRecordReadMs`,`ecdsaRegistrationWarmSessionSealPolicyReadMs`,`ecdsaRegistrationWarmSessionSealApplyServerSealMs`,`ecdsaRegistrationWarmSessionSealApplyRuntimeSetupMs`,`ecdsaRegistrationWarmSessionSealApplyClientSealMs`,`ecdsaRegistrationWarmSessionSealApplyServerRouteMs`,`ecdsaRegistrationWarmSessionSealApplyClientUnsealMs`,`ecdsaRegistrationWarmSessionSealApplyPolicyUpdateMs`,`ecdsaRegistrationWarmSessionSealRegisterMs`,`ecdsaRegistrationWarmSessionSealVerifyReadMs`,`ecdsaRegistrationEmailOtpSessionCommitMs`],ja=[...ka,...Aa],Ma=[`registrationWarmupMs`,`registrationWarmupWaitMs`,`registrationWarmupAuthenticatedWalletStateMs`,`registrationWarmupNoncePrefetchMs`,`registrationWarmupKeyMaterialReadMs`,`registrationWarmupUiConfirmPrewarmMs`,`registrationWarmupEmailOtpWorkerPrewarmMs`,`registrationWarmupEmailOtpYaoWasmInitMs`,`managedRegistrationGrantMs`,`registrationIntentMs`,`registrationIntentDigestMs`,`authProofMs`,...Da,`emailOtpEnrollmentMaterialMs`,...Oa,`yaoBranchTotalMs`,`yaoAdmissionMs`,`yaoClientSessionCreateMs`,`yaoClientCompletionMs`,`yaoServerCredentialDigestMs`,`yaoServerD1AdmissionReadMs`,`yaoServerRouterExecutionMs`,`yaoServerResultReconstructionMs`,`yaoServerRouterPreparePairMs`,`yaoServerRouterRoleExecutionMs`,`yaoServerRouterSigningWorkerDeliveryMs`,`ecdsaRespondD1ClaimMs`,`ecdsaRespondReconcileMs`,`ecdsaRespondRouterMs`,`ecdsaRespondD1CommitMs`,`ecdsaRespondTotalMs`,`ecdsaActivateD1ClaimMs`,`ecdsaActivateReconcileMs`,`ecdsaActivateRouterMs`,`ecdsaActivateBootstrapMs`,`ecdsaActivateSessionProvisionMs`,`ecdsaActivateD1CommitMs`,`ecdsaActivatePolicyLookupMs`,`ecdsaActivateJwtMintMs`,`ecdsaActivateTotalMs`,`ecdsaRtAuthorizeMs`,`ecdsaRtAdmissionMs`,`ecdsaRtDeriversMs`,`ecdsaRtDeriverAMs`,`ecdsaRtDeriverBMs`,`ecdsaRtCompletionMs`,`ecdsaRtTotalMs`,`ecdsaRtActSessionMs`,`ecdsaRtActWorkerMs`,`ecdsaRtActTotalMs`,`ecdsaDeriverAParseMs`,`ecdsaDeriverAPreloadMs`,`ecdsaDeriverAExecuteMs`,`ecdsaDeriverATotalMs`,`ecdsaDeriverBParseMs`,`ecdsaDeriverBPreloadMs`,`ecdsaDeriverBExecuteMs`,`ecdsaDeriverBTotalMs`,`ecdsaSigningWorkerParseMs`,`ecdsaSigningWorkerActivateMs`,`ecdsaSigningWorkerTotalMs`,`nearFinalizeAuthorityMs`,`nearFinalizeFingerprintMs`,`nearFinalizeSideEffectMs`,`nearFinalizeCleanupMs`,`nearFinalizeSessionProjectionMs`,`nearFinalizeSessionSealMs`,`nearFinalizeTotalMs`,`walletRegisterStartMs`,...ka,`emailOtpRecoveryCodeBackupMs`,`walletRegisterFinalizeMs`,...Aa];function q(e){throw Error(`Unexpected registration timing branch: ${String(e)}`)}function Na(e){switch(e.kind){case`near_ed25519`:return`near_ed25519`;case`evm_family_ecdsa`:return`evm_family_ecdsa`;default:return q(e)}}function Pa(e){return{kind:`signer_set`,branches:e.branches.map(Na)}}function Fa(e,t){return e.branches.includes(t)}function Ia(e){return Math.max(0,Math.round(performance.now()-e))}function La(e){switch(e){case`registrationIntentLoadMs`:case`registrationIntentDigestMs`:case`registrationIntentConsumeMs`:case`registrationPreparationPersistMs`:case`registrationPreparationLoadMs`:case`registrationPreparationConsumeMs`:case`registrationPreparationScopeCheckMs`:case`registrationAuthorityVerifyMs`:case`registrationEcdsaPrepareMs`:case`registrationCeremonyPersistMs`:case`registerPrepareTotalMs`:case`registerStartTotalMs`:case`registrationEcdsaRespondMs`:case`registrationFinalizeReplayLoadMs`:case`registrationCeremonyLoadMs`:case`registrationEcdsaBootstrapVerifyMs`:case`sponsoredNearAccountCreateMs`:case`registrationKeygenMs`:case`registrationEmailOtpEnrollmentPlanMs`:case`relaySessionMintMs`:case`relayGoogleEmailOtpActivationPlanMs`:case`relayPersistenceMs`:case`registrationFinalizeReplayCacheMs`:case`registerFinalizeTotalMs`:return e;default:return null}}function Ra(e){if(!b(e)||e.kind!==`wallet_registration_route_diagnostics_v1`||e.route!==`wallets_register_start`&&e.route!==`wallets_register_ecdsa_derivation_respond`&&e.route!==`wallets_register_finalize`||!Array.isArray(e.entries))return null;let t=[];for(let n of e.entries){if(!b(n))continue;let e=La(n.name),r=Number(n.durationMs);!e||!Number.isFinite(r)||r<0||t.push({name:e,durationMs:r})}return{kind:`wallet_registration_route_diagnostics_v1`,route:e.route,entries:t}}function za(e){return{kind:e.kind,route:e.route,entries:e.entries.map(Ba)}}function Ba(e){return{name:e.name,durationMs:e.durationMs}}function Va(e,t){let n={};for(let r of e)n[r]=t[r];return n}function Ha(e){let t={};for(let n of e)t[n]=0;return t}function Ua(e){switch(e.authMethod){case`passkey`:return{kind:`passkey`,authProofMs:e.buckets.authProofMs,...Va(Da,e.buckets),emailOtpEnrollmentMaterialMs:0,emailOtpRecoveryCodeBackupMs:0};case`email_otp`:return{kind:`email_otp`,authProofMs:e.buckets.authProofMs,...Ha(Da),emailOtpEnrollmentMaterialMs:e.buckets.emailOtpEnrollmentMaterialMs,emailOtpRecoveryCodeBackupMs:e.buckets.emailOtpRecoveryCodeBackupMs};default:return q(e.authMethod)}}function Wa(e){return Fa(e.signerSet,`near_ed25519`)?{kind:`ed25519_yao_enabled`,...Va(Oa,e.buckets)}:{kind:`ed25519_disabled`,...Ha(Oa)}}function Ga(e){return Fa(e.signerSet,`evm_family_ecdsa`)?{kind:`ecdsa_enabled`,...Va(ja,e.buckets)}:{kind:`ecdsa_disabled`,...Ha(ja)}}const Ka=[`registrationWarmupWaitMs`,`managedRegistrationGrantMs`,`registrationIntentMs`,`registrationIntentDigestMs`,`authProofMs`,`emailOtpEnrollmentMaterialMs`,`emailOtpYaoEnrollmentMaterialWaitMs`,`emailOtpYaoWorkerRegistrationMs`,`emailOtpYaoTotalMs`,`walletRegisterStartMs`,`ecdsaClientBootstrapMs`,`ecdsaRegistrationTotalMs`,`emailOtpRecoveryCodeBackupMs`,`walletRegisterFinalizeMs`,`ecdsaRegistrationPersistenceMs`];function qa(e){return e.startsWith(`registrationWarmup`)?`warmup`:e.startsWith(`passkeyAuth`)||e===`authProofMs`?`auth`:e.includes(`Yao`)||e.includes(`yao`)?`ed25519_yao`:e.includes(`ecdsa`)?`ecdsa`:`registration`}function Ja(e){return{name:e.name,kind:e.kind,startOffsetMs:e.startOffsetMs,endOffsetMs:e.endOffsetMs}}function Ya(e,t){let n=t.map(t=>({start:Math.max(0,Math.min(e,t.startOffsetMs)),end:Math.max(0,Math.min(e,t.endOffsetMs))})).filter(e=>e.end>e.start).sort((e,t)=>e.start-t.start||e.end-t.end),r=0,i=0,a=0;for(let e of n){if(a<=i){i=e.start,a=e.end;continue}if(e.start>a){r+=a-i,i=e.start,a=e.end;continue}a=Math.max(a,e.end)}return a>i?r+a-i:r}function Xa(e){let t=Ka.map(t=>({name:t,durationMs:e.buckets[t]})),n=t.reduce((e,t)=>e+Math.max(0,t.durationMs),0),r=t.filter(e=>e.durationMs>0).sort((e,t)=>t.durationMs===e.durationMs?e.name.localeCompare(t.name):t.durationMs-e.durationMs).slice(0,5),i=Ya(e.totalElapsedMs,e.spans);return{kind:`registration_critical_path_summary_v2`,totalElapsedMs:e.totalElapsedMs,measuredWorkMs:n,spanUnionMs:i,spanCoverageRatio:e.totalElapsedMs>0?Math.min(1,i/e.totalElapsedMs):1,unattributedElapsedMs:Math.max(0,e.totalElapsedMs-i),overlappedOrBackgroundMs:Math.max(0,n-e.totalElapsedMs),topBuckets:r,spans:e.spans.map(Ja)}}function Za(e){let t=Va(Ma,e.buckets);return{...t,auth:Ua({authMethod:e.authMethod,buckets:t}),ed25519:Wa({signerSet:e.signerSet,buckets:t}),ecdsa:Ga({signerSet:e.signerSet,buckets:t}),emailOtpYaoPrewarm:{...e.emailOtpYaoPrewarm}}}var Qa=class{startedAt;nearStageStartedAt;buckets;relayDiagnostics;spans;emailOtpYaoPrewarm;constructor(e){this.startedAt=e,this.nearStageStartedAt=e,this.buckets=Ha(Ma),this.relayDiagnostics=[],this.spans=[],this.emailOtpYaoPrewarm=$a()}markNearStage(e,t){let n=performance.now();Ea({ceremonyId:e,stage:t,durationMs:n-this.nearStageStartedAt,outcome:`success`}),this.nearStageStartedAt=n}async measure(e,t){let n=performance.now();try{return await t()}finally{this.buckets[e]=Ia(n),this.recordSpan(e,n,performance.now())}}record(e,t){let n=Math.max(0,Math.round(t));this.buckets[e]+=n}snapshot(){return Va(Ma,this.buckets)}spansSnapshot(){return this.spans.map(Ja)}recordSpan(e,t,n){this.spans.push({name:e,kind:qa(e),startOffsetMs:Math.max(0,Math.round(t-this.startedAt)),endOffsetMs:Math.max(0,Math.round(n-this.startedAt))})}captureRouteDiagnostics(e){let t=Ra(e);t&&this.relayDiagnostics.push(t)}captureWarmupDiagnostics(e){this.buckets.registrationWarmupAuthenticatedWalletStateMs=e.authenticatedWalletStateMs,this.buckets.registrationWarmupNoncePrefetchMs=e.noncePrefetchMs,this.buckets.registrationWarmupKeyMaterialReadMs=e.keyMaterialReadMs,this.buckets.registrationWarmupUiConfirmPrewarmMs=e.uiConfirmPrewarmMs,this.buckets.registrationWarmupEmailOtpWorkerPrewarmMs=e.emailOtpWorkerPrewarmMs,this.buckets.registrationWarmupEmailOtpYaoWasmInitMs=e.emailOtpYaoWasmInitMs,this.emailOtpYaoPrewarm={...e.emailOtpYaoPrewarm}}emailOtpYaoPrewarmSnapshot(){return{...this.emailOtpYaoPrewarm}}capturePasskeyAuthDiagnostics(e){this.buckets.passkeyAuthConfirmationMs=e.requestConfirmationMs,this.buckets.passkeyAuthPrfExtractionMs=e.prfExtractionMs,this.buckets.passkeyAuthCredentialRedactionMs=e.credentialRedactionMs,this.buckets.passkeyAuthWorkerReadyMs=e.confirmationWorkerReadyMs,this.buckets.passkeyAuthWorkerRequestRoundTripMs=e.confirmationWorkerRequestRoundTripMs,this.buckets.passkeyAuthWorkerResponseValidationMs=e.confirmationWorkerResponseValidationMs,this.buckets.passkeyAuthRequestSetupMs=e.confirmationRequestSetupMs,this.buckets.passkeyAuthPromptUserMs=e.confirmationPromptUserMs,this.buckets.passkeyAuthPromptElementDefineMs=e.confirmationPromptElementDefineMs,this.buckets.passkeyAuthPromptMountMs=e.confirmationPromptMountMs,this.buckets.passkeyAuthPromptHostFirstUpdateMs=e.confirmationPromptHostFirstUpdateMs,this.buckets.passkeyAuthPromptHostInteractiveMs=e.confirmationPromptHostInteractiveMs,this.buckets.passkeyAuthPromptConfirmEventMs=e.confirmationPromptConfirmEventMs,this.buckets.passkeyAuthPromptDecisionWaitMs=e.confirmationPromptDecisionWaitMs,this.buckets.passkeyAuthCredentialCreateStartMs=e.confirmationCredentialCreateStartMs,this.buckets.passkeyAuthCredentialCreateMs=e.confirmationCredentialCreateMs,this.buckets.passkeyAuthCredentialSerializeMs=e.confirmationCredentialSerializeMs,this.buckets.passkeyAuthDuplicateRetryCount=e.confirmationDuplicateRetryCount,this.buckets.passkeyAuthMainThreadTotalMs=e.confirmationMainThreadTotalMs}routeDiagnosticsSnapshot(){return this.relayDiagnostics.map(za)}totalMs(){return Ia(this.startedAt)}};function $a(){return{kind:`not_requested`,elapsedMs:0,workerPrewarmMs:0,yaoWasmInitMs:0}}function eo(e){let t=e.recorder.totalMs(),n=e.recorder.snapshot();return{kind:`registration_timing_summary_v2`,status:`succeeded`,authMethod:e.authMethod,signerSet:e.signerSet,totalMs:t,criticalPath:Xa({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:Za({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function to(e){let t=e.recorder.totalMs(),n=e.recorder.snapshot();return{kind:`registration_timing_summary_v2`,status:`failed`,authMethod:e.authMethod,signerSet:e.signerSet,totalMs:t,criticalPath:Xa({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),errorCode:e.errorCode,relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:Za({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function no(e){br()&&(console.info(ya,e),console.info(`${ya} ${JSON.stringify(e)}`))}function ro(e){let t={event:`seams_registration_timing_span_v1`,span:e.span,operation:`registration`,outcome:e.outcome,duration_ms:Math.max(0,Math.round(e.durationMs)),trace_id:e.traceContext.value};try{e.callback?.(t)}catch{}}function J(e){return{kind:`unavailable`,reason:e}}function io(e){let t=e.selected;if(t.kind!==`resolved`)switch(t.kind){case`missing_selection`:return J(`selected_authority_missing`);case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return J(`selected_authority_invalid`);default:return t}return t.selection.walletId!==e.walletId||t.authMethod.walletId!==e.walletId||t.authority.walletId!==e.walletId||t.selection.walletAuthMethodId!==t.authMethod.walletAuthMethodId||t.authMethod.walletAuthorityId!==t.authority.authorityId?J(`authority_identity_mismatch`):t.selection.lockState===`unlocked`?t.authMethod.status===`active`?t.authority.state===`active`?t.authMethod.kind===e.authMethod?{authority:t.authority,authMethod:t.authMethod}:J(`auth_method_mismatch`):J(`authority_inactive`):J(`auth_method_inactive`):J(`wallet_locked`)}function ao(e){let t=e.authority.signerActivations;return e.keyFamily===`ed25519`?t.ed25519?.materialActivation??null:t.ecdsa?.materialActivation??null}function oo(e){return e.session.capabilitySubjects.filter(t=>t.kind===`sign`&&t.keyFamily===e.keyFamily&&p(t.materialActivation,e.materialActivation)).length===1}function so(e){return ir(e)?{keyFamily:`ecdsa_secp256k1`,materialActivation:e.signer.materialActivation}:{keyFamily:`ed25519`}}async function co(e){let{input:t,ports:n}=e,r;try{r=await n.resolveSelectedWalletAuthority(String(t.walletId))}catch{return J(`persistence_unavailable`)}let i=io({selected:r,walletId:t.walletId,authMethod:t.authMethod});if(`kind`in i)return i;let a=ao({authority:i.authority,keyFamily:t.requiredSigningSubject.keyFamily});if(!a)return J(`signer_material_missing`);if(t.requiredSigningSubject.keyFamily===`ecdsa_secp256k1`&&!p(t.requiredSigningSubject.materialActivation,a))return J(`signer_material_mismatch`);let o;try{o=await n.readExactWithOperationCredential({walletId:t.walletId,authorityId:i.authority.authorityId,authMethodId:i.authMethod.walletAuthMethodId})}catch{return J(`persistence_unavailable`)}switch(o.kind){case`found`:break;case`missing`:return J(`wallet_session_missing`);case`upgrade_required`:return J(`wallet_session_upgrade_required`)}let s=o.record,c=o.operationCredential;return s.walletId!==t.walletId||s.authorityId!==i.authority.authorityId||s.authMethodId!==i.authMethod.walletAuthMethodId||s.authorityDigestB64u!==i.authority.authorityDigestB64u||s.authorityRevocationEpoch!==i.authority.revocationEpoch||s.quotaId!==t.quotaId||c.walletSessionId!==t.walletSessionId||c.token.trim().length===0?J(`wallet_session_identity_mismatch`):t.expiry.kind===`unexpired`&&s.expiresAtMs<=t.expiry.nowMs?J(`wallet_session_expired`):t.expiry.kind===`expired`&&s.expiresAtMs>t.expiry.nowMs?J(`wallet_session_not_expired`):oo({session:s,keyFamily:t.requiredSigningSubject.keyFamily,materialActivation:a})?{kind:`resolved`,resolved:{authMethod:i.authMethod,session:s,operationCredential:c,walletSessionId:c.walletSessionId,materialActivation:a}}:J(`wallet_session_capability_mismatch`)}function lo(e){return String(e||``).trim()}function uo(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:0}function fo(e){let t=Math.floor(Number(e));return Number.isSafeInteger(t)&&t>=0?t:null}function po(e){return e.expiresAtMs<=e.nowMs?{kind:`expired`}:e.remainingUses<=0?{kind:`exhausted`}:null}function mo(e,t){let n=lo(e);return n?{kind:`wallet_session_opaque`,walletSessionToken:n,credential:{kind:`wallet_session_opaque`,walletSessionToken:n,home:t}}:null}function ho(e){let t=mo(lo(e.walletSessionToken),e.home);if(!t)return{ok:!1,reason:`missing_wallet_session_token`};let n=lo(e.walletId),r=lo(e.nearAccountId),i=lo(e.nearEd25519SigningKeyId);if(!n||!r||!i)return{ok:!1,reason:`wallet_binding_mismatch`};let a=_e(e.walletSessionId),o=ve(e.authorizationId),c=he(e.quotaId),l=s(e.thresholdSessionId);if(!a.ok||!o.ok)return{ok:!1,reason:`missing_session_identity`};if(!c.ok)return{ok:!1,reason:`missing_quota_id`};if(!l.ok)return{ok:!1,reason:`missing_threshold_session_id`};let u=fo(e.nowMs),d=uo(e.remainingUses),f=uo(e.expiresAtMs);if(u==null||!Number.isSafeInteger(e.remainingUses)||!Number.isSafeInteger(e.expiresAtMs)||e.remainingUses<0||e.expiresAtMs<=0)return{ok:!1,reason:`invalid_budget`};let p=po({remainingUses:Math.max(0,Math.floor(e.remainingUses)),expiresAtMs:Math.max(0,Math.floor(e.expiresAtMs)),nowMs:u});if(p?.kind===`expired`)return{ok:!1,reason:`expired`};if(p?.kind===`exhausted`)return{ok:!1,reason:`exhausted`};let m;try{m=re(e.runtimePolicyScope)}catch{return{ok:!1,reason:`missing_signing_root`}}return m.signingRootId!==lo(e.signingRootId)||m.signingRootVersion!==lo(e.signingRootVersion)?{ok:!1,reason:`signing_root_mismatch`}:{ok:!0,value:{curve:`ed25519`,auth:t,walletSessionId:a.value,authorizationId:o.value,quotaId:c.value,thresholdSessionId:l.value,remainingUses:d,expiresAtMs:f,runtimePolicyScope:e.runtimePolicyScope,signingRootId:m.signingRootId,signingRootVersion:lo(m.signingRootVersion),routerAbNormalSigning:e.routerAbNormalSigning}}}const go=qe.signingSessionSeals,_o=qe.signingSessionRestoreLeases,vo=[Ye.ed25519ThresholdSessionId,Ye.ecdsaThresholdSessionId];function yo(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error||Error(`IndexedDB request failed`))})}function bo(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onabort=()=>n(e.error||Error(`IndexedDB transaction aborted`)),e.onerror=()=>n(e.error||Error(`IndexedDB transaction failed`))})}async function xo(){if(Xe.isDisabled())return null;try{return Je(await Xe.getDB())}catch{return null}}function So(e,t){return new Promise((n,r)=>{let i=[],a=e.openCursor(t);a.onsuccess=()=>{let e=a.result;if(!e){n(i);return}i.push({primaryKey:e.primaryKey,value:e.value}),e.continue()},a.onerror=()=>r(a.error||Error(`IndexedDB cursor failed`))})}function Co(e){return new Promise((t,n)=>{let r=[],i=e.openCursor();i.onsuccess=()=>{let e=i.result;if(!e){t(r);return}r.push({primaryKey:e.primaryKey,value:e.value}),e.continue()},i.onerror=()=>n(i.error||Error(`IndexedDB cursor failed`))})}async function wo(e,t){let n=new Map;for(let r of vo)try{let i=await So(e.index(r),t);for(let e of i)n.set(String(e.primaryKey),e)}catch{}return n.size?[...n.values()]:await Co(e).catch(()=>[])}const Y=new class{async collectAllRawSealedRecordEntries(){let e=await xo();if(!e)return[];let t=e.transaction(go,`readonly`),n=await Co(t.objectStore(go));return await bo(t).catch(()=>void 0),n}async collectRawSealedRecordEntriesByThresholdSessionId(e){let t=await xo();if(!t)return[];let n=t.transaction(go,`readonly`),r=await wo(n.objectStore(go),e);return await bo(n).catch(()=>void 0),r}async replaceSealedRecord(e){let t=await xo();if(!t)return;let n=t.transaction(go,`readwrite`),r=n.objectStore(go);for(let t of e.staleStoreKeys)r.delete(t);r.put(e.row),await bo(n)}async replaceSealedRecordAndDeleteRestoreLease(e){let t=await xo();if(!t)return!1;let n=t.transaction([go,_o],`readwrite`),r=n.objectStore(go);for(let t of e.staleStoreKeys)r.delete(t);return r.put(e.row),n.objectStore(_o).delete(e.restoreLeaseKey),await bo(n),!0}async deleteSealedRecords(e){if(!e.length)return;let t=await xo();if(!t)return;let n=t.transaction(go,`readwrite`),r=n.objectStore(go);for(let t of e)r.delete(t);await bo(n).catch(()=>void 0)}async deleteRestoreLease(e){let t=await xo();if(!t)return;let n=t.transaction(_o,`readwrite`);n.objectStore(_o).delete(e),await bo(n).catch(()=>void 0)}async deleteRestoreLeaseIf(e){let t=await xo();if(!t)return;let n=t.transaction(_o,`readwrite`),r=n.objectStore(_o),i=await yo(r.get(e.leaseKey));e.shouldDelete(i)&&r.delete(e.leaseKey),await bo(n).catch(()=>void 0)}async withRestoreLeaseTransaction(e,t){let n=await xo();if(!n)return null;try{let r=n.transaction([go,_o],`readwrite`),i=r.objectStore(go),a=r.objectStore(_o),o=await wo(i,e),s=!1,c=await t({entries:o,getRawRestoreLease:async e=>await yo(a.get(e)),putRestoreLease:e=>a.put(e),abort:()=>{s=!0}});return s?(r.abort(),c):(await bo(r),c)}catch{return null}}};function To(e){throw Error(`Unhandled durable sealed-session identity: ${String(e)}`)}function Eo(e){return{kind:`delete_durable_sealed_session`,durableRecord:e.durableRecord,deleteReason:e.deleteReason,preserveResolvedIdentity:e.preserveResolvedIdentity}}function Do(e){switch(e.curve){case`ed25519`:return{authMethod:e.authMethod,curve:`ed25519`};case`ecdsa`:return{authMethod:e.authMethod,curve:`ecdsa`,chainTarget:e.chainTarget};default:return To(e)}}function Oo(e){return[`ecdsa-material-v2`,e.walletId,e.authMethod,Re(e.chainTarget),e.materialActivation.activationId,e.materialActivation.capability,e.materialActivation.materialOwner,e.materialActivation.keyBinding,e.materialActivation.lifecycleBinding,e.materialActivation.signingWorker].map(e=>encodeURIComponent(String(e))).join(`:`)}const ko=`ecdsa_inactive_sealed_material_v1`,Ao=`sealed_record`;function jo(e){let t=C(e)??{},n=o(t.ed25519),r=o(t.ecdsa);return{...n?{ed25519:n}:{},...r?{ecdsa:r}:{}}}function Mo(e){return jo((C(e)??{}).thresholdSessionIds)}function No(e){let t=C(e);if(!t)return!1;let n=[`signing`,`Grant`,`Id`].join(``),r=[`signing`,`grant`,`id`].join(`_`);return Object.prototype.hasOwnProperty.call(t,n)||Object.prototype.hasOwnProperty.call(t,r)}function Po(e){let t=String(e||``).trim();return t===`ed25519`||t===`ecdsa`?t:void 0}function Fo(e){let t=C(e);return t&&Ao in t?t[Ao]:e}function Io(e){let t=e.ecdsaRestore?.chainTarget,n=o(e.thresholdSessionIds.ecdsa),r=o(e.thresholdSessionIds.ed25519);return{store_key:e.storeKey,wallet_id:e.walletId,auth_method:e.authMethod,curve:e.curve,signing_root_id:o(`signingRootId`in e?e.signingRootId:void 0),signing_root_version:o(`signingRootVersion`in e?e.signingRootVersion:void 0),ed25519_threshold_session_id:r,ecdsa_threshold_session_id:n,threshold_session_id:n||r,key_handle:o(e.ecdsaRestore?.keyHandle),chain_target_key:t?Re(t):void 0,expires_at_ms:e.expiresAtMs,updated_at:e.updatedAtMs,[Ao]:e}}function Lo(e){return{store_key:e.storeKey,wallet_id:e.walletId,auth_method:e.authMethod,curve:e.curve,key_handle:e.ecdsaRestore.keyHandle,chain_target_key:Re(e.ecdsaRestore.chainTarget),updated_at:e.updatedAtMs,[Ao]:e}}function Ro(e){return Io(e)}function zo(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:void 0}function Bo(e){return e.curve?e.curve:e.thresholdSessionIds.ecdsa?`ecdsa`:e.thresholdSessionIds.ed25519?`ed25519`:null}function Vo(e){try{return st(e)}catch{return null}}function Ho(e){switch(e){case`login`:case`registration`:case`manual-bootstrap`:case`email_otp`:return e;default:return null}}function Uo(e){try{let t=re(I(e)),n=o(t.signingRootId),r=o(t.signingRootVersion);return n&&r?{signingRootId:n,signingRootVersion:r}:null}catch{return null}}function Wo(e){let t=C(e);if(!t)return;let n=null;try{n=Fe(C(t.chainTarget)??{})}catch{n=null}let r=Ho(t.source),i=bt(t.authority),a=o(t.rpId),s=t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?t.runtimePolicyScope:void 0,c=Uo(s),l=o(t.signingRootId),u=o(t.signingRootVersion);if(l&&c?.signingRootId&&l!==c.signingRootId||u&&c?.signingRootVersion&&u!==c.signingRootVersion)return;let d=l||c?.signingRootId||``,f=u||c?.signingRootVersion||``,p=o(t.credentialIdB64u),m=null;try{m=dn(t.roleLocalMaterialRef)}catch{m=null}let h=lt(t.emailOtpAuthority),g=t.provider===`google`||t.provider===`email`?t.provider:null,_=o(t.providerSubjectId),v=o(t.emailHashHex),y=o(t.keyHandle),b=o(t.ecdsaThresholdKeyId),x=zo(t.ethereumAddress),S=o(t.relayerKeyId),w=o(t.thresholdEcdsaPublicKeyB64u),T=Vo(t.routerAbEcdsaDerivationNormalSigning),E=null;try{E=Ct(t.publicCapability)}catch{E=null}let D=Qo(t.participantIds);if(!n||!r||!d||!f||!y||!x||!S||!T||!E||!D.length)return;let O=p&&a&&m&&i&&r!==`email_otp`?{source:r,authority:i,roleLocalMaterialRef:m,rpId:a,credentialIdB64u:p}:_&&g&&v&&m&&i&&h&&r===`email_otp`?{source:r,provider:g,providerSubjectId:_,emailHashHex:v,authority:i,emailOtpAuthority:h,roleLocalMaterialRef:m}:null;if(!O)return;let k=o(t.clientVerifyingShareB64u);return{chainTarget:n,signingRootId:d,signingRootVersion:f,...O,keyHandle:y,...b?{ecdsaThresholdKeyId:b}:{},ethereumAddress:x,relayerKeyId:S,...k?{clientVerifyingShareB64u:k}:{},...w?{thresholdEcdsaPublicKeyB64u:w}:{},participantIds:D,routerAbEcdsaDerivationNormalSigning:T,publicCapability:E,...s?{runtimePolicyScope:s}:{}}}function Go(e){let t=C(e);if(!t)return;let r=o(t.nearAccountId),i=o(t.nearEd25519SigningKeyId),a=o(t.rpId),s=o(t.credentialIdB64u),c=o(t.providerSubjectId),u=t.provider===`google`||t.provider===`email`?t.provider:null,d=o(t.emailHashHex),f=o(t.authSubjectId),p=o(t.relayerKeyId),m=Qo(t.participantIds),h=n(t.signerSlot),g=se(t.routerAbNormalSigning),_=l(t.materialActivation),v=s&&!c&&_.ok?{credentialIdB64u:s,materialActivation:_.value}:u&&c&&d&&!s&&_.ok?{provider:u,providerSubjectId:c,emailHashHex:d,materialActivation:_.value}:null;if(!(!r||!i||!a||!p||!m.length||h==null||h<=0||!g||!v||f))return{nearAccountId:r,nearEd25519SigningKeyId:i,rpId:a,...v,relayerKeyId:p,participantIds:m,...t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?{runtimePolicyScope:t.runtimePolicyScope}:{},signerSlot:h,routerAbNormalSigning:g}}function Ko(e){let t=e.restore.materialActivation;return[`ed25519-material-v2`,e.walletId,e.authMethod,`ed25519`,t.activationId,t.capability,t.materialOwner,t.keyBinding,t.lifecycleBinding,t.signingWorker].map(Jo).join(`:`)}function qo(e){let t=e.restore.roleLocalMaterialRef;return[`inactive-material`,e.walletId,e.authMethod,`ecdsa`,Re(e.restore.chainTarget),t.materialActivation.activationId].map(Jo).join(`:`)}function Jo(e){return encodeURIComponent(String(e||``).trim())}function Yo(e){let t=String(e||``).trim();return t===`passkey`||t===`email_otp`?t:void 0}function Xo(e){let t=C(e);return!!(o(t?.subjectId)||o(t?.userId))}function Zo(e){let t=C(e);return!!(o(t?.signingRootId)||o(t?.signingRootVersion))}function Qo(e){return Array.isArray(e)?e.map(e=>Math.floor(Number(e))).filter(e=>Number.isFinite(e)&&e>0):[]}function $o(e){return{authMethod:o(e?.authMethod)||null,curve:o(e?.curve)||null,storeKey:o(e?.storeKey)||null,walletId:o(e?.walletId)||null,thresholdSessionIds:Mo(e),hasEcdsaRestore:!!C(e?.ecdsaRestore),hasEd25519Restore:!!C(e?.ed25519Restore),issuedAtMs:n(e?.issuedAtMs),expiresAtMs:n(e?.expiresAtMs),remainingUses:n(e?.remainingUses),updatedAtMs:n(e?.updatedAtMs)}}function X(e,t,n){return{kind:e,storeKey:o(t?.storeKey)||null,walletId:o(t?.walletId)||null,reason:n,safeSummary:$o(t)}}function es(e){return{v:2,alg:ue,storageScope:le,authMethod:e,secretKind:de}}function ts(e){e=Fo(e);let t=C(e);if(!t)return X(`malformed`,null,`invalid_payload`);if(No(t))return X(`delete_required`,t,`invalid_identity`);if(t.recordKind===`ecdsa_reauth_anchor_v1`)return X(`delete_required`,t,`invalid_header`);if(t.recordKind===ko){let e=is(t);return e?{kind:`ecdsa_inactive_material`,record:e}:X(`malformed`,t,`invalid_identity`)}if(Number(t.v)===1)return X(`delete_required`,t,`invalid_header`);if(Number(t.v)!==2||String(t.alg||``).trim()!==`shamir3pass-v2`||String(t.storageScope||``).trim()!==`iframe_origin_indexeddb`||String(t.secretKind||``).trim()!==`signing_session_secret32`)return X(`malformed`,t,`invalid_header`);let r=String(t.authMethod||``).trim(),i=Mo(t),a=o(t.sealedSecretB64u),s=Po(t.curve),c=o(t.subjectId),l=o(t.userId),u=o(t.walletId),d=o(t.signingRootId),f=o(t.signingRootVersion),p=f||(d?`default`:null),m=o(t.relayerUrl),h=o(t.keyVersion),g=o(t.groupId),_=n(t.issuedAtMs),v=n(t.expiresAtMs),y=n(t.remainingUses),b=n(t.updatedAtMs);if(!a||!h||g!==`rfc2409-group2`||r!==`passkey`&&r!==`email_otp`||!i.ed25519&&!i.ecdsa||!u)return X(`malformed`,t,`invalid_identity`);let x=Bo({curve:s,thresholdSessionIds:i});if(!x||_==null||_<=0||v==null||v<=0||y==null||y<0||b==null||b<=0)return X(`malformed`,t,`invalid_identity`);let S=C(t.ecdsaRestore),w=C(t.ed25519Restore),T=Wo(t.ecdsaRestore),E=Go(t.ed25519Restore);if(x===`ecdsa`){if(!i.ecdsa)return X(`malformed`,t,`invalid_identity`);if(c||l||d||f)return X(`delete_required`,t,`invalid_identity`);if(!S||!m)return X(`rebuild_required`,t,`missing_restore_metadata`);if(!Qo(S.participantIds).length)return X(`delete_required`,t,`missing_participant_ids`);if(!T)return X(`rebuild_required`,t,`missing_restore_metadata`);let e=Oo({walletId:u,authMethod:r,chainTarget:T.chainTarget,materialActivation:T.roleLocalMaterialRef.materialActivation}),n=o(t.storeKey);return n&&n!==e?X(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...es(r),storeKey:e,thresholdSessionIds:{...i.ed25519?{ed25519:i.ed25519}:{},ecdsa:i.ecdsa},sealedSecretB64u:a,curve:`ecdsa`,walletId:u,relayerUrl:m,keyVersion:h,groupId:oe,ecdsaRestore:T,...E?{ed25519Restore:E}:{},issuedAtMs:_,expiresAtMs:v,remainingUses:y,updatedAtMs:b}}}if(!i.ed25519)return X(`malformed`,t,`invalid_identity`);if(c||l)return X(`delete_required`,t,`invalid_identity`);if(!w||!m)return X(`rebuild_required`,t,`missing_restore_metadata`);if(!Qo(w.participantIds).length)return X(`delete_required`,t,`missing_participant_ids`);if(!E)return X(`rebuild_required`,t,`missing_restore_metadata`);let D=Ko({walletId:u,authMethod:r,restore:E}),O=o(t.storeKey);return O&&O!==D?X(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...es(r),storeKey:D,thresholdSessionIds:{ed25519:i.ed25519,...i.ecdsa?{ecdsa:i.ecdsa}:{}},sealedSecretB64u:a,curve:`ed25519`,walletId:u,...d?{signingRootId:d}:{},...p?{signingRootVersion:p}:{},relayerUrl:m,keyVersion:h,groupId:oe,...T?{ecdsaRestore:T}:{},ed25519Restore:E,issuedAtMs:_,expiresAtMs:v,remainingUses:y,updatedAtMs:b}}}function ns(e){let t=ts(Fo(e));return t.kind===`current`?t.record:null}function rs(e){let t=C(e);if(!t||t.clientVerifyingShareB64u!=null)return null;let n,r,i,a;try{n=Fe(t.chainTarget&&typeof t.chainTarget==`object`?t.chainTarget:{}),r=I(t.runtimePolicyScope);let e=st(t.routerAbEcdsaDerivationNormalSigning);if(!e)return null;i=e,a=Ct(t.publicCapability)}catch{return null}let s=o(t.signingRootId),c=o(t.signingRootVersion),l=null;try{l=dn(t.roleLocalMaterialRef)}catch{l=null}let u=bt(t.authority),d=lt(t.emailOtpAuthority),f=o(t.keyHandle),p=o(t.ecdsaThresholdKeyId),m=o(t.ethereumAddress),h=o(t.relayerKeyId),g=o(t.thresholdEcdsaPublicKeyB64u),_=Qo(t.participantIds);if(!s||!c||!f||!p||!m||!h||!g||!_.length)return null;let v={chainTarget:n,signingRootId:s,signingRootVersion:c,keyHandle:f,ecdsaThresholdKeyId:p,ethereumAddress:m,relayerKeyId:h,thresholdEcdsaPublicKeyB64u:g,participantIds:_,runtimePolicyScope:r,routerAbEcdsaDerivationNormalSigning:i,publicCapability:a};switch(t.source){case`email_otp`:{let e=t.provider===`google`||t.provider===`email`?t.provider:null,n=o(t.providerSubjectId),r=o(t.emailHashHex);return!e||!n||!r||!l||!u||!d||t.rpId!=null||t.credentialIdB64u!=null?null:{...v,source:`email_otp`,provider:e,providerSubjectId:n,emailHashHex:r,authority:u,emailOtpAuthority:d,roleLocalMaterialRef:l}}case`login`:case`registration`:case`manual-bootstrap`:{let e=o(t.rpId),n=o(t.credentialIdB64u);return!e||!n||!l||!u||t.providerSubjectId!=null||t.emailHashHex!=null?null:{...v,source:t.source,authority:u,roleLocalMaterialRef:l,rpId:e,credentialIdB64u:n}}default:return null}}function is(e){let t=C(Fo(e));if(!t||t.recordKind!==ko||No(t)||t.thresholdSessionIds!=null||t.ed25519Restore!=null||t.curve!==`ecdsa`)return null;let r=Yo(t.authMethod),i=o(t.walletId),a=o(t.relayerUrl),s=rs(t.ecdsaRestore),c=o(t.sealedSecretB64u),l=o(t.keyVersion),u=o(t.groupId),d=n(t.updatedAtMs),f=t.authorizationRetirementReason;if(!r||!i||!a||!s||t.alg!==`shamir3pass-v2`||t.storageScope!==`iframe_origin_indexeddb`||t.secretKind!==`signing_session_secret32`||!c||!l||u!==`rfc2409-group2`||t.issuedAtMs!=null||t.expiresAtMs!=null||t.remainingUses!=null||d==null||d<=0||f!==`expired`&&f!==`exhausted`)return null;let p=qo({walletId:i,authMethod:r,restore:s});return o(t.storeKey)===p?as({storeKey:p,walletId:i,relayerUrl:a,sealedSecretB64u:c,keyVersion:l,updatedAtMs:d,authorizationRetirementReason:f,authMethod:r,ecdsaRestore:s}):null}function as(e){let{authMethod:t,ecdsaRestore:n}=e,r={recordKind:ko,storeKey:e.storeKey,curve:`ecdsa`,walletId:e.walletId,relayerUrl:e.relayerUrl,alg:ue,storageScope:le,secretKind:de,sealedSecretB64u:e.sealedSecretB64u,keyVersion:e.keyVersion,groupId:oe,updatedAtMs:e.updatedAtMs,authorizationRetirementReason:e.authorizationRetirementReason};return t===`email_otp`&&n.source===`email_otp`||t===`passkey`&&n.source!==`email_otp`?{...r,authMethod:t,ecdsaRestore:n}:null}function os(e){if(e.classification.kind===`ecdsa_inactive_material`||e.classification.kind===`rebuild_required`)return;let t=e.classification.kind===`malformed`?`malformed`:`rejected`,n={operation:e.operation,outcome:t,classificationKind:e.classification.kind,...e.classification};console.warn(`[SigningSessionSealedStore] rejected sealed record`,n)}function ss(e){let t=String(e.thresholdSessionId||``).trim(),r=Po(e.curve),i=e.authMethod===`passkey`||e.authMethod===`email_otp`?e.authMethod:void 0;if(!r||!i)return null;let a=cs({thresholdSessionId:t,curve:r,thresholdSessionIds:e.thresholdSessionIds}),s=o(e.walletId),c=o(e.sealedSecretB64u),l=n(e.expiresAtMs),u=n(e.remainingUses),d=n(e.issuedAtMs),f=n(e.updatedAtMs),p=o(e.keyVersion);if(!t||!c||!p||e.groupId!==`rfc2409-group2`||!a.ed25519&&!a.ecdsa||d==null||d<=0||l==null||l<=0||u==null||u<0||f==null||f<=0)return null;let m=Wo(e.ecdsaRestore),h=Go(e.ed25519Restore);if(Xo(e)||r===`ecdsa`&&(!m?.chainTarget||!s||Zo(e)))return null;let g,_;e.curve===`ed25519`&&(g=o(e.signingRootId),_=o(e.signingRootVersion));let v=ts({...es(i),thresholdSessionIds:a,sealedSecretB64u:c,curve:r,...s?{walletId:s}:{},...g?{signingRootId:g}:{},..._?{signingRootVersion:_}:{},...o(e.relayerUrl)?{relayerUrl:o(e.relayerUrl)}:{},keyVersion:p,groupId:oe,...m?{ecdsaRestore:m}:{},...h?{ed25519Restore:h}:{},issuedAtMs:d,expiresAtMs:l,remainingUses:u,updatedAtMs:f});return v.kind===`current`?v.record:(os({operation:`build current sealed session record`,classification:v}),null)}function cs(e){let t=jo(e.thresholdSessionIds),n=String(e.thresholdSessionId||``).trim();return n&&(e.curve===`ed25519`&&t.ed25519===n||e.curve===`ecdsa`&&t.ecdsa===n)?t:{}}function ls(e,t){let n=o(t),r=o(e.ecdsaThresholdKeyId),i=o(e.thresholdEcdsaPublicKeyB64u);if(!n||!r||!i)return null;let a;try{a=I(e.runtimePolicyScope)}catch{return null}let s={chainTarget:e.chainTarget,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,keyHandle:e.keyHandle,ecdsaThresholdKeyId:r,ethereumAddress:e.ethereumAddress,relayerKeyId:e.relayerKeyId,thresholdEcdsaPublicKeyB64u:i,participantIds:[...e.participantIds],runtimePolicyScope:a,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,publicCapability:e.publicCapability};switch(e.source){case`email_otp`:return{...s,source:`email_otp`,provider:e.provider,providerSubjectId:e.providerSubjectId,emailHashHex:e.emailHashHex,authority:e.authority,emailOtpAuthority:e.emailOtpAuthority,roleLocalMaterialRef:dn(e.roleLocalMaterialRef)};case`login`:case`registration`:case`manual-bootstrap`:return{...s,source:e.source,authority:e.authority,roleLocalMaterialRef:dn(e.roleLocalMaterialRef),rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}}}function us(e){let t=e.record,n=ls(t.ecdsaRestore,t.relayerUrl);return n?as({storeKey:qo({walletId:t.walletId,authMethod:t.authMethod,restore:n}),walletId:t.walletId,relayerUrl:t.relayerUrl,sealedSecretB64u:t.sealedSecretB64u,keyVersion:t.keyVersion,updatedAtMs:e.updatedAtMs,authorizationRetirementReason:e.retirement,authMethod:t.authMethod,ecdsaRestore:n}):null}function ds(e){let t=us(e);if(!t)throw Error(`[SigningSessionSealedStore] inactive ECDSA material requires exact public restore facts`);return t}const fs=15e3;function ps(e){return ie(e,32,`sealed signing session restore IDs`)}function ms(e){return{lease_key:e.leaseKey,owner_id:e.ownerId,attempt_id:e.attemptId,started_at_ms:e.startedAtMs,expires_at_ms:e.expiresAtMs,lease:e}}function hs(e){let t=new Set,n=o(e.walletId);return n&&t.add(n),t}function gs(e,t){let n=hs(e);if(!n.size)return!1;for(let e of hs(t))if(n.has(e))return!0;return!1}function _s(e,t){if(!gs(e,t)||e.authMethod!==t.authMethod||e.curve!==t.curve)return!1;if(e.curve===`ed25519`&&t.curve===`ed25519`)return p(e.ed25519Restore.materialActivation,t.ed25519Restore.materialActivation);if(e.curve===`ecdsa`){let n=o(e.ecdsaRestore?.keyHandle),r=o(t.ecdsaRestore?.keyHandle);if(!n||!r||n!==r)return!1;let i=e.ecdsaRestore?.chainTarget,a=t.ecdsaRestore?.chainTarget;if(!i||!a||!Be(i,a))return!1}return!0}function vs(e){return x({storeKey:e.storeKey,walletId:e.walletId,authMethod:e.authMethod,signingRootId:e.signingRootId??null,signingRootVersion:e.signingRootVersion??null,restore:e.ed25519Restore})}function ys(e,t){if(typeof e.primaryKey!=`string`||!e.primaryKey.trim())throw Error(`[SigningSessionSealedStore] exact Ed25519 record key is invalid`);return{primaryKey:e.primaryKey,record:t}}function bs(e,t){return e.record.updatedAtMs===t.record.updatedAtMs?e.primaryKey===e.record.storeKey?e:t.primaryKey===t.record.storeKey?t:e.primaryKey.localeCompare(t.primaryKey)<=0?e:t:e.record.updatedAtMs>t.record.updatedAtMs?e:t}async function xs(e,t={writeCanonical:!1}){let n=e[0];if(!n)return null;let r=vs(n.record);for(let t of e.slice(1))if(vs(t.record)!==r)throw Error(`[SigningSessionSealedStore] exact Ed25519 material has conflicting public identity facts`);let i=e.reduce(bs),a=i.record.storeKey,o=[...new Set(e.map(e=>e.primaryKey))].filter(e=>e!==a);return(t.writeCanonical||o.length>0||i.primaryKey!==a)&&await Y.replaceSealedRecord({row:Ro(i.record),staleStoreKeys:o}),i.record}async function Ss(e){let t=Fo(e.value),n=ts(t);if(n.kind!==`current`)return n;let r=C(t);return No(C(e.value))||No(r)?X(`delete_required`,r,`invalid_identity`):n}function Cs(e){return Mo(Fo(e))}function ws(e,t,n,r){os({operation:e,classification:t}),(t.kind===`delete_required`||t.kind===`malformed`)&&r.push(n)}function Ts(e){let t=C(e);if(!t)return null;if(C(t.lease))return Ts(t.lease);if(Number(t.v)!==1||No(t))return null;let r=o(t.leaseKey),i=o(t.ownerId),a=o(t.attemptId),s=n(t.startedAtMs),c=n(t.expiresAtMs);return!r||!i||!a||s==null||s<=0||c==null||c<=s?null:{v:1,leaseKey:r,ownerId:i,attemptId:a,startedAtMs:s,expiresAtMs:c}}function Es(e){return{v:1,leaseKey:e.leaseKey,ownerId:e.ownerId,attemptId:ps(`restore-attempt`),startedAtMs:e.nowMs,expiresAtMs:e.nowMs+e.ttlMs}}function Ds(e,t,n){return!(e.authMethod!==n.authMethod||e.thresholdSessionIds[n.curve]!==t||n.curve===`ecdsa`&&(!e.ecdsaRestore?.chainTarget||!Be(e.ecdsaRestore.chainTarget,n.chainTarget)))}function Os(e,t){if(e?.authMethod&&e.curve===`ed25519`||e?.authMethod&&e.curve===`ecdsa`&&e.chainTarget)return e;throw console.warn(`[SigningSessionSealedStore] rejected ambiguous sealed record access`,{operation:t}),Error(`[SigningSessionSealedStore] ${t} requires an explicit authMethod, curve, and ECDSA chain target`)}async function ks(e){let t=await Y.collectRawSealedRecordEntriesByThresholdSessionId(e);return t.length?t:(await Y.collectAllRawSealedRecordEntries()).filter(t=>{let n=Cs(t.value);return n.ed25519===e||n.ecdsa===e})}async function As(e,t,n){let r=await ks(e),i=null,a=[],o=[];for(let s of r){let r=await Ss(s);if(r.kind===`current`){Ds(r.record,e,t)&&(i=r.record,r.record.curve===`ed25519`&&a.push(ys(s,r.record)));continue}ws(n,r,s.primaryKey,o)}return await Y.deleteSealedRecords(o),a.length>0?await xs(a):i}async function js(e,t){try{let n=await ks(e),r=[];for(let i of n){let n=await Ss(i),a=n.kind===`current`?n.record:null;a?.storeKey&&Ds(a,e,t)&&r.push(i.primaryKey)}await Y.deleteSealedRecords(r)}catch{}}async function Ms(e){if(!hs(e).size||!e.authMethod)return[];try{let t=await Y.collectAllRawSealedRecordEntries(),n=[];for(let r of t){let t=await Ss(r),i=t.kind===`current`?t.record:null;i&&i.storeKey!==e.storeKey&&_s(i,e)&&n.push(i)}return n}catch{return[]}}function Ns(e){if(e.curve!==`ecdsa`)return null;let t=ls(e.ecdsaRestore,e.relayerUrl);return t?qo({walletId:e.walletId,authMethod:e.authMethod,restore:t}):null}async function Ps(e,t){let n=Os(t,`read`),r=String(e||``).trim();return r?await As(r,n,`read`):null}function Fs(e,t){return e.curve===`ed25519`&&e.authMethod===t.authMethod&&p(e.ed25519Restore.materialActivation,t.materialActivation)}async function Is(e){let t=await Y.collectAllRawSealedRecordEntries(),n=[],r=[];for(let i of t){let t=await Ss(i);if(t.kind===`current`){let n=t.record;Fs(n,e)&&r.push(ys(i,n));continue}ws(`read exact Ed25519 material`,t,i.primaryKey,n)}return await Y.deleteSealedRecords(n),await xs(r)}async function Ls(e){let t=o(e.walletId);if(!t)return[];let n=Os(e.filter,`list exact account records`),r=e.filter.curve===`ecdsa`?e.filter.chainTarget:void 0,i=await Y.collectAllRawSealedRecordEntries(),a=[];try{let e=[],o=new Set,s=new Map;for(let c of i){let i=await Ss(c);if(i.kind!==`current`){ws(`list exact account records`,i,c.primaryKey,a);continue}let l=i.record;if(l.walletId===t&&l.authMethod===n.authMethod&&l.thresholdSessionIds[n.curve]&&!(r&&(!l.ecdsaRestore?.chainTarget||!Be(l.ecdsaRestore.chainTarget,r)))){if(l.curve===`ed25519`){let e=s.get(l.storeKey)??[];e.push(ys(c,l)),s.set(l.storeKey,e);continue}o.has(l.storeKey)||(o.add(l.storeKey),e.push(l))}}for(let t of s.values()){let n=await xs(t);n&&e.push(n)}return await Y.deleteSealedRecords(a),e}finally{await Y.deleteSealedRecords(a)}}async function Rs(e){let t=o(e.walletId);if(!t)return[];if(e.filter.curve!==`ecdsa`)return console.warn(`[SigningSessionSealedStore] rejected non-ECDSA wallet-scoped list`,{operation:`list wallet ecdsa records`}),[];let n=await Y.collectAllRawSealedRecordEntries(),r=[];try{let i=[],a=new Set;for(let o of n){let n=await Ss(o);if(n.kind===`ecdsa_inactive_material`){let r=n.record;if(r.walletId!==t||e.filter.authMethod&&r.authMethod!==e.filter.authMethod||a.has(r.storeKey))continue;a.add(r.storeKey),i.push(r);continue}if(n.kind!==`current`){ws(`list wallet ecdsa records`,n,o.primaryKey,r);continue}let s=n.record;s.walletId===t&&(e.filter.authMethod&&s.authMethod!==e.filter.authMethod||s.thresholdSessionIds.ecdsa&&s.ecdsaRestore?.chainTarget&&(a.has(s.storeKey)||(a.add(s.storeKey),i.push(s))))}return await Y.deleteSealedRecords(r),i}finally{await Y.deleteSealedRecords(r)}}async function zs(e){let t=ts(e);if(t.kind!==`current`){os({operation:`write exact sealed session`,classification:t});return}let n=t.record;if(n.curve===`ed25519`){let e=[{primaryKey:n.storeKey,record:n}],t=await Y.collectAllRawSealedRecordEntries();for(let r of t){let t=await Ss(r);t.kind===`current`&&t.record.curve===`ed25519`&&t.record.storeKey===n.storeKey&&e.push(ys(r,t.record))}await xs(e,{writeCanonical:!0});return}let r=await Ms(n),i=Ns(n);await Y.replaceSealedRecord({row:Ro(n),staleStoreKeys:[...r.map(e=>e.storeKey),...i?[i]:[]]})}function Bs(e,t,n){return Vs({current:e,inactive:ds({record:e,retirement:t,updatedAtMs:n})})}async function Vs(e){await Y.replaceSealedRecordAndDeleteRestoreLease({row:Lo(e.inactive),staleStoreKeys:[e.current.storeKey],restoreLeaseKey:e.current.storeKey})}async function Hs(e){let t=Os(e.filter,`update policy`),n=String(e.thresholdSessionId||``).trim();if(!n)return;let r=await Ps(n,t);r&&await Ws(r,e)}async function Us(e){let t=await Is(e.locator);t&&await Ws(t,e)}async function Ws(e,t){let r=n(t.expiresAtMs??e.expiresAtMs),i=n(t.remainingUses??e.remainingUses),a=n(t.updatedAtMs);if(r==null||r<=0||i==null||i<0||a==null||a<=0)return;let o={...e,expiresAtMs:r,remainingUses:i,updatedAtMs:a};if(o.curve===`ecdsa`){let e=r<=Date.now()?`expired`:i===0?`exhausted`:null;if(e){await Bs(o,e,a);return}}await zs(o)}async function Gs(e,t,n){let r=Os(t,`delete`),i=String(e||``).trim();if(!i)return;let a=await As(i,r,`delete`);await js(i,r),a&&n.deleteResolvedIdentity&&await Y.deleteRestoreLease(a.storeKey)}async function Ks(e,t){let n=await Y.collectAllRawSealedRecordEntries(),r=[],i=[];for(let a of n){let n=await Ss(a);if(n.kind!==`current`){os({operation:`delete exact Ed25519 material`,classification:n});continue}let o=n.record;Fs(o,e)&&(r.push(a.primaryKey),t.deleteResolvedIdentity&&i.push(o.storeKey))}if(await Y.deleteSealedRecords(r),t.deleteResolvedIdentity)for(let e of i)await Y.deleteRestoreLease(e)}async function qs(e){let t=e.preserveResolvedIdentity?{deleteResolvedIdentity:!1}:{deleteResolvedIdentity:!0,resolvedIdentityDeleteReason:`durable_record_deleted`};if(e.durableRecord.curve===`ed25519`){await Ks({kind:`ed25519_durable_material`,authMethod:e.durableRecord.authMethod,materialActivation:e.durableRecord.materialActivation},t);return}let n=Do(e.durableRecord),r=await Js(e.durableRecord.thresholdSessionId,n);if(e.preserveResolvedIdentity&&e.durableRecord.curve===`ecdsa`&&r?.curve===`ecdsa`&&(e.deleteReason===`expired`||e.deleteReason===`exhausted`)){await Bs(r,e.deleteReason,Date.now());return}await Gs(e.durableRecord.thresholdSessionId,n,t)}async function Js(e,t){try{return await Ps(e,t)}catch{return null}}async function Ys(e){let t=Os(e,`acquire restore lease`),r=String(e.thresholdSessionId||``).trim();if(!r)return null;let i=n(e.nowMs??Date.now())??Date.now(),a=Math.max(1,n(e.ttlMs??fs)??fs),s=o(e.ownerId)||ps(`restore-owner`);return await As(r,t,`acquire restore lease`)?await Y.withRestoreLeaseTransaction(r,async e=>{let n=[];for(let t of e.entries){let e=ns(t.value);e?.storeKey&&!n.some(t=>t.storeKey===e.storeKey)&&n.push(e)}let o=n.find(e=>Ds(e,r,t))||null;if(!o)return e.abort(),null;let c=Ts(await e.getRawRestoreLease(o.storeKey));if(c&&c.expiresAtMs>i&&c.ownerId!==s)return e.abort(),null;let l=Es({leaseKey:o.storeKey,ownerId:s,nowMs:i,ttlMs:a});return e.putRestoreLease(ms(l)),{...l,thresholdSessionId:r}}):null}async function Xs(e){!e?.leaseKey||!e.ownerId||!e.attemptId||await Y.deleteRestoreLeaseIf({leaseKey:e.leaseKey,shouldDelete:t=>{let n=Ts(t);return n?.ownerId===e.ownerId&&n.attemptId===e.attemptId}})}function Zs(e){return String(e??``).trim()||null}function Qs(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function $s(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:null}function ec(e){let t=ne(e);return t?.length===2?[t[0],t[1]]:null}function tc(e){let t=e.ed25519Restore;switch(e.authMethod){case Ge.passkey:{let e=Zs(t.credentialIdB64u);return e?{kind:`passkey`,rpId:pt(t.rpId),credentialIdB64u:e}:null}case Ge.emailOtp:{if(!(`provider`in t))return null;let e=Zs(t.providerSubjectId),n=Zs(t.emailHashHex);return!e||!n?null:{kind:`email_otp`,provider:t.provider,providerSubjectId:e,emailHashHex:n}}}}function nc(e){switch(e.kind){case`passkey`:return{kind:Ge.passkey,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u};case`email_otp`:return{kind:Ge.emailOtp,providerSubjectId:e.providerSubjectId}}}function rc(e){let t=e.ed25519Restore,n=Zs(e.thresholdSessionIds.ed25519),r=Zs(e.relayerUrl),i=Zs(t.relayerKeyId),a=Qs(e.expiresAtMs),o=$s(e.remainingUses),s=Dn(t.signerSlot),c=ec(t.participantIds),l=ae(t.runtimePolicyScope),u=l?re(l):null,d=Zs(u?.signingRootVersion),f=se(t.routerAbNormalSigning),p=tc(e);if(!n||!r||!i||!a||o===null||!s||!c||!l||!u||!d||!f||f.signingWorkerId!==i||!p||e.signingRootId!==u.signingRootId||e.signingRootVersion!==d)return null;try{return{kind:`exact_ed25519_sealed_session_runtime`,sealedRecord:e,walletId:Ie(e.walletId),nearAccountId:z(t.nearAccountId),nearEd25519SigningKeyId:Yt(t.nearEd25519SigningKeyId),signerSlot:s,factor:p,auth:nc(p),thresholdSessionId:Fn.thresholdEd25519Session(n),remainingUses:o,expiresAtMs:a,relayerUrl:r,relayerKeyId:i,participantIds:c,runtimePolicyScope:l,signingRootId:u.signingRootId,signingRootVersion:d,routerAbNormalSigning:f}}catch{return null}}async function ic(e){let t;switch(e.runtime.factor.kind){case`passkey`:t=xt({walletId:e.runtime.walletId,factor:{kind:`passkey`,credentialIdB64u:e.runtime.factor.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.runtime.factor.rpId},bindingId:e.walletAuthMethodId});break;case`email_otp`:t=lt({walletId:e.runtime.walletId,factor:{kind:`email_otp`,provider:e.runtime.factor.provider,providerUserId:e.runtime.factor.providerSubjectId},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:e.runtime.factor.emailHashHex},bindingId:e.walletAuthMethodId});break;default:return ac(e.runtime.factor)}if(!t)throw Error(`[SigningEngine][near] sealed Ed25519 authority is invalid`);return await ct({authority:t})}function ac(e){throw Error(`Unsupported Ed25519 factor: ${String(e)}`)}async function oc(e){let{authorization:t,runtime:n}=e;if(t.session.walletId!==n.walletId||t.session.authMethodId!==t.selectedAuthMethod.walletAuthMethodId||t.session.quotaId!==t.status.quotaId||t.operationCredential.walletSessionId!==t.status.walletSessionId||t.operationCredential.token.trim().length===0||t.status.remainingUses<=0||!ar({session:t.session,materialActivation:n.sealedRecord.ed25519Restore.materialActivation}))return!1;if(n.factor.kind===`passkey`){if(t.selectedAuthMethod.kind!==`passkey`||String(t.selectedAuthMethod.rpId)!==String(n.factor.rpId)||t.selectedAuthMethod.credentialIdB64u!==n.factor.credentialIdB64u||t.selectedFactorAuthority.factor.kind!==`passkey`||t.selectedFactorAuthority.factor.credentialIdB64u!==n.factor.credentialIdB64u||t.selectedFactorAuthority.verifier.kind!==`webauthn`||String(t.selectedFactorAuthority.verifier.rpId)!==String(n.factor.rpId))return!1}else if(t.selectedAuthMethod.kind!==`email_otp`||t.selectedAuthMethod.emailHashHex!==n.factor.emailHashHex||t.selectedFactorAuthority.factor.kind!==`email_otp`||t.selectedFactorAuthority.factor.provider!==n.factor.provider||t.selectedFactorAuthority.factor.providerUserId!==n.factor.providerSubjectId||t.selectedFactorAuthority.verifier.kind!==`email_otp_wallet_auth_method`||t.selectedFactorAuthority.verifier.emailHashHex!==n.factor.emailHashHex)return!1;try{let e=await ic({runtime:n,walletAuthMethodId:t.selectedAuthMethod.walletAuthMethodId}),r=await ct({authority:t.selectedFactorAuthority});return e.walletId===t.selectedAuthority.walletId&&e.walletAuthMethodId===t.selectedAuthMethod.walletAuthMethodId&&e.walletId===r.walletId&&e.walletAuthMethodId===r.walletAuthMethodId&&e.authorityDigest===r.authorityDigest}catch{return!1}}function sc(e,t){switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u;case`email_otp`:return t.kind===`email_otp`&&e.providerSubjectId===t.providerSubjectId}}function cc(e){let t=e.laneIdentity.signer,n=e.record.ed25519Restore;return e.record.walletId===t.account.wallet.walletId&&n.nearAccountId===t.account.nearAccountId&&n.nearEd25519SigningKeyId===t.nearEd25519SigningKeyId&&n.signerSlot===t.signerSlot&&e.record.thresholdSessionIds.ed25519===e.laneIdentity.thresholdSessionId}function lc(e,t){return sc(e.auth,t.auth)}async function uc(e,t){let n=(await t.listExactSealedSessionsForWallet({walletId:e.walletId,filter:{authMethod:e.laneIdentity.auth.kind,curve:`ed25519`}})).filter(t=>t.curve===`ed25519`&&cc({record:t,laneIdentity:e.laneIdentity}));if(n.length===0)return{kind:`missing`};if(n.length>1)return{kind:`conflict`};let r=rc(n[0]);return!r||!lc(r,e.laneIdentity)?{kind:`corrupt`}:{kind:`resolved`,runtime:r}}async function dc(e){return await uc(e,{listExactSealedSessionsForWallet:Ls})}async function fc(e,t){return mc(await pc(e,t))}async function pc(e,t){let n=await Promise.all([t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Ge.passkey,curve:`ed25519`}}),t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Ge.emailOtp,curve:`ed25519`}})]),r=[];for(let e of n)for(let t of e)t.curve===`ed25519`&&r.push(t);return r}function mc(e){if(e.length===0)return{kind:`missing`};if(e.length>1)return{kind:`conflict`};let t=rc(e[0]);return t?{kind:`resolved`,runtime:t}:{kind:`corrupt`}}async function hc(e){return await fc(e,{listExactSealedSessionsForWallet:Ls})}async function gc(e,t){let n=await pc(e.walletId,t),r=[];for(let t of n)t.ed25519Restore.nearAccountId===e.nearAccountId&&t.ed25519Restore.nearEd25519SigningKeyId===e.nearEd25519SigningKeyId&&r.push(t);return mc(r)}async function _c(e){return await gc(e,{listExactSealedSessionsForWallet:Ls})}function vc(e,t){let n=String(e).trim();if(!n)throw Error(`${t} is required for Ed25519 Wallet Session state`);return n}function yc(e,t){if(!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be positive for Ed25519 Wallet Session state`);return e}function bc(e){let t=Fn.thresholdEd25519Session(vc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=vc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=vc(e.relayerUrl,`relayerUrl`),i=vc(e.providerSubjectId,`providerSubjectId`),a=yc(e.signerSlot,`signerSlot`),o=yc(e.signingWalletSession.remainingUses,`remainingUses`);return{walletSessionAuth:{kind:`wallet_session_opaque`,home:e.signingWalletSession.auth.credential.home,walletSessionToken:n},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,signingLane:dr({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:a,auth:{kind:`email_otp`,providerSubjectId:i},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,retention:`session`,sessionOrigin:`login`}),remainingUses:o,signingRootId:e.signingWalletSession.signingRootId,signingRootVersion:e.signingWalletSession.signingRootVersion,routerAbNormalSigning:e.signingWalletSession.routerAbNormalSigning,runtimePolicyScope:e.signingWalletSession.runtimePolicyScope,relayerUrl:r,signingWalletSession:e.signingWalletSession,authority:e.authority}}function xc(e){let t=Fn.thresholdEd25519Session(vc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=vc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=vc(e.relayerUrl,`relayerUrl`),i=vc(e.credentialIdB64u,`credentialIdB64u`),a=yc(e.signerSlot,`signerSlot`);return{walletSessionAuth:{kind:`wallet_session_opaque`,home:e.signingWalletSession.auth.credential.home,walletSessionToken:n},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,signingLane:dr({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:a,auth:{kind:`passkey`,rpId:e.rpId,credentialIdB64u:i},walletSessionId:e.signingWalletSession.walletSessionId,quotaId:e.signingWalletSession.quotaId,thresholdSessionId:t,storageSource:`login`}),remainingUses:e.signingWalletSession.remainingUses,signingRootId:e.signingWalletSession.signingRootId,signingRootVersion:e.signingWalletSession.signingRootVersion,routerAbNormalSigning:e.signingWalletSession.routerAbNormalSigning,runtimePolicyScope:e.signingWalletSession.runtimePolicyScope,relayerUrl:r,signingWalletSession:e.signingWalletSession,authority:e.authority}}async function Sc(e){let t=e.authorization.operationCredential.token,n=e.authorization.session.authorizationId,r=await ic({runtime:e.runtime,walletAuthMethodId:e.authorization.selectedAuthMethod.walletAuthMethodId}),i=await ct({authority:e.authorization.selectedFactorAuthority}),a=Math.min(e.runtime.expiresAtMs,e.authorization.status.expiresAtMs);if(!t||!n||e.authorization.session.walletId!==e.runtime.walletId||e.authorization.selectedAuthMethod.kind!==e.runtime.auth.kind||r.walletId!==e.runtime.walletId||r.walletAuthMethodId!==e.authorization.selectedAuthMethod.walletAuthMethodId||r.walletId!==i.walletId||r.walletAuthMethodId!==i.walletAuthMethodId||String(r.authorityDigest)!==String(i.authorityDigest)||e.authorization.operationCredential.walletSessionId!==e.authorization.status.walletSessionId||a<=e.nowMs)throw Error(`Ed25519 Wallet Session authorization does not match sealed material`);let o=ho({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,walletSessionId:e.authorization.operationCredential.walletSessionId,authorizationId:n,quotaId:e.authorization.session.quotaId,thresholdSessionId:e.runtime.thresholdSessionId,remainingUses:Math.min(e.runtime.remainingUses,e.authorization.status.remainingUses),expiresAtMs:a,runtimePolicyScope:e.runtime.runtimePolicyScope,signingRootId:e.runtime.signingRootId,signingRootVersion:e.runtime.signingRootVersion,routerAbNormalSigning:e.runtime.routerAbNormalSigning,walletSessionToken:t,home:e.authorization.operationCredential.home,nowMs:e.nowMs});if(!o.ok)throw Error(`Ed25519 Wallet Session runtime is invalid: ${o.reason}`);if(e.runtime.factor.kind===`passkey`&&e.runtime.auth.kind===`passkey`)return xc({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,signerSlot:e.runtime.signerSlot,rpId:e.runtime.factor.rpId,credentialIdB64u:e.runtime.factor.credentialIdB64u,relayerUrl:e.runtime.relayerUrl,authority:r,signingWalletSession:o.value});if(e.runtime.factor.kind===`email_otp`&&e.runtime.auth.kind===`email_otp`)return bc({walletId:e.runtime.walletId,nearAccountId:e.runtime.nearAccountId,nearEd25519SigningKeyId:e.runtime.nearEd25519SigningKeyId,providerSubjectId:e.runtime.auth.providerSubjectId,signerSlot:e.runtime.signerSlot,relayerUrl:e.runtime.relayerUrl,authority:r,signingWalletSession:o.value});throw Error(`Ed25519 sealed runtime factor and auth binding disagree`)}function Cc(e){return{thresholdSessionId:e.thresholdSessionId,signer:e.signingLane.identity.signer,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,routerAbNormalSigning:e.routerAbNormalSigning,runtimePolicyScope:e.runtimePolicyScope,relayerUrl:e.relayerUrl}}function wc(e){return e.authorization.capabilitySubjects.some(t=>t.kind===`sign`&&t.keyFamily===`ed25519`&&p(t.materialActivation,e.materialActivation))}function Tc(e){let t=e.state,n=e.authorization,r=t.signingLane.identity.signer.account.wallet.walletId,i=e.operationCredential.token,a=t.signingLane.identity.signer,o=Math.min(t.signingWalletSession.expiresAtMs,n.expiresAtMs);if(!i||!wc({authorization:n,materialActivation:e.materialActivation})||n.walletId!==r||n.authMethodId!==t.authority.walletAuthMethodId||e.operationCredential.walletSessionId!==t.walletSessionId||n.authorizationId!==t.signingWalletSession.authorizationId||o<=e.nowMs||!Number.isSafeInteger(o))return null;let s=ho({walletId:String(a.account.wallet.walletId),nearAccountId:String(a.account.nearAccountId),nearEd25519SigningKeyId:String(a.nearEd25519SigningKeyId),walletSessionId:String(t.walletSessionId),authorizationId:String(t.signingWalletSession.authorizationId),quotaId:String(t.quotaId),thresholdSessionId:String(t.thresholdSessionId),remainingUses:t.remainingUses,expiresAtMs:o,runtimePolicyScope:t.runtimePolicyScope,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,routerAbNormalSigning:t.routerAbNormalSigning,walletSessionToken:i,home:e.operationCredential.home,nowMs:e.nowMs});if(!s.ok)return null;switch(t.signingLane.auth.kind){case`passkey`:return{...xc({walletId:a.account.wallet.walletId,nearAccountId:a.account.nearAccountId,nearEd25519SigningKeyId:a.nearEd25519SigningKeyId,signerSlot:a.signerSlot,rpId:t.signingLane.auth.rpId,credentialIdB64u:t.signingLane.auth.credentialIdB64u,relayerUrl:t.relayerUrl,authority:t.authority,signingWalletSession:s.value}),walletSessionAuthorization:n,walletSessionOperationCredential:e.operationCredential};case`email_otp`:return{...bc({walletId:a.account.wallet.walletId,nearAccountId:a.account.nearAccountId,nearEd25519SigningKeyId:a.nearEd25519SigningKeyId,providerSubjectId:t.signingLane.auth.providerSubjectId,signerSlot:a.signerSlot,relayerUrl:t.relayerUrl,authority:t.authority,signingWalletSession:s.value}),walletSessionAuthorization:n,walletSessionOperationCredential:e.operationCredential};default:return Ec(t.signingLane.auth)}}function Ec(e){throw Error(`Unknown Ed25519 signing lane auth: ${String(e)}`)}async function Dc(e){let t=e.state.signingLane.identity.signer.account.wallet.walletId,n=await co({ports:e.ports,input:{walletId:t,authMethod:Pn(e.state.signingLane.auth),walletSessionId:e.state.walletSessionId,quotaId:e.state.quotaId,requiredSigningSubject:so(e.state.signingLane.identity),expiry:{kind:`unexpired`,nowMs:e.nowMs}}});return n.kind!==`resolved`||n.resolved.authMethod.walletAuthMethodId!==e.state.authority.walletAuthMethodId?null:Tc({state:e.state,authorization:n.resolved.session,operationCredential:n.resolved.operationCredential,materialActivation:n.resolved.materialActivation,nowMs:e.nowMs})}function Oc(e){return ut(x({operation:`wallet_add_signer_activate_v2`,addSignerCeremonyId:e.addSignerCeremonyId,activationCorrelationId:e.activationCorrelationId,publicFacts:e.publicFacts}))}async function kc(e){return L(await A(String(Oc(e))))}function Ac(e){let t;try{t=$t(e,`custody envelope`)}catch(e){return{ok:!1,reason:e instanceof Error?e.message:`custody envelope is invalid`}}let n=t.lifecycle.state;return n===`active`?t.binding.kind===`wallet_custody_seed_v1`?{ok:!0,custodyJson:JSON.stringify({envelopeBinding:{walletId:t.walletId,envelopeId:t.envelopeId,factor:t.factor,envelopeRevision:t.envelopeRevision,binding:t.binding,ownership:on(t.ownership)},nonceB64u:t.nonceB64u,sealedCustodySecretB64u:t.sealedCustodySecretB64u,aadHashB64u:t.aadHashB64u,ciphertextDigestB64u:t.ciphertextDigestB64u})}:{ok:!1,reason:`generic custody wire rejects non-seed envelopes`}:{ok:!1,reason:`custody envelope is ${n}`}}function jc(e){let t={};return br()&&(t[`X-Seams-Benchmark-Diagnostics`]=`registration-flow`),e&&(t[vn]=e.value),Object.keys(t).length>0?t:void 0}function Mc(e){let t=R(e);if(t.length!==20)throw Error(`ECDSA activation returned an invalid address`);let n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return`0x${n}`}var Nc=class extends Error{code=`wallet_unlock_required`;next=`unlock_exact_method`;projection;constructor(e){super(`Registration response was already committed; exact-method unlock is required`),this.name=`RegistrationExactMethodUnlockRequiredError`,this.projection=e}};function Pc(e){switch(e.kind){case`issued`:return e.session;case`already_committed`:throw new Nc(e.session);default:return q(e)}}function Fc(e){let t=e[0];if(t)for(let n of e.slice(1)){let e=Lc(t,n);if(e)throw Error(`ECDSA registration returned partitioned EVM-family wallet key material: ${e}`)}}function Ic(e){for(let t of e.walletKeys)if(!vt(t.publicCapability,e.session.publicCapability))throw Error(`ECDSA registration wallet key public capability does not match client-verified activation`)}function Lc(e,t){return e.keyScope!==`evm-family`||t.keyScope!==`evm-family`?`keyScope`:e.walletId===t.walletId?e.evmFamilySigningKeySlotId===t.evmFamilySigningKeySlotId?e.keyHandle===t.keyHandle?e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId?e.signingRootId===t.signingRootId?e.signingRootVersion===t.signingRootVersion?e.thresholdEcdsaPublicKeyB64u===t.thresholdEcdsaPublicKeyB64u?e.thresholdOwnerAddress.trim().toLowerCase()===t.thresholdOwnerAddress.trim().toLowerCase()?e.relayerKeyId===t.relayerKeyId?e.relayerVerifyingShareB64u===t.relayerVerifyingShareB64u?e.participantIds.join(`,`)===t.participantIds.join(`,`)?null:`participantIds`:`relayerVerifyingShareB64u`:`relayerKeyId`:`thresholdOwnerAddress`:`thresholdEcdsaPublicKeyB64u`:`signingRootVersion`:`signingRootId`:`ecdsaThresholdKeyId`:`keyHandle`:`evmFamilySigningKeySlotId`:`walletId`}function Rc(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||Re(r)!==Re(i))return!1}return!0}async function zc(e){try{await e.context.signingEngine.closeRouterAbEcdsaRegistrationCeremony({kind:`close_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:e.ceremonyId})}catch{return}}function Bc(e){let t=e.prepare;return{formatVersion:t.formatVersion,walletId:t.walletId,evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,signingRootId:t.signingRootId,signingRootVersion:t.signingRootVersion,keyScope:t.keyScope,relayerKeyId:t.relayerKeyId,registrationPreparationId:t.registrationPreparationId,requestId:t.requestId,thresholdSessionId:t.thresholdSessionId,ttlMs:t.ttlMs,remainingUses:t.remainingUses,participantIds:[...t.participantIds],runtimePolicyScope:t.runtimePolicyScope,derivationClientSharePublicKey33B64u:e.verified.derivationClientSharePublicKey33B64u,clientShareRetryCounter:e.verified.clientShareRetryCounter,contextBinding32B64u:e.verified.contextBinding32B64u}}async function Vc(e){return{canonicalRequest:Oc(e),requestDigest:xe(await kc(e))}}async function Hc(e){try{return await Jn(e)}catch{return await Jn(e)}}async function Uc(e){return e.registrationTiming?await e.registrationTiming.measure(e.bucket,e.operation):await e.operation()}async function Wc(e){let[t,...n]=e.started.chainTargets;if(!t)throw Error(`Strict ECDSA ceremony requires at least one EVM-family target`);let r=e.addSignerCeremonyId,i=be(r);try{let a=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientCreateMs`,operation:e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony.bind(e.context.signingEngine,{kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:r,registration:e.started.strictRegistration})}),o=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Kn.bind(void 0,{relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:r,ecdsa:{kind:`router_ab_ecdsa_registration_v1`,strictRegistration:a.registrationRequest,requestDigestB64u:a.registrationRequestDigestB64u}})}),s=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientProofVerifyMs`,operation:e.context.signingEngine.verifyRouterAbEcdsaRegistrationClientProofs.bind(e.context.signingEngine,{kind:`verify_router_ab_ecdsa_registration_client_proofs_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:o.ecdsa.strictResult.response.bundles}})}),c=Ac(e.custodyEnvelope);if(!c.ok)throw Error(c.reason);let l={response:null,journalId:null},u=await e.context.signingEngine.joinWalletCustodyEvmFamilyKeySet({walletId:e.walletId,custodyJson:c.custodyJson,factorSecret:e.factorSecret,evmFamilySigningKeySlotId:e.started.prepare.evmFamilySigningKeySlotId,applicationBindingDigestB64u:s.applicationBindingDigestB64u,runRelayerRound:async a=>{let o=ht({registrationRequestDigestB64u:s.registrationRequestDigestB64u,proofTranscriptDigestB64u:s.proofTranscriptDigestB64u,contextBinding32B64u:a.contextBinding32B64u,derivationClientSharePublicKey33B64u:a.clientSharePublicKey33B64u,clientShareRetryCounter:a.clientShareRetryCounter,participantId:1}),c=await Vc({addSignerCeremonyId:r,activationCorrelationId:i,publicFacts:o}),u={bytes:Array.from(R(String(c.requestDigest)))},d=await e.context.signingEngine.persistInitialCanonicalEcdsaActivation({kind:`persist_initial_canonical_ecdsa_activation_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientActivation:o,planInput:{authority:e.authority,targetMemberships:[t,...n],evmFamilySigningKeySlotId:Gt(e.started.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:ln(e.started.prepare.ecdsaThresholdKeyId),signingRootId:ot(e.started.prepare.signingRootId),signingRootVersion:mt(e.started.prepare.signingRootVersion),runtimePolicyScope:e.started.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:sn(a.clientSharePublicKey33B64u),participantIds:[Dt(e.started.prepare.participantIds[0]),Dt(e.started.prepare.participantIds[1])],relayerKeyId:cn(e.started.prepare.relayerKeyId),bindingDigest:pn(a.contextBinding32B64u),journalId:i,requestDigest:c.requestDigest,canonicalRequest:c.canonicalRequest,createdAt:ye(new Date().toISOString())}});if(!d.ok)throw Error(`Canonical ECDSA activation persistence failed (${d.code}): ${d.message}`);l.journalId=d.journalId,l.response=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Hc.bind(void 0,{relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:r,activationCorrelationId:i,publicFacts:o,expectedActivationRequestDigest:u})});let f=l.response.ecdsa.activation.ecdsa_activation.public_identity;return JSON.stringify({relayerKeyId:e.started.prepare.relayerKeyId,relayerPublicKey33B64u:f.server_public_key33_b64u,groupPublicKey33B64u:f.threshold_public_key33_b64u,ethereumAddress:Mc(f.ethereum_address20_b64u),relayerShareRetryCounter:f.server_share_retry_counter})}});if(!l.response||!l.journalId)throw Error(`Add-signer ECDSA custody join did not activate`);let d=l.response,f=l.journalId,p=u.commitPayload.clientRootPublicKey33B64u;if(!p)throw Error(`Add-signer ECDSA custody join returned no client root public key`);let m=Bc({prepare:e.started.prepare,verified:u.clientBootstrap}),h=Gn({clientBootstrap:m,serverBootstrap:d.ecdsa.bootstrap,activationEpoch:d.ecdsa.activation.ecdsa_activation.activation_epoch});return{chainTargets:[t,...n],clientBootstrap:m,bootstrap:h,activatedThresholdSessionId:d.ecdsa.bootstrap.thresholdSessionId,journalId:f,activationReceipt:d.ecdsa.activation,custodyKeySet:{kind:`evm_family_ecdsa_v1`,keyManifestDigestB64u:u.commitPayload.keyManifestDigestB64u,clientRootPublicKey33B64u:p},custodyLocalMaterial:u.localMaterial}}catch(t){throw await zc({context:e.context,ceremonyId:r}),t}}async function Gc(e){let t=await e.context.signingEngine.finalizeRouterAbEcdsaRegistrationActivation({kind:`finalize_router_ab_ecdsa_registration_activation_v1`,bootstrapOwner:`wallet_custody`,journalId:e.pending.journalId,activationReceipt:e.pending.activationReceipt,routerAbEcdsaDerivationNormalSigning:e.pending.bootstrap.routerAbEcdsaDerivationNormalSigning,readyStateBlobB64u:e.pending.custodyLocalMaterial.readyStateBlobB64u,walletCustodyPublicFacts:e.pending.custodyLocalMaterial.publicFacts});return{chainTargets:e.pending.chainTargets,authority:t.authority,clientBootstrap:e.pending.clientBootstrap,bootstrap:e.pending.bootstrap,activatedThresholdSessionId:e.pending.activatedThresholdSessionId,roleLocalMaterial:t.roleLocalMaterial,materialActivation:t.materialActivation,clientPublicFacts:t.publicFacts,publicCapability:t.publicCapability}}function Kc(e){switch(e.tokens.kind){case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:return e.tokens.ecdsa;case`near_ed25519`:throw Error(`Registration-established session is missing ECDSA authorization`);default:return q(e.tokens)}}function qc(e){let[t]=e.walletKeys;if(!t)throw Error(`ECDSA registration did not return wallet key material`);let n=Kc(e.session.registrationEstablishedSession);if(String(e.session.registrationEstablishedSession.walletId)!==t.walletId||n.thresholdSessionId!==e.session.activatedThresholdSessionId||n.keyHandle!==t.keyHandle||!Jc(n.runtimePolicyScope,e.session.clientBootstrap.runtimePolicyScope)||!yt(n.routerAbEcdsaDerivationNormalSigning,e.session.bootstrap.routerAbEcdsaDerivationNormalSigning))throw Error(`Registration-established ECDSA session changed the signer identity`);for(let r of e.walletKeys)if(r.walletId!==t.walletId||r.keyHandle!==n.keyHandle||r.ecdsaThresholdKeyId!==t.ecdsaThresholdKeyId)throw Error(`ECDSA registration material changed the established session identity`)}function Jc(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}async function Yc(e,t){e.kind===`passkey`&&await Promise.allSettled([Promise.resolve().then(t),ua.initializeBundled()])}function Xc(e){return ft({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:String(e.credential.rawId||e.credential.id||``).trim()})}async function Zc(e){if(!e.material)throw Error(`Email OTP registration ${e.operation} is missing enrollment material`);return await e.material}function Qc(e){let t=e.admissionRequest,n=s(t.scope.threshold_session_id);if(!n.ok)throw Error(`Ed25519 registration threshold-session identity is invalid`);let r=t.participant_ids,i=I(e.finalized.runtimePolicyScope);if(t.application_binding.wallet_id!==e.walletId||t.application_binding.near_ed25519_signing_key_id!==e.finalized.nearEd25519SigningKeyId||t.application_binding.key_creation_signer_slot!==e.finalized.signerSlot||r[0]!==e.finalized.participantIds[0]||r[1]!==e.finalized.participantIds[1]||!Jc(i,e.expectedRuntimePolicyScope)||t.application_binding.signing_root_id!==`${i.projectId}:${i.envId}`||t.scope.root_share_epoch!==i.signingRootVersion||t.scope.signing_worker_id!==e.finalized.routerAbNormalSigning.signingWorkerId||e.finalized.relayerKeyId!==e.finalized.routerAbNormalSigning.signingWorkerId)throw Error(`Ed25519 registration material changed the admitted signer identity`);return{identity:{walletId:String(e.walletId),nearAccountId:e.finalized.nearAccountId,nearEd25519SigningKeyId:e.finalized.nearEd25519SigningKeyId,thresholdSessionId:n.value,signerSlot:e.finalized.signerSlot,signingRootId:t.application_binding.signing_root_id,signingRootVersion:t.scope.root_share_epoch,signingWorkerId:t.scope.signing_worker_id},stableServerScope:{relayerKeyId:e.finalized.relayerKeyId,participantIds:e.finalized.participantIds,runtimePolicyScope:i,routerAbNormalSigning:e.finalized.routerAbNormalSigning}}}function $c(e){switch(e.tokens.kind){case`near_ed25519`:case`near_ed25519_and_evm_family_ecdsa`:return e.tokens.ed25519;case`evm_family_ecdsa`:throw Error(`Registration-established session is missing Ed25519 authorization`);default:return q(e.tokens)}}async function el(e){let t=$c(e.registrationEstablishedSession);if(t.nearAccountId!==String(e.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.nearEd25519SigningKeyId)||t.thresholdSessionId!==String(e.thresholdSessionId)||!Jc(t.runtimePolicyScope,e.runtimePolicyScope))throw Error(`Registration-established Email OTP Ed25519 session changed signer identity`);let n=re(t.runtimePolicyScope),r=n.signingRootVersion;if(!r)throw Error(`Registration-established Ed25519 session is missing a signing-root version`);let i=ho({walletId:String(e.walletId),nearAccountId:String(e.nearAccountId),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId),walletSessionId:String(e.registrationEstablishedSession.walletSessionId),authorizationId:String(e.registrationEstablishedSession.authorizationId),quotaId:String(e.registrationEstablishedSession.quotaId),thresholdSessionId:t.thresholdSessionId,remainingUses:e.registrationEstablishedSession.remainingUses,expiresAtMs:e.registrationEstablishedSession.expiresAtMs,runtimePolicyScope:t.runtimePolicyScope,signingRootId:n.signingRootId,signingRootVersion:r,routerAbNormalSigning:t.routerAbNormalSigning,walletSessionToken:e.registrationEstablishedSession.operationCredential.token,home:e.registrationEstablishedSession.operationCredential.home,nowMs:Date.now()});if(!i.ok)throw Error(`Registration-established Email OTP Ed25519 session is unusable (${i.reason})`);let a=await ct({authority:e.emailOtpAuthContext.authority});return bc({walletId:e.walletId,nearAccountId:z(e.nearAccountId),nearEd25519SigningKeyId:Jt(e.nearEd25519SigningKeyId),providerSubjectId:sr(e.emailOtpAuthContext),signerSlot:e.signerSlot,relayerUrl:e.relayerUrl,authority:a,signingWalletSession:i.value})}function tl(e){if(e.authMethod.kind!==`passkey`)throw Error(`Ed25519 Yao registration requires a passkey registration intent`);return{version:e.version,walletId:e.walletId,authMethod:e.authMethod,signerSelection:e.signerSelection,foundingWalletAuthMethodId:e.foundingWalletAuthMethodId,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},nonceB64u:e.nonceB64u}}function nl(e){if(e.finalized.authMethod.kind!==`passkey`||e.finalized.rpId!==e.expectedRpId)throw Error(`Ed25519 Yao finalize returned a different passkey authority`);if(e.finalized.walletId!==e.expectedWalletId)throw Error(`Ed25519 Yao finalize returned a different wallet`);if(e.finalized.ed25519.publicKey!==e.clientPublicKey||e.finalized.ed25519.nearEd25519SigningKeyId!==e.finalized.resolvedAccount.nearEd25519SigningKeyId||e.finalized.ed25519.nearAccountId!==e.finalized.resolvedAccount.nearAccountId)throw Error(`Ed25519 Yao finalize returned mismatched signer identity`);return{rpId:e.finalized.rpId,credentialIdB64u:e.finalized.authMethod.credentialIdB64u}}function rl(e){if(e.finalized.authMethod.kind!==`email_otp`||e.finalized.authMethod.registrationAuthorityId!==e.expectedRegistrationAuthorityId)throw Error(`Ed25519 Yao finalize returned a different Email OTP authority`);if(e.finalized.walletId!==e.expectedWalletId)throw Error(`Ed25519 Yao finalize returned a different wallet`);if(e.finalized.ed25519.publicKey!==e.clientPublicKey||e.finalized.ed25519.nearEd25519SigningKeyId!==e.finalized.resolvedAccount.nearEd25519SigningKeyId||e.finalized.ed25519.nearAccountId!==e.finalized.resolvedAccount.nearAccountId)throw Error(`Ed25519 Yao finalize returned mismatched signer identity`)}async function il(e,t){let n=await new ra(t).send({kind:`admit`,path:At,body:e.admissionRequest});if(!n.ok)throw Error(n.message);let r=Rt(n.value);if(!r.ok)throw Error(r.message);return r.value}function al(e){let t=$c(e.session);return{thresholdSessionId:String(t.thresholdSessionId),prfFirstB64u:e.prfFirstB64u,expiresAtMs:e.session.expiresAtMs,remainingUses:e.session.remainingUses,diagnostics:{recordDuration:Ta.bind(void 0,e.ceremonyId)},...e.preparedServerSeal?{preparedServerSeal:e.preparedServerSeal}:{},transport:{curve:`ed25519`,authMethod:`passkey`,walletId:e.walletId,relayerUrl:e.relayerUrl,walletSessionToken:e.session.operationCredential.token,ed25519Restore:_a({rpId:e.restore.rpId,nearAccountId:e.restore.nearAccountId,nearEd25519SigningKeyId:e.restore.nearEd25519SigningKeyId,relayerKeyId:e.restore.relayerKeyId,participantIds:e.restore.participantIds,runtimePolicyScope:t.runtimePolicyScope,signerSlot:e.restore.signerSlot,routerAbNormalSigning:t.routerAbNormalSigning,credentialIdB64u:e.restore.credentialIdB64u,materialActivation:e.restore.materialActivation})}}}function ol(e){if(e.operation!==`registration_activate`||e.signerPlanKind!==`evm_family_ecdsa`)return!1;let t=e.localMaterial.keyFamilies;return t.length===1&&t[0]===`ecdsa_secp256k1`}function sl(e){if(e.operation!==`registration_activate`||e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)return!1;let t=e.localMaterial.keyFamilies;return t.length===1&&t[0]===`ecdsa_secp256k1`}function cl(e){let t=e.registrationEstablishedSession.session.tokens;if(t.kind===`evm_family_ecdsa`||t.kind===`near_ed25519_and_evm_family_ecdsa`)return t;throw Error(`pending ECDSA activation returned no ECDSA projection`)}function ll(e,t,n){let r=t.registrationEstablishedSession.session,i=cl(t);return t.walletId===e.walletId&&t.custodyKeyManifestDigestB64u===e.localMaterial.custodyCommit.keyManifestDigestB64u&&t.walletCustody?.status===`committed`&&r.walletId===e.walletId&&r.walletSession.walletId===e.walletId&&r.walletSession.authMethodId===e.walletAuthMethodId&&r.tokens.kind===`evm_family_ecdsa`&&i.ecdsa.keyHandle===n.keyHandle&&i.ecdsa.thresholdSessionId===t.ecdsa.bootstrap.thresholdSessionId&&r.expiresAtMs===t.ecdsa.bootstrap.expiresAtMs&&r.remainingUses===t.ecdsa.bootstrap.remainingUses}function ul(e,t,n){let r=e.ecdsa_activation.public_identity;return kt({registrationRequestDigestB64u:t.publicCapability.registration_request_digest_b64u,proofTranscriptDigestB64u:L(Uint8Array.from(e.transcript_digest.bytes)),contextBinding32B64u:r.context_binding_b64u,derivationClientSharePublicKey33B64u:r.derivation_client_share_public_key33_b64u,clientShareRetryCounter:r.client_share_retry_counter,participantId:1},n)}function dl(e,t){return e.derivationClientSharePublicKey33B64u===t.derivationClientSharePublicKey33B64u&&e.relayerPublicKey33B64u===t.relayerVerifyingShareB64u&&e.groupPublicKey33B64u===t.thresholdEcdsaPublicKeyB64u&&e.ethereumAddress===t.thresholdOwnerAddress.toLowerCase()}function fl(e,t){return e.server_public_key33_b64u===t.relayerVerifyingShareB64u&&e.threshold_public_key33_b64u===t.thresholdEcdsaPublicKeyB64u&&gl(e.ethereum_address20_b64u)===t.thresholdOwnerAddress&&e.server_share_retry_counter===t.relayerShareRetryCounter}function pl(e,t){return e.walletId===t.walletId&&e.keyHandle===t.keyHandle&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&e.evmFamilySigningKeySlotId===t.evmFamilySigningKeySlotId&&e.signingRootId===t.signingRootId&&e.signingRootVersion===t.signingRootVersion&&e.thresholdEcdsaPublicKeyB64u===t.thresholdEcdsaPublicKeyB64u&&e.ethereumAddress.toLowerCase()===t.thresholdOwnerAddress.toLowerCase()&&e.relayerKeyId===t.relayerKeyId&&e.relayerVerifyingShareB64u===t.relayerVerifyingShareB64u&&e.clientShareRetryCounter===t.clientShareRetryCounter&&e.relayerShareRetryCounter===t.relayerShareRetryCounter}function ml(e,t){let n={relayerUrl:e,registrationCeremonyId:t.registrationCeremonyId,signedSetup:t.signedSetup,idempotencyKey:t.idempotencyKey,walletCustodyCommit:t.localMaterial.custodyCommit,...t.auth.kind===`email_otp`?{emailOtpEnrollment:t.auth.enrollment}:{}},r={activationCorrelationId:t.localMaterial.ecdsa.activationJournalId,activationRequestDigestB64u:t.localMaterial.ecdsa.activationRequestDigestB64u,clientActivation:t.localMaterial.ecdsa.clientActivation};return{...n,signerPlanKind:t.signerPlanKind,ecdsa:r}}function hl(e){let t=e.ecdsa.walletKeys[0];if(!t)throw Error(`pending ECDSA activation returned no wallet keys`);return Fc(e.ecdsa.walletKeys),[t,...e.ecdsa.walletKeys.slice(1)]}function gl(e){let t=R(e);if(t.length!==20)throw Error(`pending ECDSA activation returned an invalid address`);let n=`0x`;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n}function _l(e,t,n){if(!ll(e,t,n))throw Error(`pending ECDSA activation projection mismatch`);Cn(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function vl(e){return e.ok===!0&&e.kind===`evm_family_ecdsa`&&e.registrationEstablishedSession.kind===`already_committed`}async function yl(e,t){if(e.auth.kind===`passkey`){if(t.authMethod.kind!==`passkey`||t.rpId!==e.auth.rpId||t.authMethod.credentialIdB64u!==e.auth.credentialIdB64u)throw Error(`pending ECDSA activation returned a different Passkey method`);return}if(t.authMethod.kind!==`email_otp`||t.authMethod.registrationAuthorityId!==e.auth.registrationAuthorityId)throw Error(`pending ECDSA activation returned a different Email OTP method`);let n=lt(t.authority),r=await S(e.auth.email);if(!n||n.factor.providerUserId!==e.auth.providerSubject||n.verifier.emailHashHex.toLowerCase()!==r.toLowerCase())throw Error(`pending ECDSA activation returned a different Email OTP identity`)}function bl(e,t,n){let r=t.ecdsa.activation,i=r.ecdsa_activation,a=i.public_identity,o=e.localMaterial.ecdsa.clientActivation;if(r.activation_correlation_id!==e.localMaterial.ecdsa.activationJournalId||L(Uint8Array.from(r.activation_request_digest.bytes))!==e.localMaterial.ecdsa.activationRequestDigestB64u||!ul(r,n,o)||!dl(t.ecdsa.bootstrap.publicIdentity,n)||i.context.application_binding_digest_b64u!==t.ecdsa.bootstrap.applicationBindingDigestB64u||!fl(a,n))throw Error(`pending ECDSA activation facts mismatch`);if(!pl(t.ecdsa.bootstrap,n))throw Error(`pending ECDSA bootstrap changed committed key identity`)}function xl(e){let t=cl(e).ecdsa,n=e.ecdsa.activation.ecdsa_activation;if(!p(t.materialActivation,gt(n.material_activation))||!yt(t.routerAbEcdsaDerivationNormalSigning,e.ecdsa.bootstrap.routerAbEcdsaDerivationNormalSigning))throw Error(`pending ECDSA activation facts do not match the committed projection`)}async function Sl(e){let t=e.response;if(!vl(t))throw Error(t.ok?`pending ECDSA activation replay did not return a committed projection`:`pending ECDSA activation replay failed`);let n=hl(t)[0];if(_l(e.pending,t,n),await yl(e.pending,t),bl(e.pending,t,n),xl(t),e.pending.signerPlanKind===`evm_family_ecdsa`){if(t.nearProvisioning!==void 0)throw Error(`ECDSA-only registration unexpectedly has deferred NEAR provisioning`)}else if(t.nearProvisioning?.status!==`near_pending`)throw Error(`mixed registration did not retain deferred NEAR provisioning`);return t}function Cl(e){return String(Ln(e)||``).trim()}function wl(e,t){let n=Cl(e);if(!n)throw Error(`${t} requires PRF.first output from the passkey credential`);return n}function Tl(e){return String(e?.rawId||e?.id||``).trim()}async function El(e){let t=new xn,n=gt(e.activationReceipt.ecdsa_activation.material_activation),r=await t.lookupByMaterialActivation({walletId:e.authority.walletId,authority:e.authority,materialActivation:n});if(r.kind===`missing`){let t=await Sn(e);return{roleLocalMaterialRef:t.roleLocalMaterialRef,publication:[t]}}if(r.kind!==`active`)throw Error(`Pending ECDSA registration continuity is ${r.kind}`);let i=r.manifest,a=i.durableMaterial;if(!Et(i.activation.serverActivation.serverActivationReceipt.protocolReceipt,e.activationReceipt)||!vt(a.roleLocalPublicFacts.publicCapability,e.publicCapability)||!Nn(i.signer.scope,fn({targetMemberships:e.chainTargets}))||a.roleLocalBinding.keyHandle!==e.keyHandle||a.roleLocalBinding.ecdsaThresholdKeyId!==e.ecdsaThresholdKeyId||a.roleLocalBinding.relayerKeyId!==e.relayerKeyId||a.bindingDigest!==e.publicFacts.contextBinding32B64u||i.signer.signingRootId!==e.signingRootId||i.signer.signingRootVersion!==e.signingRootVersion||!Mn(a.runtimePolicyScope,e.runtimePolicyScope))throw Error(`Pending ECDSA registration conflicts with its restored activation`);return{roleLocalMaterialRef:{kind:`ecdsa_role_local_persisted_material_ref_v1`,durableMaterialRef:a.durableMaterialRef,bindingDigest:a.bindingDigest,materialActivation:n},publication:[]}}function Dl(e){let t=e[0];if(!t)throw Error(`ECDSA registration finalization returned no wallet keys`);return[t,...e.slice(1)]}function Ol(e){let t=e[0];if(!t)throw Error(`ECDSA registration activation returned no chain targets`);return[t.chainTarget,...e.slice(1).map(e=>e.chainTarget)]}async function kl(e){let t=Dl(e.walletKeys);if(e.pending.auth.kind===`passkey`){if(e.response.authMethod.kind!==`passkey`||!e.response.authMethod.credentialPublicKeyB64u)throw Error(`ECDSA registration publication has no exact Passkey credential`);return await nt({kind:`passkey`,walletId:e.pending.walletId,rpId:e.pending.auth.rpId,credentialIdB64u:e.pending.auth.credentialIdB64u,credentialPublicKeyB64u:e.response.authMethod.credentialPublicKeyB64u,transports:e.pending.auth.transports,walletKeys:t})}if(e.response.authMethod.kind!==`email_otp`)throw Error(`ECDSA Email OTP registration publication has a different auth method`);let n=lt(e.response.authority);if(!n)throw Error(`ECDSA Email OTP registration authority is invalid`);return await nt({kind:`email_otp`,walletId:e.pending.walletId,email:e.pending.auth.email,registrationAuthorityId:e.pending.auth.registrationAuthorityId,authority:n,walletKeys:t})}function Al(e){return{pending:e.pending,authority:e.response.authority,foundingAuthority:{authority:e.response.foundingAuthority,authMethod:e.response.foundingAuthMethod},request:{operation:e.pending.operation,registrationCeremonyId:e.pending.registrationCeremonyId,idempotencyKey:e.pending.idempotencyKey,walletId:e.pending.walletId,walletAuthMethodId:e.pending.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:e.session.session.wallet_session,operationCredential:e.session.session.operation_credential},ecdsaContinuity:e.ecdsaContinuity,registration:e.registration}}async function jl(e){let t=await e.ports.activateWalletRegistration(ml(e.relayerUrl,e.pending)),n=await Sl({pending:e.pending,response:t}),r=hl(n),i={sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,relayerUrl:e.relayerUrl,pending:e.pending,response:n,walletKeys:r,exactMethod:e.exactMethod,signingSurface:e.signingSurface},a=await e.ports.unlockPendingEcdsaRegistration(i),o=r[0];if(!o)throw Error(`ECDSA registration activation returned no primary key`);let s=await ct({authority:n.authority}),c=await El({authority:s,chainTargets:Ol(r),walletId:String(e.pending.walletId),keyHandle:o.keyHandle,ecdsaThresholdKeyId:o.ecdsaThresholdKeyId,signingRootId:o.signingRootId,signingRootVersion:o.signingRootVersion,relayerKeyId:o.relayerKeyId,participantIds:o.participantIds,publicCapability:o.publicCapability,activationReceipt:n.ecdsa.activation,runtimePolicyScope:cl(n).ecdsa.runtimePolicyScope,readyStateBlobB64u:a.readyStateBlobB64u,publicFacts:a.publicFacts}),l={kind:`ecdsa_role_local_worker_handle_v1`,materialHandle:un(c.roleLocalMaterialRef.durableMaterialRef),bindingDigest:c.roleLocalMaterialRef.bindingDigest,durableMaterialRef:c.roleLocalMaterialRef.durableMaterialRef},u=await e.signingSurface.finalizeWalletRegistrationEcdsaSessions({walletId:String(e.pending.walletId),session:{chainTargets:Ol(r),authority:s,bootstrap:{applicationBindingDigestB64u:n.ecdsa.bootstrap.applicationBindingDigestB64u},roleLocalMaterial:l,materialActivation:c.roleLocalMaterialRef.materialActivation,clientPublicFacts:{contextBinding32B64u:a.publicFacts.contextBinding32B64u,derivationClientSharePublicKey33B64u:a.publicFacts.derivationClientSharePublicKey33B64u,clientVerifyingShareB64u:a.publicFacts.clientVerifyingShare33B64u,relayerPublicKey33B64u:a.publicFacts.relayerPublicKey33B64u,groupPublicKey33B64u:a.publicFacts.groupPublicKey33B64u,ethereumAddress:a.publicFacts.ethereumAddress},publicCapability:o.publicCapability},walletKeys:r}),d=await kl({pending:e.pending,response:n,walletKeys:u});if(await e.ports.publishPendingWalletRegistrationCommit(Al({pending:e.pending,response:n,registration:d,session:a.session,ecdsaContinuity:c.publication})),e.pending.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&e.pending.auth.kind===`passkey`&&a.kind===`passkey`){let t=wl(a.credential,`Pending NEAR registration continuation`),n=xh({context:e.nearContext,sessionAuthority:{record:a.session.session.wallet_session,operationCredential:a.session.session.operation_credential},factor:{kind:`passkey`,rpId:e.pending.auth.rpId,credentialIdB64u:Tl(a.credential),prfFirstB64u:t},ownedFactorSecret:R(t).slice().buffer,custodyEnvelope:a.custody.envelope});e.nearCompletion===`await`&&await n}return{kind:`published`,registrationCeremonyId:e.pending.registrationCeremonyId,walletId:n.walletId,signingSession:{sessionId:String(a.session.session.threshold_session_id),status:`active`,authMethod:a.kind,remainingUses:a.session.session.remaining_uses,expiresAtMs:a.session.session.expires_at_ms}}}function Ml(e,t,n){e?.(mn({flowId:`unlock:${t}`,accountId:t,...n}))}async function Nl(e){let{context:t,authMethod:n,unlockSubjectId:r,loginResult:i,onEvent:a,afterCall:o}=e;return i.success&&t.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:i.walletId,authMethod:n}),Ml(a,r,{phase:gn.STEP_07_COMPLETED,status:`succeeded`,data:{...i.success&&i.kind===`near_wallet_unlocked`?{operationalPublicKey:i.operationalPublicKey??``}:{walletId:i.success?String(i.walletId):``}}}),await o?.(!0,i),i}async function Pl(e){let{message:t,unlockSubjectId:n,error:r,onEvent:i,onError:a,afterCall:o,callOnError:s=!0,callAfterCall:c=!0,cancelled:l=!1}=e;return s&&a?.(Ce(r)),Ml(i,n,{phase:l?gn.CANCELLED:gn.FAILED,status:l?`cancelled`:`failed`,...l?{}:{message:t},interaction:{kind:`passkey_assert`,overlay:`hide`},error:{message:t}}),c&&await o?.(!1),{success:!1,error:t}}async function Fl(e){let t=An(),n=null;try{let r=JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:L(e)}))),i=await Ar({runStep:e.runStep,custody:e.factorAfterRouterRound?{origin:`establish_factor_after_round`,walletId:e.walletId,recoveryCodesJson:r,factor:e.factorAfterRouterRound}:{origin:`establish`,walletId:e.walletId,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:r},keySetRun:{keySet:`near_ed25519_v1`,protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],...e.continuityRegisteredPublicKeyB64u===void 0?{}:{continuityRegisteredPublicKeyB64u:e.continuityRegisteredPublicKeyB64u}}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async t=>{let r=await e.runRouterRound(t);return n=Yl(r),r}}});if(!n)throw Error(`the NEAR custody ceremony produced no activation session id`);let a=await Jl(i,t);return{recoveryCodes:t.codes,activationReference:{kind:`router_ab_ed25519_yao_activation_reference_v1`,lifecycle_id:e.registrationCeremonyId,session_id:n},commitPayload:ql(a),localMaterial:i.ed25519LocalMaterialB64u&&i.ed25519LocalMaterialNonceB64u&&i.ed25519ApplicationBindingDigestB64u?{b64u:i.ed25519LocalMaterialB64u,nonceB64u:i.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:i.ed25519ApplicationBindingDigestB64u}:null}}finally{t&&On(t),t=null}}function Il(e){let t=e.establishedCustody;if(!t)throw Error(`wallet custody join requires an established envelope`);let n;try{n=JSON.parse(t.envelopeBindingJson)}catch{throw Error(`wallet custody envelope binding is not JSON`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`wallet custody envelope binding must be an object`);return JSON.stringify({envelopeBinding:n,nonceB64u:t.envelopeNonceB64u,sealedCustodySecretB64u:t.sealedCustodySecretB64u,aadHashB64u:t.envelopeAadHashB64u,ciphertextDigestB64u:t.envelopeCiphertextDigestB64u})}async function Ll(e){let t=An(),n=null,r=null;try{let i=t;if(!i)throw Error(`recovery codes were not issued`);let a=await Ar({runStep:e.runStep,custody:{origin:`establish`,walletId:e.walletId,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:L(e)})))},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:e.confirmRecoveryCodesBackedUp.bind(void 0,t.codes),runRelayerRound:async t=>{let a=rn(await Jl(t.preActivationCommitPayload,i));return n=a,r={contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.clientSharePublicKey33B64u,clientShareRetryCounter:t.clientShareRetryCounter,participantId:1},await e.runRelayerRound({...t,preActivationCommitPayload:a})}}});if(!n||!r)throw Error(`the EVM custody ceremony reached no activation round`);if(!a.ecdsaReadyStateBlobB64u||!a.ecdsaPublicFacts)throw Error(`the EVM custody ceremony produced no local signing material`);return{recoveryCodes:t.codes,commitPayload:n,clientBootstrap:r,localMaterial:{readyStateBlobB64u:a.ecdsaReadyStateBlobB64u,publicFacts:a.ecdsaPublicFacts}}}finally{t&&On(t),t=null}}async function Rl(e){let t=null,n=null,r=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:async r=>(t=r.preActivationCommitPayload,n={contextBinding32B64u:r.contextBinding32B64u,derivationClientSharePublicKey33B64u:r.clientSharePublicKey33B64u,clientShareRetryCounter:r.clientShareRetryCounter,participantId:1},await e.runRelayerRound(r))}});if(!t||!n)throw Error(`the EVM custody join reached no activation round`);if(r.establishedCustody)throw Error(`an EVM custody join must not establish a second wallet seed`);if(!r.ecdsaReadyStateBlobB64u||!r.ecdsaPublicFacts)throw Error(`the EVM custody join produced no local signing material`);return{commitPayload:t,clientBootstrap:n,localMaterial:{readyStateBlobB64u:r.ecdsaReadyStateBlobB64u,publicFacts:r.ecdsaPublicFacts}}}function zl(e){switch(e.factorReplacement.kind){case`preserve_existing`:return{origin:`recover`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode};case`reseal_replacement_factor`:return{origin:`recover_and_reseal`,custodyJson:e.custodyJson,recoveryCode:e.recoveryCode,replacementFactorJson:e.factorReplacement.factorJson,replacementFactorSecret:e.factorReplacement.factorSecret};default:return Bl(e.factorReplacement)}}function Bl(e){throw Error(`unsupported recovery factor replacement: ${String(e)}`)}async function Vl(e){if(await Gl({walletId:e.walletId,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,clientRootPublicKey33B64u:e.registeredClientRootPublicKey33B64u})!==e.recordedKeyManifestDigestB64u)throw Error(`EVM recovery manifest digest does not match the registered identity`);let t=await Ar({runStep:e.runStep,custody:zl(e),keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:e.resolveRelayerPublicIdentity},recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});if(!t.ecdsaReadyStateBlobB64u||!t.ecdsaPublicFacts)throw Error(`the EVM recovery produced no local signing material`);if(t.clientRootPublicKey33B64u!==e.registeredClientRootPublicKey33B64u)throw Error(`the EVM recovery changed the registered client root public key`);return{readyStateBlobB64u:t.ecdsaReadyStateBlobB64u,publicFacts:t.ecdsaPublicFacts,recoveryReplacementEnvelope:t.recoveryReplacementEnvelope??null}}async function Hl(e){let t=await Gl({walletId:e.walletId,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,clientRootPublicKey33B64u:e.registeredClientRootPublicKey33B64u}),n=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`evm_family_ecdsa_v1`,protocolInputsJson:JSON.stringify({applicationBindingDigestB64u:e.applicationBindingDigestB64u}),evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,beforeRelayerRound:async()=>void 0,runRelayerRound:async()=>e.relayerPublicIdentityJson},recordedKeyManifestDigestB64u:t});if(n.establishedCustody)throw Error(`an EVM cold unlock must not establish custody`);if(!n.ecdsaReadyStateBlobB64u||!n.ecdsaPublicFacts)throw Error(`the EVM cold unlock produced no local signing material`);return{readyStateBlobB64u:n.ecdsaReadyStateBlobB64u,publicFacts:n.ecdsaPublicFacts}}function Ul(e,t){e.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255)}function Wl(e,t,n){let r=new TextEncoder().encode(t);Ul(e,r.length),e.push(...r),Ul(e,n.length),e.push(...n)}async function Gl(e){let t=String(e.walletId||``).trim(),n=String(e.evmFamilySigningKeySlotId||``).trim(),r=R(e.clientRootPublicKey33B64u);if(!t||!n||r.length!==33)throw Error(`EVM custody continuity identity is invalid`);let i=[];return Wl(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/evm-family-ecdsa/v1`)),Wl(i,`walletId`,new TextEncoder().encode(t)),Wl(i,`evmFamilySigningKeySlotId`,new TextEncoder().encode(n)),Wl(i,`clientRootPublicKey33`,r),L(await D(Uint8Array.from(i)))}async function Kl(e){let t=String(e.walletId||``).trim(),n=String(e.nearEd25519SigningKeyId||``).trim(),r=R(e.registeredPublicKeyB64u);if(!t||!n||r.length!==32)throw Error(`NEAR custody continuity identity is invalid`);let i=[];return Wl(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/near-ed25519/v1`)),Wl(i,`walletId`,new TextEncoder().encode(t)),Wl(i,`nearEd25519SigningKeyId`,new TextEncoder().encode(n)),Wl(i,`registeredPublicKey`,r),L(await D(Uint8Array.from(i)))}function ql(e){let{ed25519LocalMaterialB64u:t,ed25519LocalMaterialNonceB64u:n,ed25519ApplicationBindingDigestB64u:r,ecdsaReadyStateBlobB64u:i,recoveryReplacementEnvelope:a,...o}=e;return o}async function Jl(e,t){let n=e.establishedCustody;if(!n)return e;if(n.recoveryManifestKekWraps.length!==t.codeBytes.length)throw Error(`recovery code and wrap counts do not match`);let r=await Promise.all(t.codeBytes.map(async(e,t)=>{let r=n.recoveryManifestKekWraps[t];if(!r)throw Error(`recovery code and wrap counts do not match`);return{locatorB64u:await kn(e),recoveryKeyId:r.recoveryKeyId}}));if(new Set(r.map(e=>e.locatorB64u)).size!==r.length)throw Error(`recovery code locators must be unique`);return{...e,establishedCustody:{...n,recoveryCodeLocators:r}}}function Yl(e){let t;try{t=JSON.parse(e)}catch{throw Error(`the Router activation result is not JSON`)}let n=t?.binding?.session_id;if(!Array.isArray(n)||n.length===0)throw Error(`the Router activation result carries no session id`);return n.map(e=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`the Router activation session id is not a byte array`);return e})}async function Xl(e){if(await Kl({walletId:e.walletId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,registeredPublicKeyB64u:e.registeredPublicKeyB64u})!==e.recordedKeyManifestDigestB64u)throw Error(`NEAR recovery manifest digest does not match the registered identity`);let t=null,n=null,r=await Ar({runStep:e.runStep,custody:zl(e),keySetRun:{keySet:`near_ed25519_v1`,protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],continuityRegisteredPublicKeyB64u:e.registeredPublicKeyB64u}),nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async n=>(t=await e.runRouterRound(n),t),afterRouterRoundCompleted:async t=>{n=await e.activateRouterRecovery(t)}},recordedKeyManifestDigestB64u:e.recordedKeyManifestDigestB64u});if(!r.ed25519LocalMaterialB64u||!r.ed25519LocalMaterialNonceB64u)throw Error(`the NEAR recovery sealed no local signing material`);if(!r.ed25519ApplicationBindingDigestB64u)throw Error(`the NEAR recovery omitted its application binding digest`);if(!t||!n)throw Error(`the NEAR recovery produced no Router activation`);return{localMaterial:{b64u:r.ed25519LocalMaterialB64u,nonceB64u:r.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:r.ed25519ApplicationBindingDigestB64u},activationResultJson:t,activationReceipt:n,recoveryReplacementEnvelope:r.recoveryReplacementEnvelope??null}}async function Zl(e){return await $l(e,e.registrationCeremonyId,void 0,`registration join`)}async function Ql(e){let t=String(e.registeredPublicKeyB64u||``).trim();if(!t)throw Error(`a cold unlock must name the key set it reproduces`);let n=null,r=null,i=await $l({...e,preparation:{kind:`fresh`}},e.recoveryLifecycleId,t,`cold unlock`,async t=>{n=t,r=await e.activateRouterRecovery(t)});if(!n||!r)throw Error(`the NEAR cold unlock produced no Router recovery activation`);return{...i,activationResultJson:n,activationReceipt:r}}async function $l(e,t,n,r,i){let a=null,o=await Ar({runStep:e.runStep,custody:{origin:`join`,custodyJson:e.custodyJson,factorSecret:e.factorSecret},keySetRun:{keySet:`near_ed25519_v1`,...e.preparation.kind===`checkpoint`?{checkpointJson:e.preparation.checkpointJson}:{protocolInputsJson:JSON.stringify({yaoAdmission:e.yaoAdmission,yaoApplication:e.yaoApplication,clientParticipantId:e.participantIds[0],signingWorkerParticipantId:e.participantIds[1],...n?{continuityRegisteredPublicKeyB64u:n}:{}}),beforeRouterRound:e.beforeRouterRound},nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,runRouterRound:async t=>{let n=await e.runRouterRound(t);return a=Yl(n),n},...i?{afterRouterRoundCompleted:i}:{}}});if(!a)throw Error(`the NEAR ${r} produced no activation session id`);if(o.establishedCustody)throw Error(`a NEAR ${r} must not establish custody`);if(!o.ed25519LocalMaterialB64u||!o.ed25519LocalMaterialNonceB64u)throw Error(`the NEAR ${r} sealed no local material`);return{commitPayload:ql(o),activationReference:{kind:`router_ab_ed25519_yao_activation_reference_v1`,lifecycle_id:t,session_id:a},localMaterial:{b64u:o.ed25519LocalMaterialB64u,nonceB64u:o.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:String(o.ed25519ApplicationBindingDigestB64u||``)}}}function eu(e){switch(e.routeFamily){case`operation_step_up`:return{routeFamily:e.routeFamily,operation:e.operation,operationCredential:e.operationCredential};case`registration`:if(e.operation!==`registration`)throw Error(`Email OTP registration routes require registration operation`);return{routeFamily:`registration`,operation:e.operation};case`login`:if(!Ue(e.operation))throw Error(`Email OTP login routes require a login operation`);return{routeFamily:`login`,operation:e.operation};case`signing_session`:if(e.operation!==`transaction_sign`&&e.operation!==`export_key`)throw Error(`Email OTP signing-session routes require signing or export operation`);return{routeFamily:`signing_session`,authLane:e.authLane,operation:e.operation}}throw Error(`Unsupported Email OTP route family`)}var tu=class e extends Error{kind=`email_otp_signing_session_auth_state_error`;failure;constructor(t){super(nu(t)),this.name=`EmailOtpSigningSessionAuthStateError`,this.failure=t,Object.setPrototypeOf(this,e.prototype)}};function nu(e){return`Email OTP ${e.expectedCurve} signing-session auth lane is unavailable at ${e.source}; unlock wallet again`}function ru(e){throw new tu(e)}function iu(e){return e.freshRouteFamily===`registration`?eu({routeFamily:`registration`,operation:He}):eu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function au(e){return e?.kind!==`signing_session`&&ru({kind:`auth_lane_missing`,source:`route_plan`,expectedCurve:`unknown`}),e}function ou(e){return eu({routeFamily:`signing_session`,authLane:e.authLane,operation:e.operation})}function su(e){if(e.kind===`signing_session`&&e.curve===`ecdsa`)return{kind:`threshold_ecdsa_session`,operationCredential:e.operationCredential,curve:`ecdsa`,thresholdSessionId:e.thresholdSessionId,chainTarget:e.chainTarget}}function cu(e){if(e.routeFamily===`signing_session`)return su(e.authLane)}async function lu(e){return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`unlockEmailOtpAuthorityWallet`,timeoutMs:6e4,payload:{relayUrl:e.relayUrl,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,challengeId:e.challengeId,otpCode:e.otpCode,ed25519:e.ed25519}}})}async function uu(e){return await e.base.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`loginWithEmailOtpWallet`,timeoutMs:6e4,payload:{relayUrl:e.base.relayUrl,walletId:String(e.base.walletSession.walletId),authoritySelector:e.base.authoritySelector,userId:String(e.base.walletSession.walletSessionUserId),verification:e.base.verification,groupId:e.base.groupId,routePlan:e.base.routePlan,otpChannel:Ke,material:e.material},onEvent:e.base.onProgress}})}async function du(e){let t=await uu({base:e,material:e.ecdsaSessionPolicy?{kind:`ecdsa`,ecdsaSessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope,ecdsaSessionPolicy:e.ecdsaSessionPolicy}:{kind:`ecdsa`,ecdsaSessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope}});if(t.kind!==`ecdsa`)throw Error(`Email OTP wallet unlock returned the wrong material branch`);if(e.ecdsaSessionPolicy){if(t.operation!==`wallet_unlock`)throw Error(`Email OTP wallet unlock returned a non-unlock ECDSA result`);return{kind:`ecdsa`,operation:`wallet_unlock`,recovery:t.recovery,emailOtpSessionHandle:t.emailOtpSessionHandle,ecdsaSession:t.ecdsaSession,ecdsaCustody:t.ecdsaCustody}}if(t.operation!==e.ecdsaSessionHandleBinding.operation)throw Error(`Email OTP ECDSA result operation does not match its request`);return{kind:`ecdsa`,operation:t.operation,recovery:t.recovery,emailOtpSessionHandle:t.emailOtpSessionHandle}}async function fu(e){let t=await uu({base:e,material:{kind:`ed25519_yao_recovery`,providerSubject:e.providerSubject,nearAccountId:e.nearAccountId,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,walletCustodyEd25519Material:e.walletCustodyEd25519Material,ed25519YaoRecovery:{kind:Bt,signerSlot:e.signerSlot,remainingUses:e.remainingUses,orgId:e.orgId}}});if(t.kind===`ed25519_yao_capability`)return{kind:t.kind,recovery:t.recovery,activeClientHandle:t.activeClientHandle,metadata:t.metadata,ed25519YaoCapability:t.ed25519YaoCapability,walletSessionAuthorization:t.walletSessionAuthorization,...t.walletCustodyEd25519Material?{walletCustodyEd25519Material:t.walletCustodyEd25519Material}:{},ed25519ExportRootCustody:t.ed25519ExportRootCustody};if(t.kind!==`wallet_custody_cache_absent`)throw Error(`Email OTP Ed25519 Yao unlock returned the wrong material branch`);return{kind:`wallet_custody_cache_absent`,recovery:t.recovery,ed25519YaoRecovery:t.ed25519YaoRecovery}}async function pu(e){let t=await uu({base:e,material:{kind:`wallet_unlock_capabilities`,ecdsa:{sessionHandleBinding:e.ecdsaSessionHandleBinding,runtimePolicyScope:e.runtimePolicyScope,sessionPolicy:e.ecdsaSessionPolicy},ed25519Yao:{providerSubject:e.providerSubject,nearAccountId:e.nearAccountId,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,walletCustodyEd25519Material:e.walletCustodyEd25519Material,recovery:{kind:Bt,signerSlot:e.signerSlot,remainingUses:e.remainingUses,orgId:e.runtimePolicyScope.orgId}}}});if(t.kind!==`wallet_unlock_capabilities`)throw Error(`Email OTP capability unlock returned the wrong material branch`);return{kind:`wallet_unlock_capabilities`,recovery:t.recovery,walletSessionAuthorization:t.walletSessionAuthorization,ed25519ExportRootCustody:t.ed25519ExportRootCustody,ecdsa:{kind:`ecdsa`,operation:`wallet_unlock`,recovery:t.recovery,emailOtpSessionHandle:t.ecdsa.emailOtpSessionHandle,ecdsaSession:t.ecdsa.session,ecdsaCustody:t.ecdsa.custody},ed25519Yao:t.ed25519Yao.kind===`wallet_custody_cache_absent`?{kind:`wallet_custody_cache_absent`,recovery:t.recovery,ed25519YaoRecovery:t.ed25519Yao.bootstrap}:{kind:`ed25519_yao_capability`,recovery:t.recovery,activeClientHandle:t.ed25519Yao.activeClientHandle,metadata:t.ed25519Yao.metadata,ed25519YaoCapability:t.ed25519Yao.bootstrap,walletSessionAuthorization:t.walletSessionAuthorization,ed25519ExportRootCustody:t.ed25519ExportRootCustody}}}function mu(e){let t=e.walletSessionState.signingLane;if(t.auth.kind!==`passkey`)throw Error(`[SigningEngine][near] Passkey recovery returned another auth lane`);let n=t.identity.signer;return{walletId:n.account.wallet.walletId,nearAccountId:n.account.nearAccountId,thresholdSessionId:e.walletSessionState.thresholdSessionId,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,materialActivation:e.materialActivation,auth:{kind:`passkey`,rpId:t.auth.rpId,credentialIdB64u:t.auth.credentialIdB64u},nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}}function hu(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function gu(e){if(!Array.isArray(e)||e.length!==2||!Number.isSafeInteger(e[0])||!Number.isSafeInteger(e[1])||e[0]<1||e[1]<1||e[0]===e[1])throw Error(`participantIds must contain two distinct positive integers`);return[Number(e[0]),Number(e[1])]}function _u(e){return e.kind===`sign`&&e.keyFamily===`ed25519`}function vu(e,t,n,r,i,a){if(`sessionKind`in e||`walletSessionToken`in e)throw Error(`sync-account signer bootstrap must not carry a Wallet Session bearer`);if(T(e.walletId,`session.walletId`)!==n.walletId||T(e.nearAccountId,`session.nearAccountId`)!==n.nearAccountId||T(e.nearEd25519SigningKeyId,`session.nearEd25519SigningKeyId`)!==n.nearEd25519SigningKeyId)throw Error(`Yao recovery session identity does not match the verified passkey`);let o=I(E(e.runtimePolicyScope,`session.runtimePolicyScope`)),s=se(e.routerAbNormalSigning);if(!s)throw Error(`Yao recovery session signing state is invalid`);let c=_e(e.walletSessionId),l=he(e.quotaId);if(!c.ok||!l.ok)throw Error(`Yao recovery Wallet Session identity is invalid`);let u=hu(e.expiresAtMs,`session.expiresAtMs`),d=hu(e.remainingUses,`session.remainingUses`),f=r.capabilitySubjects.find(_u);if(r.walletId!==n.walletId||r.authorityId!==a.walletAuthorityId||r.authMethodId!==a.walletAuthMethodId||r.authorityDigestB64u!==a.authorityDigestB64u||r.authorityRevocationEpoch!==a.authorityRevocationEpoch||r.expiresAtMs!==u||i.walletSessionId!==c.value||!f||!p(f.materialActivation,a.materialActivation))throw Error(`Yao recovery session does not match the exact Wallet Session`);return{thresholdSessionId:T(e.thresholdSessionId,`session.thresholdSessionId`),authorizationId:r.authorizationId,walletSessionId:i.walletSessionId,quotaId:l.value,expiresAtMs:u,remainingUses:d,runtimePolicyScope:o,participantIds:t,routerAbNormalSigning:s,walletSession:r,operationCredential:i}}function yu(e){let t=e.capability,n=e.session,r=re(n.runtimePolicyScope);if(!r||t.applicationBinding.wallet_id!==String(e.walletId)||t.applicationBinding.near_ed25519_signing_key_id!==e.nearEd25519SigningKeyId||t.applicationBinding.key_creation_signer_slot!==e.signerSlot||t.nearAccountId!==e.nearAccountId||t.lifecycle.accountId!==String(e.walletId)||t.lifecycle.signingWorkerId!==e.relayerKeyId||n.routerAbNormalSigning?.signingWorkerId!==e.relayerKeyId||n.participantIds[0]!==t.participantIds[0]||n.participantIds[1]!==t.participantIds[1]||!ee(n.runtimePolicyScope,t.runtimePolicyScope)||n.runtimePolicyScope.signingRootVersion!==t.lifecycle.rootShareEpoch||t.applicationBinding.signing_root_id!==r.signingRootId||e.operationalPublicKey!==`ed25519:${Ee(Uint8Array.from(t.registeredPublicKey))}`)throw Error(`Yao recovery response does not preserve the registered wallet identity`)}function bu(e){if(yu(e),e.capability.lifecycle.thresholdSessionId!==e.session.thresholdSessionId)throw Error(`Yao recovery response does not preserve the threshold material lifecycle`)}function xu(e,t){if(yu(e),!p(e.capability.materialActivation,t))throw Error(`Yao warm recovery response does not preserve exact material activation`)}function Su(e){return`operationCredential`in e?e.operationCredential.token:e.walletSessionToken}function Cu(e){let n=E(e,`sync-account response`);if(n.ok!==!0||n.verified!==!0)throw Error(`sync-account response is not verified`);let r=qt(T(n.walletId,`walletId`)),i=z(T(n.nearAccountId,`nearAccountId`)),a=T(n.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),o=E(n.thresholdEd25519,`thresholdEd25519`),s=gu(o.participantIds),l=E(n.ed25519YaoRecovery,`ed25519YaoRecovery`);if(l.kind!==`router_ab_ed25519_yao_sync_recovery_v1`)throw Error(`sync-account recovery kind is invalid`);let u=bt(l.authorityRef);if(!u||String(u.walletId)!==String(r))throw Error(`sync-account recovery authority is invalid`);let d=c(n.walletAuthMethodId),f=t(n.walletAuthorityId),p=rt(n.foundingAuthority),m=Kt(n.foundingAuthMethod);if(!d.ok||!f.ok||d.value!==u.walletAuthMethodId||!p.ok||p.value.state!==`active`||p.value.provenance.kind!==`wallet_registration`||p.value.walletId!==r||p.value.authorityId!==f.value||!m||m.kind!==`passkey`||m.status!==`active`||m.walletId!==r||m.walletAuthorityId!==f.value||m.walletAuthMethodId!==d.value)throw Error(`sync-account exact auth-method identity is invalid`);let h=E(n.walletCustody,`walletCustody`);if(h.kind!==`wallet_custody_sync_bootstrap_v1`)throw Error(`walletCustody kind is invalid`);let g=Jr(l.capability),_=me(n.walletSession),v=pe(n.operationCredential),y={authority:u,walletAuthMethodId:d.value,walletAuthorityId:f.value,foundingAuthority:p.value,foundingAuthMethod:m,walletId:r,nearAccountId:i,nearEd25519SigningKeyId:a,signerSlot:hu(n.signerSlot,`signerSlot`),operationalPublicKey:T(n.publicKey,`publicKey`),relayerKeyId:T(o.relayerKeyId,`thresholdEd25519.relayerKeyId`),keyVersion:T(o.keyVersion,`thresholdEd25519.keyVersion`),credentialIdB64u:T(n.credentialIdB64u,`credentialIdB64u`),credentialPublicKeyB64u:T(n.credentialPublicKeyB64u,`credentialPublicKeyB64u`),session:vu(E(o.session,`thresholdEd25519.session`),s,{walletId:String(r),nearAccountId:String(i),nearEd25519SigningKeyId:a},_,v,{walletAuthorityId:f.value,walletAuthMethodId:d.value,authorityDigestB64u:p.value.authorityDigestB64u,authorityRevocationEpoch:p.value.revocationEpoch,materialActivation:g.materialActivation}),capability:g,walletSession:_,operationCredential:v,walletCustody:{envelope:$t(h.envelope),storeVersion:T(h.storeVersion,`walletCustody.storeVersion`)}};return bu(y),y}function wu(e){let t=e.parsed,n=t.session,r=re(n.runtimePolicyScope),i=ho({walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,walletSessionId:n.walletSessionId,authorizationId:n.authorizationId,quotaId:n.quotaId,thresholdSessionId:e.thresholdSessionId,remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs,runtimePolicyScope:n.runtimePolicyScope,signingRootId:r.signingRootId,signingRootVersion:String(r.signingRootVersion||``),routerAbNormalSigning:n.routerAbNormalSigning,walletSessionToken:Su(n),home:`operationCredential`in n?n.operationCredential.home:n.home,nowMs:Math.min(Date.now(),n.expiresAtMs-1)});if(!i.ok)throw Error(`recovered Yao Wallet Session is unusable: ${i.reason}`);return xc({walletId:Ie(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:Yt(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,rpId:pt(e.rpId),credentialIdB64u:t.credentialIdB64u,relayerUrl:e.relayerUrl,authority:t.authority,signingWalletSession:i.value})}function Tu(e){if(!b(e)||e.kind!==`wallet_custody_passkey_login_v1`)throw Error(`Passkey wallet unlock returned invalid custody data`);if(!b(e.ed25519))throw Error(`Passkey wallet unlock omitted Ed25519 custody continuity`);if(e.ed25519.kind===`absent`)return{kind:`wallet_custody_passkey_login_v1`,envelope:$t(e.envelope),storeVersion:T(e.storeVersion,`walletCustody.storeVersion`),ed25519:{kind:`absent`}};if(e.ed25519.kind!==`active`)throw Error(`Passkey wallet unlock returned invalid Ed25519 custody state`);let t=Number(e.ed25519.signerSlot),n=e.ed25519.participantIds;if(!Number.isSafeInteger(t)||t<1||!Array.isArray(n)||n.length!==2||!n.every(e=>Number.isSafeInteger(e)&&Number(e)>0)||n[0]===n[1])throw Error(`Passkey wallet unlock returned invalid Ed25519 signer identity`);return{kind:`wallet_custody_passkey_login_v1`,envelope:$t(e.envelope),storeVersion:T(e.storeVersion,`walletCustody.storeVersion`),ed25519:{kind:`active`,nearAccountId:T(e.ed25519.nearAccountId,`walletCustody.ed25519.nearAccountId`),nearEd25519SigningKeyId:T(e.ed25519.nearEd25519SigningKeyId,`walletCustody.ed25519.nearEd25519SigningKeyId`),signerSlot:t,publicKey:T(e.ed25519.publicKey,`walletCustody.ed25519.publicKey`),relayerKeyId:T(e.ed25519.relayerKeyId,`walletCustody.ed25519.relayerKeyId`),participantIds:[Number(n[0]),Number(n[1])],capability:Jr(e.ed25519.capability)}}}function Eu(e){if(!b(e))throw Error(`ECDSA custody chain target is invalid`);let t=T(e.kind,`ecdsaCustody.chainTarget.kind`),n=Number(e.chainId),r=T(e.networkSlug,`ecdsaCustody.chainTarget.networkSlug`);if(!Number.isSafeInteger(n)||n<0||!r)throw Error(`ECDSA custody chain target is invalid`);if(t===`evm`){if(e.namespace!==`eip155`)throw Error(`ECDSA custody EVM namespace is invalid`);return{kind:`evm`,namespace:`eip155`,chainId:n,networkSlug:r}}if(t===`tempo`)return{kind:`tempo`,chainId:n,networkSlug:r};throw Error(`ECDSA custody chain target kind is invalid`)}function Du(e){if(!b(e)||e.kind!==`wallet_custody_ecdsa_sync_continuity_v1`)throw Error(`Passkey wallet unlock returned invalid ECDSA custody continuity`);if(!Array.isArray(e.signers))throw Error(`Passkey wallet unlock returned invalid ECDSA custody signers`);let t=[];for(let n of e.signers){if(!b(n)||!b(n.walletKey))throw Error(`Passkey wallet unlock returned invalid ECDSA custody signer`);let e=n.walletKey,r=e.participantIds;if(!Array.isArray(r)||r.length!==2||r[0]!==1||r[1]!==2)throw Error(`Passkey wallet unlock returned invalid ECDSA custody participants`);t.push({chainTarget:Eu(n.chainTarget),walletKey:{walletId:T(e.walletId,`ecdsaCustody.walletKey.walletId`),keyHandle:T(e.keyHandle,`ecdsaCustody.walletKey.keyHandle`),ecdsaThresholdKeyId:T(e.ecdsaThresholdKeyId,`ecdsaCustody.walletKey.ecdsaThresholdKeyId`),signingRootId:T(e.signingRootId,`ecdsaCustody.walletKey.signingRootId`),signingRootVersion:T(e.signingRootVersion,`ecdsaCustody.walletKey.signingRootVersion`),relayerKeyId:T(e.relayerKeyId,`ecdsaCustody.walletKey.relayerKeyId`),contextBinding32B64u:T(e.contextBinding32B64u,`ecdsaCustody.walletKey.contextBinding32B64u`),derivationClientSharePublicKey33B64u:T(e.derivationClientSharePublicKey33B64u,`ecdsaCustody.walletKey.derivationClientSharePublicKey33B64u`),participantIds:[1,2],publicCapability:Ct(e.publicCapability)},activationReceipt:Tt(n.activationReceipt),runtimePolicyScope:I(n.runtimePolicyScope)})}if(t.length===0)throw Error(`Passkey wallet unlock omitted ECDSA custody signers`);return{kind:`wallet_custody_ecdsa_sync_continuity_v1`,signers:t}}function Ou(e){let t=e.raw.sessionKind;if(t===`issued_exact_wallet_session`){let n=pe(e.raw.operationCredential);if(n.walletSessionId!==e.walletSessionId)throw Error(`Wallet unlock Ed25519 credential does not identify its session`);return{sessionKind:t,operationCredential:n}}if(t!==`already_committed_exact_wallet_session`)throw Error(`Wallet unlock returned an unsupported Ed25519 session kind`);if(e.raw.operationCredential!==void 0)throw Error(`Reused Ed25519 Wallet Session must not carry its own credential`);if(pe(e.unlockCredential).walletSessionId!==e.walletSessionId)throw Error(`Wallet unlock Ed25519 session reuses another Wallet Session`);return{sessionKind:t}}function ku(e,t){if(e===null)return null;if(!b(e))throw Error(`Wallet unlock returned invalid Ed25519 session data`);let n=s(e.thresholdSessionId),r=ve(e.authorizationId),i=_e(e.walletSessionId),a=he(e.quotaId),o=Number(e.expiresAtMs),c=Number(e.remainingUses),l=I(e.runtimePolicyScope),u=ce(e.routerAbNormalSigning),d=e.participantIds;if(!n.ok||!r.ok||!i.ok||!a.ok||!Number.isSafeInteger(o)||o<=Date.now()||!Number.isSafeInteger(c)||c<1||!Array.isArray(d)||d.length!==2||!d.every(e=>Number.isSafeInteger(e)&&e>0)||d[0]===d[1])throw Error(`Wallet unlock returned invalid Ed25519 session lifecycle`);let f=Ou({raw:e,walletSessionId:i.value,unlockCredential:t});return{walletId:T(e.walletId,`ed25519Session.walletId`),nearAccountId:T(e.nearAccountId,`ed25519Session.nearAccountId`),nearEd25519SigningKeyId:T(e.nearEd25519SigningKeyId,`ed25519Session.nearEd25519SigningKeyId`),relayerKeyId:T(e.relayerKeyId,`ed25519Session.relayerKeyId`),participantIds:[Number(d[0]),Number(d[1])],thresholdSessionId:n.value,authorizationId:r.value,walletSessionId:i.value,quotaId:a.value,expiresAtMs:o,remainingUses:c,runtimePolicyScope:l,routerAbNormalSigning:u,...f}}function Au(e){let t=e.authorization.record,n=gt(e.ecdsaSession.public_capability.material_activation),r=0;for(let e of t.capabilitySubjects)e.kind===`sign`&&e.keyFamily===`ecdsa_secp256k1`&&p(e.materialActivation,n)&&(r+=1);if(t.walletId!==e.ed25519Session.walletId||t.walletId!==e.ecdsaSession.public_capability.client_id||t.authorizationId!==e.ed25519Session.authorizationId||t.authorizationId!==e.ecdsaSession.session.authorization_id||t.quotaId!==e.ed25519Session.quotaId||t.quotaId!==e.ecdsaSession.session.quota_id||t.expiresAtMs!==e.ed25519Session.expiresAtMs||t.expiresAtMs!==e.ecdsaSession.session.expires_at_ms||e.ed25519Session.walletSessionId!==e.ecdsaSession.session.wallet_session_id||e.authorization.operationCredential.walletSessionId!==e.ed25519Session.walletSessionId||e.ed25519Session.remainingUses!==e.ecdsaSession.session.remaining_uses||r!==1)throw Error(`Passkey ECDSA activation authority does not match its Wallet Session`)}function ju(e){let t=e.authorization.record;if(t.walletId!==e.ed25519Session.walletId||t.authorizationId!==e.ed25519Session.authorizationId||t.quotaId!==e.ed25519Session.quotaId||t.expiresAtMs!==e.ed25519Session.expiresAtMs||e.authorization.operationCredential.walletSessionId!==e.ed25519Session.walletSessionId)throw Error(`Passkey Ed25519 Wallet Session authorization is inconsistent`)}async function Mu(e,t){let n=e.data.walletSession!==void 0;if(n!==(e.data.operationCredential!==void 0))throw Error(`Passkey wallet unlock returned a partial Wallet Session authorization`);if(n){if(e.ed25519Session.sessionKind!==`already_committed_exact_wallet_session`)throw Error(`Passkey wallet unlock returned competing Wallet Session credentials`);let t={record:me(e.data.walletSession),operationCredential:pe(e.data.operationCredential)};return ju({ed25519Session:e.ed25519Session,authorization:t}),t}if(e.ed25519Session.sessionKind!==`issued_exact_wallet_session`)throw Error(`Passkey wallet unlock omitted the exact Wallet Session credential`);let r=await t.read({relayerUrl:e.relayServerUrl,operationCredential:e.ed25519Session.operationCredential},{walletSessionId:e.ed25519Session.walletSessionId,quotaId:e.ed25519Session.quotaId});if(r.status!==`active`||r.walletSessionId!==e.ed25519Session.walletSessionId||r.quotaId!==e.ed25519Session.quotaId||r.expiresAtMs!==e.ed25519Session.expiresAtMs||r.remainingUses!==e.ed25519Session.remainingUses)throw Error(`Passkey wallet unlock returned an inconsistent issued Wallet Session`);let i={record:r.authorization,operationCredential:e.ed25519Session.operationCredential};return ju({ed25519Session:e.ed25519Session,authorization:i}),i}async function Nu(e,t){let n=await Mu(e,t);return Au({ed25519Session:e.ed25519Session,ecdsaSession:e.ecdsaSession,authorization:n}),n}function Pu(e){let t=qn(e)??er(e);return t?{success:!1,kind:`already_committed`,code:t.code,message:t.message,next:t.next,committed:t.committed}:null}async function Fu(e,t,n){try{if(t.type!==`passkey_assertion`)throw Error(`Passkey wallet unlock requires a passkey assertion`);let r=T(t.challengeId,`challengeId`),a=t.webauthn_authentication,o=String(t.expected_origin||``).trim(),s={unlockBackend:`passkey`,challengeId:r,...`walletId`in t&&t.walletId?{walletId:t.walletId}:{},webauthn_authentication:zn(a),ed25519SessionRequest:t.ed25519SessionRequest,...o?{expected_origin:o}:{},...t.ecdsaSessionPolicy?{ecdsaSessionPolicy:dt(t.ecdsaSessionPolicy)}:{}},c=i(e,`/wallet/unlock/verify`),l=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(s)}),u=await l.json().catch(()=>({})),d=b(u)?u:{};if(!l.ok)return Pu(d)||{success:!1,error:typeof d.message==`string`?d.message:`HTTP ${l.status}`};if(d.ok!==!0)return Pu(d)||{success:!1,error:typeof d.message==`string`?d.message:`Wallet unlock verification failed`};let f=t.type===`passkey_assertion`&&t.ecdsaSessionPolicy!==void 0,p=ku(d.ed25519Session,d.operationCredential);if(t.ed25519SessionRequest.kind===`requested`&&!p)throw Error(`Wallet unlock omitted the requested Ed25519 Wallet Session`);if(t.ed25519SessionRequest.kind===`not_requested`&&p)throw Error(`Wallet unlock returned an unrequested Ed25519 Wallet Session`);let m=Tu(d.walletCustody),h,g,_,v;if(f){if(d.ecdsaSession===void 0)throw Error(`Wallet unlock omitted the requested ECDSA Wallet Session activation`);if(h=b(d.ecdsaSession)&&d.ecdsaSession.kind===`router_ab_ecdsa_credential_free_session_activated_v1`?at(d.ecdsaSession):_t(d.ecdsaSession),d.ecdsaActivationReceipt===void 0||d.ecdsaCustody===void 0)throw Error(`Wallet unlock omitted ECDSA custody continuity`);if(_=Tt(d.ecdsaActivationReceipt),v=Du(d.ecdsaCustody),!m)throw Error(`Wallet unlock omitted wallet custody for ECDSA activation`);if(h.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){if(!p)throw Error(`Credential-free ECDSA activation requires an Ed25519 Wallet Session`);g=await Nu({relayServerUrl:e,data:d,ed25519Session:p,ecdsaSession:h},n)}}else if(d.ecdsaSession!==void 0)throw Error(`Wallet unlock returned an unrequested ECDSA Wallet Session activation`);else p&&(g=await Mu({relayServerUrl:e,data:d,ed25519Session:p},n));if(h&&_&&v&&m){if(h.kind===`router_ab_ecdsa_credential_free_session_activated_v1`){if(!g)throw Error(`Credential-free ECDSA activation omitted exact Wallet Session authority`);return{success:!0,ecdsaSession:h,ecdsaActivationReceipt:_,ecdsaCustody:v,ed25519Session:p,walletCustody:m,walletSessionAuthorization:g}}return{success:!0,ecdsaSession:h,ecdsaActivationReceipt:_,ecdsaCustody:v,ed25519Session:p,walletCustody:m}}if(m&&p&&g)return{success:!0,ed25519Session:p,walletCustody:m,walletSessionAuthorization:g};if(m&&!p)return{success:!0,ed25519Session:null,walletCustody:m};throw Error(`Passkey wallet unlock returned incomplete exact session state`)}catch(e){return{success:!1,error:we(e)||`Failed to verify wallet unlock`}}}async function Iu(e,t){try{let n=T(t.challengeId,`challengeId`),r=String(t.expected_origin||``).trim(),a={unlockBackend:`passkey`,challengeId:n,webauthn_authentication:zn(t.webauthn_authentication),ed25519SessionRequest:t.ed25519SessionRequest,...r?{expected_origin:r}:{}},o=await fetch(i(e,`/wallet/unlock/verify`),{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(a)}),s=await o.json().catch(()=>({})),c=b(s)?s:{};if(!o.ok||c.ok!==!0)return Pu(c)||{success:!1,error:typeof c.message==`string`?c.message:`Wallet Session unlock failed (HTTP ${o.status})`};if(c.walletCustody!==void 0&&c.walletCustody!==null)throw Error(`Linked passkey unlock returned custody data`);if(c.ecdsaSession!==void 0&&c.ecdsaSession!==null)throw Error(`Linked passkey unlock returned an ECDSA activation`);let l=ku(c.ed25519Session,c.operationCredential);if(t.ed25519SessionRequest.kind===`requested`&&!l)throw Error(`Linked passkey unlock omitted the requested Ed25519 Wallet Session`);if(t.ed25519SessionRequest.kind===`not_requested`&&l)throw Error(`Linked passkey unlock returned an unrequested Ed25519 Wallet Session`);return{success:!0,walletSession:me(c.walletSession),operationCredential:pe(c.operationCredential),ed25519Session:l}}catch(e){return{success:!1,error:we(e)||`Failed to verify linked passkey Wallet Session`}}}function Lu(e){let t=g(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a session id`);return t.value}function Ru(e){let t=ge(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a Wallet Session mint id`);return t.value}function zu(e){return dt({kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:e.keyHandle,session_policy:{threshold_session_id:Lu(pr(`threshold-ecdsa-registration-recovery`)),wallet_session_mint_id:Ru(pr(`wallet-session-mint`)),ttl_ms:e.sessionPolicy.ttlMs,remaining_uses:e.sessionPolicy.unlockRemainingUses,runtime_policy_scope:e.runtimePolicyScope}})}async function Bu(e){let t=await fetch(i(e.relayerUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:e.walletId,rpId:e.rpId})}),n=E(await t.json().catch(()=>({})),`Passkey unlock challenge response`);if(!t.ok||n.ok!==!0)throw Error(typeof n.message==`string`&&n.message?n.message:`wallet/unlock/challenge failed (HTTP ${t.status})`);return{challengeId:y(n.challengeId,`Passkey unlock challenge ID`),challengeB64u:y(n.challengeB64u,`Passkey unlock challenge`)}}function Vu(e){return e===`ble`||e===`hybrid`||e===`internal`||e===`nfc`||e===`usb`}function Hu(e,t){return{id:e,type:`public-key`,transports:t.filter(Vu)}}function Uu(e){let t=e.session.session.wallet_session;if(t.walletId!==e.pending.walletId||t.authMethodId!==e.pending.walletAuthMethodId||t.authorityId!==e.response.foundingAuthority.authorityId||t.expiresAtMs!==e.session.session.expires_at_ms||t.authorizationId!==e.session.session.authorization_id||t.quotaId!==e.session.session.quota_id||e.session.session.remaining_uses<=0||e.session.session.expires_at_ms<=Date.now()||e.session.session.wallet_session_id!==e.session.session.operation_credential.walletSessionId||!vt(e.session.public_capability,e.walletKey.publicCapability))throw Error(`ECDSA registration unlock did not issue the exact Wallet Session`)}function Wu(e){if(e.signers.length!==e.walletKeys.length)throw Error(`ECDSA registration unlock returned incomplete custody continuity`);let t=new Map;for(let n of e.walletKeys){let e=Re(n.chainTarget);if(t.has(e))throw Error(`ECDSA registration has duplicate custody targets`);t.set(e,n)}for(let n of e.signers){let r=Re(n.chainTarget),i=t.get(r);if(!i)throw Error(`ECDSA registration unlock returned an unknown target`);if(t.delete(r),n.walletKey.walletId!==e.pending.walletId||n.walletKey.keyHandle!==i.keyHandle||n.walletKey.ecdsaThresholdKeyId!==i.ecdsaThresholdKeyId||n.walletKey.signingRootId!==i.signingRootId||n.walletKey.signingRootVersion!==i.signingRootVersion||n.walletKey.relayerKeyId!==i.relayerKeyId||n.walletKey.contextBinding32B64u!==i.contextBinding32B64u||n.walletKey.derivationClientSharePublicKey33B64u!==i.derivationClientSharePublicKey33B64u||!vt(n.walletKey.publicCapability,i.publicCapability)||!Et(n.activationReceipt,e.response.ecdsa.activation))throw Error(`ECDSA registration unlock returned different custody continuity`)}}function Gu(e){new Uint8Array(e).fill(0)}async function Ku(e){if(e.pending.auth.kind!==`passkey`)throw Error(`ECDSA registration passkey unlock has a different pending factor`);let t=e.walletKeys[0];if(!t)throw Error(`ECDSA registration unlock has no primary wallet key`);let n=typeof window<`u`?window.location.origin:``;if(!n)throw Error(`ECDSA registration passkey unlock requires an origin`);Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_CHALLENGE_STARTED,status:`running`,authMethod:`passkey`});let r=await Bu({relayerUrl:e.relayerUrl,walletId:String(e.pending.walletId),rpId:e.pending.auth.rpId});Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`}});let i=await e.signingSurface.getAuthenticationCredentialsSerialized({subjectId:String(e.pending.walletId),challengeB64u:r.challengeB64u,allowCredentials:[Hu(e.pending.auth.credentialIdB64u,e.pending.auth.transports)],includeSecondPrfOutput:!0});if(Tl(i)!==e.pending.auth.credentialIdB64u)throw Error(`ECDSA registration unlock returned a different Passkey credential`);Ml(e.onEvent,String(e.pending.walletId),{phase:gn.STEP_03_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let a=wl(i,`ECDSA registration recovery`),o=await Fu(e.relayerUrl,{type:`passkey_assertion`,challengeId:r.challengeId,walletId:String(e.pending.walletId),webauthn_authentication:i,ed25519SessionRequest:{kind:`not_requested`},expected_origin:n,ecdsaSessionPolicy:zu({keyHandle:t.keyHandle,sessionPolicy:e.sessionPolicy,runtimePolicyScope:cl(e.response).ecdsa.runtimePolicyScope})},new fr);if(!o.success)throw Error(o.error||`Passkey ECDSA registration unlock failed`);if(o.ecdsaSession.kind!==`router_ab_ecdsa_post_registration_session_activated_v1`||!o.ecdsaCustody||!o.walletCustody)throw Error(`Passkey ECDSA registration unlock did not issue exact session custody`);Uu({pending:e.pending,response:e.response,session:o.ecdsaSession,walletKey:t}),Wu({pending:e.pending,response:e.response,walletKeys:e.walletKeys,signers:o.ecdsaCustody.signers});let s=Uint8Array.from(R(a)).buffer;try{let n=await e.signingSurface.rejoinWalletCustodyEvmFamilyKeySet({walletId:String(e.pending.walletId),custodyJson:Il(e.pending.localMaterial.custodyCommit),factorSecret:s,evmFamilySigningKeySlotId:t.evmFamilySigningKeySlotId,applicationBindingDigestB64u:e.response.ecdsa.bootstrap.applicationBindingDigestB64u,registeredClientRootPublicKey33B64u:t.derivationClientSharePublicKey33B64u,relayerPublicIdentityJson:JSON.stringify({relayerKeyId:t.relayerKeyId,relayerPublicKey33B64u:t.relayerVerifyingShareB64u,groupPublicKey33B64u:t.thresholdEcdsaPublicKeyB64u,ethereumAddress:t.thresholdOwnerAddress,relayerShareRetryCounter:t.relayerShareRetryCounter})});return{kind:`passkey`,credential:i,custody:o.walletCustody,session:o.ecdsaSession,readyStateBlobB64u:n.readyStateBlobB64u,publicFacts:n.publicFacts}}finally{Gu(s)}}async function qu(e){if(e.pending.auth.kind!==`email_otp`)throw Error(`ECDSA registration Email OTP unlock has a different pending factor`);let t=e.walletKeys[0];if(!t)throw Error(`ECDSA registration unlock has no primary wallet key`);let n=cl(e.response).ecdsa.runtimePolicyScope,r=await du({walletSession:{walletId:Ie(e.pending.walletId),walletSessionUserId:String(e.pending.walletId)},authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:e.pending.walletAuthMethodId},relayUrl:e.relayerUrl,groupId:oe,routePlan:iu({freshRouteFamily:`login`,operation:We}),workerCtx:e.signingSurface.getSignerWorkerContext(),verification:{kind:`otp`,challengeId:e.exactMethod.challengeId,otpCode:e.exactMethod.otpCode},runtimePolicyScope:n,ecdsaSessionHandleBinding:{keyHandle:t.keyHandle,authSubjectId:e.pending.auth.providerSubject,operation:`wallet_unlock`,chainTarget:t.chainTarget},ecdsaSessionPolicy:zu({keyHandle:t.keyHandle,sessionPolicy:e.sessionPolicy,runtimePolicyScope:n})});if(r.operation!==`wallet_unlock`)throw Error(`Email OTP ECDSA registration unlock returned the wrong operation`);return Uu({pending:e.pending,response:e.response,session:r.ecdsaSession,walletKey:t}),Wu({pending:e.pending,response:e.response,walletKeys:e.walletKeys,signers:r.ecdsaCustody.continuity.signers}),{kind:`email_otp`,session:r.ecdsaSession,readyStateBlobB64u:r.ecdsaCustody.readyStateBlobB64u,publicFacts:r.ecdsaCustody.publicFacts}}async function Ju(e){switch(e.exactMethod.kind){case`passkey`:return await Ku({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,pending:e.pending,response:e.response,walletKeys:e.walletKeys,exactMethod:e.exactMethod,signingSurface:e.signingSurface});case`email_otp`:return await qu({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,onEvent:e.onEvent,pending:e.pending,response:e.response,walletKeys:e.walletKeys,exactMethod:e.exactMethod,signingSurface:e.signingSurface});default:throw e.exactMethod,Error(`Unsupported pending registration unlock method: ${String(e.exactMethod)}`)}}const Yu={listPendingWalletRegistrationCommits:Xu,completeWalletRegistrationNearProvisioning:Qn,publishPendingWalletRegistrationCommit:Zu};async function Xu(){return await V.initialize(),await V.listPendingWalletRegistrationCommits()}async function Zu(e){return await V.publishPendingWalletRegistrationCommit(e)}function Qu(e){return e instanceof Error?e:Error(String(e||`pending registration replay failed`))}function $u(e){return e.operation===`near_provisioning`&&e.phase===`joined`}function ed(e,t){let n=e.localMaterial.ed25519.metadata,r=e.localMaterial.ed25519.localMaterial;return{binding:{kind:Qe,applicationBindingDigestB64u:r.applicationBindingDigestB64u,registeredPublicKeyB64u:n.registeredPublicKeyB64u,participantIds:n.participantIds,stateEpoch:n.stateEpoch,walletId:String(t.walletId),nearAccountId:t.ed25519.nearAccountId,nearEd25519SigningKeyId:t.ed25519.nearEd25519SigningKeyId,signerSlot:t.ed25519.signerSlot,signingWorkerId:n.signingWorkerId,signingWorkerVerifyingShareB64u:n.signingWorkerVerifyingShareB64u},sealed:{ciphertextB64u:r.b64u,nonceB64u:r.nonceB64u}}}function td(e){let t=R(e.localMaterial.ed25519.metadata.registeredPublicKeyB64u);if(t.length!==32)throw Error(`pending registration has an invalid Ed25519 registered public key`);return`ed25519:${Ee(t)}`}function nd(e,t,n){let r=e.localMaterial.ed25519.metadata,i=e.localMaterial.custodyCommit;if(e.auth.kind===`passkey`){if(nl({clientPublicKey:n,finalized:t,expectedRpId:e.auth.rpId,expectedWalletId:e.walletId}).credentialIdB64u!==e.auth.credentialIdB64u)throw Error(`pending registration returned a different Passkey credential`)}else rl({clientPublicKey:n,finalized:t,expectedRegistrationAuthorityId:e.auth.registrationAuthorityId,expectedWalletId:e.walletId});if(t.foundingAuthMethod.walletAuthMethodId!==e.walletAuthMethodId||t.foundingAuthMethod.walletId!==e.walletId||t.foundingAuthority.walletId!==e.walletId||t.ed25519.signerSlot!==r.signerSlot||t.ed25519.nearEd25519SigningKeyId!==r.nearEd25519SigningKeyId||t.ed25519.participantIds[0]!==r.participantIds[0]||t.ed25519.participantIds[1]!==r.participantIds[1]||t.ed25519.routerAbNormalSigning.signingWorkerId!==r.signingWorkerId||t.ed25519.relayerKeyId!==t.ed25519.routerAbNormalSigning.signingWorkerId||t.custodyKeyManifestDigestB64u!==i.keyManifestDigestB64u||i.registeredPublicKeyB64u!==void 0&&i.registeredPublicKeyB64u!==r.registeredPublicKeyB64u)throw Error(`pending registration does not match the committed NEAR projection`);Cn(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function rd(e,t){let n=t.registrationEstablishedSession.session,r=n.tokens.kind===`near_ed25519`||n.tokens.kind===`near_ed25519_and_evm_family_ecdsa`?n.tokens.ed25519:null,i=e.localMaterial.ed25519.metadata;if(n.walletId!==e.walletId||!r||r.nearAccountId!==t.ed25519.nearAccountId||r.nearEd25519SigningKeyId!==t.ed25519.nearEd25519SigningKeyId||r.routerAbNormalSigning.signingWorkerId!==i.signingWorkerId||!p(r.materialActivation,i.materialActivation))throw Error(`pending registration does not match the committed Wallet Session projection`)}function id(e,t){rd(e,t);let n=t.registrationEstablishedSession;if(n.kind===`issued`){if(n.session.walletSession.walletId!==e.walletId||n.session.walletSession.authMethodId!==e.walletAuthMethodId)throw Error(`pending registration issued a Wallet Session for another auth method`);return}if(n.next!==`unlock_exact_method`)throw Error(`pending registration replay has an invalid continuation`)}function ad(e,t,n){if(!t.ok||t.kind!==`near_ed25519`)throw Error(t.ok?`pending registration replay returned a different signer branch`:`pending registration replay failed: ${t.code}`);if(t.walletCustody?.status!==n)throw Error(`pending registration replay did not commit the expected wallet custody`);return nd(e,t,td(e)),t}function od(e,t){let n=ad(e,t,e.signerPlanKind===`near_ed25519`?`committed`:`joined`);if(e.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`&&(n.registrationEstablishedSession.kind!==`already_committed`||n.registrationEstablishedSession.session.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`))throw Error(`NEAR completion must extend the committed ECDSA session`);return id(e,n),n}async function sd(e,t){let n=td(e),r={walletId:e.walletId,nearAccountId:z(t.ed25519.nearAccountId),nearEd25519SigningKeyId:t.ed25519.nearEd25519SigningKeyId,signerSlot:t.ed25519.signerSlot,operationalPublicKey:n,relayerKeyId:t.ed25519.relayerKeyId,keyVersion:t.ed25519.keyVersion,participantIds:t.ed25519.participantIds,custodyMaterial:ed(e,t)};if(e.auth.kind===`passkey`){if(t.authMethod.kind!==`passkey`)throw Error(`pending Passkey registration replay returned a non-Passkey auth method`);return $e({...r,rpId:e.auth.rpId,credentialIdB64u:e.auth.credentialIdB64u,credentialPublicKeyB64u:t.authMethod.credentialPublicKeyB64u,transports:e.auth.transports})}if(t.authMethod.kind!==`email_otp`)throw Error(`pending Email OTP registration replay returned a non-Email OTP auth method`);let i=lt(t.authority);if(!i)throw Error(`pending Email OTP registration replay returned an invalid authority`);return await tt({...r,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:i})}function cd(e,t,n){return{pending:e,authority:t.authority,foundingAuthority:{authority:t.foundingAuthority,authMethod:t.foundingAuthMethod},request:{operation:e.operation,registrationCeremonyId:e.registrationCeremonyId,idempotencyKey:e.idempotencyKey,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId},ecdsaContinuity:[],walletSessionPublication:t.registrationEstablishedSession.kind===`issued`?{kind:`issued`,walletSession:t.registrationEstablishedSession.session.walletSession,operationCredential:t.registrationEstablishedSession.session.operationCredential}:{kind:`credential_free_projection`,walletSession:t.registrationEstablishedSession.session.walletSession},registration:n}}function ld(e){switch(e.auth.kind){case`passkey`:return{kind:`passkey`};case`email_otp`:return{kind:`email_otp`,enrollment:e.auth.enrollment};default:throw e.auth,Error(`pending registration has an unsupported auth method`)}}function ud(e,t){return{relayerUrl:e,registrationCeremonyId:t.registrationCeremonyId,signedSetup:t.signedSetup,idempotencyKey:t.idempotencyKey,ed25519:{activationReference:t.localMaterial.ed25519.activationReference},auth:ld(t),walletCustodyCommit:t.localMaterial.custodyCommit}}async function dd(e){let t=ud(e.relayerUrl,e.pending),n=await e.ports.completeWalletRegistrationNearProvisioning(t);return od(e.pending,n)}async function fd(e){let t=await Qn({...ud(e.relayerUrl,e.pending),headers:te(e.operationCredential)}),n=od(e.pending,t),r=n.registrationEstablishedSession.session;if(r.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`Persisted mixed registration has no NEAR session`);let i=r.tokens.ed25519,a=Ut({kind:`router_ab_ed25519_yao_warm_recovery_bootstrap_request_v1`,walletId:e.pending.walletId,nearAccountId:n.ed25519.nearAccountId,nearEd25519SigningKeyId:n.ed25519.nearEd25519SigningKeyId,signerSlot:n.ed25519.signerSlot,thresholdSessionId:i.thresholdSessionId,signingWorkerId:n.ed25519.routerAbNormalSigning.signingWorkerId,participantIds:n.ed25519.participantIds});if(!a.ok)throw Error(a.message);let o=await fetch(`${e.relayerUrl.replace(/\/$/,``)}${Vt}`,{method:`POST`,headers:{...te(e.operationCredential),"Content-Type":`application/json`},body:JSON.stringify(a.value)}),s=await o.json();if(!o.ok||!s||typeof s!=`object`)throw Error(`Persisted NEAR registration activation is unavailable`);let c=Jr(Reflect.get(s,`capability`)),l=e.pending.localMaterial.ed25519.metadata;if(c.registrationContinuity.kind!==`registration`||c.applicationBinding.wallet_id!==e.pending.walletId||c.applicationBinding.near_ed25519_signing_key_id!==l.nearEd25519SigningKeyId||c.lifecycle.lifecycleId!==e.pending.localMaterial.ed25519.activationReference.lifecycle_id||c.lifecycle.thresholdSessionId!==i.thresholdSessionId||c.lifecycle.signingWorkerId!==l.signingWorkerId||c.applicationBinding.key_creation_signer_slot!==l.signerSlot||L(Uint8Array.from(c.registeredPublicKey))!==l.registeredPublicKeyB64u||!p(c.materialActivation,l.materialActivation))throw Error(`Persisted NEAR registration activation changed identity`);let u=c.registrationContinuity;return{joined:{commitPayload:e.pending.localMaterial.custodyCommit,activationReference:e.pending.localMaterial.ed25519.activationReference,localMaterial:e.pending.localMaterial.ed25519.localMaterial,metadata:ma({material:ed(e.pending,n),activation:{materialActivation:c.materialActivation,lifecycleId:c.lifecycle.lifecycleId,signingRootVersion:c.lifecycle.rootShareEpoch,signingRootId:c.applicationBinding.signing_root_id,signerSetId:c.lifecycle.signerSetId,thresholdSessionId:c.lifecycle.thresholdSessionId,activationTranscriptB64u:L(Uint8Array.from(u.activationTranscript)),activationCapabilityBindingB64u:L(Uint8Array.from(c.activeCapabilityBinding))}})},admissionRequest:u.admissionRequest,admissionReceipt:u.admissionReceipt}}async function pd(e){let t=await dd(e),n=await sd(e.pending,t);return await e.ports.publishPendingWalletRegistrationCommit(cd(e.pending,t,n)),{kind:`published`,registrationCeremonyId:e.pending.registrationCeremonyId}}async function md(e){let t=e.ports||Yu,n=await t.listPendingWalletRegistrationCommits(),r=[];for(let i of n){if(ol(i)||sl(i)){r.push({kind:`unlock_required`,registrationCeremonyId:i.registrationCeremonyId,keyFamilies:i.localMaterial.keyFamilies,next:`unlock_exact_method`,reason:`ecdsa_local_finalization`});continue}if(i.operation===`near_provisioning`&&i.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){r.push({kind:`unlock_required`,reason:`near_provisioning`,registrationCeremonyId:i.registrationCeremonyId,next:`unlock_exact_method`});continue}if($u(i))try{r.push(await pd({relayerUrl:e.relayerUrl,pending:i,ports:t}))}catch(e){r.push({kind:`failed`,registrationCeremonyId:i.registrationCeremonyId,error:Qu(e)})}}return r}const hd={activateWalletRegistration:Yn,publishPendingWalletRegistrationCommit:Zu,unlockPendingEcdsaRegistration:Ju};async function gd(e){await V.initialize();let t=null;for(let n of await V.listPendingWalletRegistrationCommits())if(!(n.operation!==`registration_activate`||n.walletId!==e)){if(t)throw Error(`wallet has multiple pending registration activations`);t=n}if(!t)return null;if(!ol(t)&&!sl(t))throw Error(`pending registration commit is not ECDSA-enabled`);return t}async function _d(e){if(e.pending.auth.kind!==e.exactMethod.kind)throw Error(`pending registration requires its exact authentication method`);return await jl({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,pending:e.pending,exactMethod:e.exactMethod,signingSurface:e.signingSurface,ports:hd,nearContext:e.nearContext,nearCompletion:e.nearCompletion,onEvent:e.onEvent})}async function vd(e){let t=performance.now();mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:`started`,startedAtMs:t});try{let n=await e.signingEngine.scheduleRouterAbEcdsaDerivationLoginPresignaturePrefill({walletId:e.walletId,chainTarget:e.chainTarget},e.statusReads);mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:n.status,reason:n.reason,scheduleReason:`schedule`in n?n.schedule.reason:null,walletSessionId:n.walletSessionId,durationMs:performance.now()-t})}catch{mr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:`failed`,reason:`unexpected_error`,durationMs:performance.now()-t})}}const yd=new Map,bd=new Set;function xd(e,t){for(let n of bd)try{n(e,t)}catch{}}function Sd(e,t){let n=String(e),r=yd.get(n);if(r)return r;let i={state:{status:`near_pending`,updatedAtMs:t},inFlight:null};return yd.set(n,i),i}function Cd(e){return yd.get(String(e))?.state??null}async function wd(e){let t=yd.get(String(e));return t?t.inFlight?await t.inFlight:t.state:null}function Td(e,t){let n=Sd(e,t.updatedAtMs);n.state.status===`near_ready`&&t.status!==`near_ready`||(n.state=t,xd(e,t))}function Ed(e){return bd.add(e),()=>{bd.delete(e)}}function Dd(e){let t=Sd(e.walletId,e.nowMs());if(t.inFlight)return t.inFlight;if(t.state.status===`near_ready`)return Promise.resolve(t.state);Td(e.walletId,{status:`near_provisioning`,updatedAtMs:e.nowMs()});let n=(async()=>{try{return await e.attempt()}catch(t){return{status:`near_failed_retryable`,updatedAtMs:e.nowMs(),error:t instanceof Error?t.message:String(t),errorCode:`near_provisioning_failed`}}})().then(n=>(t.inFlight=null,Td(e.walletId,n),n));return t.inFlight=n,n}function Od(e){let t=e.registration;if(t.mode!==`managed`)return;let n=String(t.projectEnvironmentId||``).trim(),r=String(t.publishableKey||``).trim();if(!(!n||!r))return{projectEnvironmentId:n,publishableKey:r}}async function kd(e){let t=(await V.listWalletAuthMethodsV2ForWallet(String(e.walletId))).filter(t=>t.kind===`passkey`&&t.status===`active`&&t.walletId===e.walletId&&String(t.rpId)===e.rpId&&String(t.credentialIdB64u)===e.credentialIdB64u),[n]=t;if(t.length!==1||!n)throw Error(`passkey authority requires one exact active V2 auth method`);return n}async function Ad(e){let t=await kd(e);return await ct({authority:{walletId:t.walletId,factor:{kind:`passkey`,credentialIdB64u:t.credentialIdB64u},verifier:{kind:`webauthn`,rpId:t.rpId},bindingId:t.walletAuthMethodId}})}const jd=[`walletId`,`envelopeId`,`factor`,`envelopeRevision`,`binding`,`ownership`];function Md(e){let t=Nd(e.replacement.envelopeBindingJson);if(t.walletId!==e.expectedWalletId)throw Error(`recovery replacement envelope changed the wallet identity`);if(t.envelopeId!==e.replacement.envelopeId)throw Error(`recovery replacement envelope changed the envelope identity`);let n=$t({kind:an,envelopeId:t.envelopeId,walletId:t.walletId,binding:t.binding,factor:t.factor,ownership:en(t.ownership,`recoveryReplacementEnvelope.binding.ownership`),envelopeVersion:an,envelopeRevision:t.envelopeRevision,nonceB64u:e.replacement.envelopeNonceB64u,sealedCustodySecretB64u:e.replacement.sealedCustodySecretB64u,ciphertextDigestB64u:e.replacement.envelopeCiphertextDigestB64u,aadHashB64u:e.replacement.envelopeAadHashB64u,lifecycle:{state:`active`,activatedAtMs:e.activatedAtMs},createdAtMs:e.activatedAtMs,updatedAtMs:e.activatedAtMs},`recoveryReplacementEnvelope`);if(n.binding.kind!==`wallet_custody_seed_v1`)throw Error(`custody envelope must seal the wallet custody seed`);return n}function Nd(e){let t;try{t=JSON.parse(e)}catch{throw Error(`recovery replacement envelope binding is not JSON`)}let n=E(t,`recoveryReplacementEnvelope.binding`);return N(n,jd,`recoveryReplacementEnvelope.binding`),n}const Pd=`passkeyCustodyEnvelopeCacheV1`,Fd=`passkey_custody_envelope_cache_v1`;let Id={kind:`unconfigured`};const Ld=new Map;function Rd(e){throw Error(`unknown passkey custody session cache persistence state: ${String(e)}`)}function zd(){switch(Id.kind){case`configured`:return Id.persistence;case`unconfigured`:throw Error(`passkey custody session cache persistence is not configured`);default:return Rd(Id)}}function Bd(e){Id={kind:`configured`,persistence:e}}function Vd(e,t){let n=String(e||``).trim(),r=String(t||``).trim();if(!n||!r)throw Error(`passkey custody session identity is required`);return`${n}:${r}`}function Hd(){return{kind:Fd,envelopes:[]}}function Ud(e){if(e==null)return Hd();if(typeof e!=`object`||Array.isArray(e))throw Error(`passkey custody envelope cache is invalid`);let t=e;if(t.kind!==Fd||!Array.isArray(t.envelopes))throw Error(`passkey custody envelope cache has an invalid shape`);return{kind:Fd,envelopes:t.envelopes.map(e=>{let t=$t(e);if(!tn(t.binding))throw Error(`generic passkey custody cache cannot contain an Ed25519 export root`);return t})}}async function Wd(){return Ud(await zd().readCacheEntry(Pd))}async function Gd(e){await zd().writeCacheEntry(Pd,e)}async function Kd(e){if(e.envelope.lifecycle.state!==`active`)throw Error(`passkey custody session envelope is not active`);if(!tn(e.envelope.binding))throw Error(`generic passkey custody cache accepts wallet custody seeds only`);if(String(e.envelope.walletId)!==String(e.walletId)||e.envelope.factor.kind!==`passkey`||String(e.envelope.factor.credentialIdB64u)!==String(e.credentialIdB64u))throw Error(`passkey custody session envelope identity changed`);let t=Vd(String(e.walletId),String(e.credentialIdB64u));Ld.set(t,e.envelope);let n=(await Wd()).envelopes.filter(e=>e.factor.kind!==`passkey`||Vd(String(e.walletId),String(e.factor.credentialIdB64u))!==t);n.push(e.envelope),await Gd({kind:Fd,envelopes:n.slice(-32)})}async function qd(e){let t=Vd(String(e.walletId),String(e.credentialIdB64u)),n=Ld.get(t);if(n)return n;let r=(await Wd()).envelopes.find(e=>e.lifecycle.state===`active`&&e.factor.kind===`passkey`&&Vd(String(e.walletId),String(e.factor.credentialIdB64u))===t);return r?(Ld.set(t,r),r):null}function Jd(e){return Math.max(0,Math.round(performance.now()-e))}function Yd(){return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:0,workerRequestRoundTripMs:0,workerResponseValidationMs:0,requestSetupMs:0,promptUserMs:0,promptElementDefineMs:0,promptMountMs:0,promptHostFirstUpdateMs:0,promptHostInteractiveMs:0,promptConfirmEventMs:0,promptDecisionWaitMs:0,credentialCreateStartMs:0,credentialCreateMs:0,credentialSerializeMs:0,duplicateRetryCount:0,mainThreadTotalMs:0}}function Xd(e){let t=performance.now(),n=wl(e.credential,`Passkey registration authority`),r=Jd(t),i=performance.now(),a=Rn(e.credential),o=Jd(i);return{kind:`passkey`,credential:e.credential,webauthnRegistration:a,prfFirstB64u:n,diagnostics:{kind:`passkey_registration_authority_diagnostics_v1`,requestConfirmationMs:e.requestConfirmationMs,prfExtractionMs:r,credentialRedactionMs:o,confirmationWorkerReadyMs:e.diagnostics.workerReadyMs,confirmationWorkerRequestRoundTripMs:e.diagnostics.workerRequestRoundTripMs,confirmationWorkerResponseValidationMs:e.diagnostics.workerResponseValidationMs,confirmationRequestSetupMs:e.diagnostics.requestSetupMs,confirmationPromptUserMs:e.diagnostics.promptUserMs,confirmationPromptElementDefineMs:e.diagnostics.promptElementDefineMs,confirmationPromptMountMs:e.diagnostics.promptMountMs,confirmationPromptHostFirstUpdateMs:e.diagnostics.promptHostFirstUpdateMs,confirmationPromptHostInteractiveMs:e.diagnostics.promptHostInteractiveMs,confirmationPromptConfirmEventMs:e.diagnostics.promptConfirmEventMs,confirmationPromptDecisionWaitMs:e.diagnostics.promptDecisionWaitMs,confirmationCredentialCreateStartMs:e.diagnostics.credentialCreateStartMs,confirmationCredentialCreateMs:e.diagnostics.credentialCreateMs,confirmationCredentialSerializeMs:e.diagnostics.credentialSerializeMs,confirmationDuplicateRetryCount:e.diagnostics.duplicateRetryCount,confirmationMainThreadTotalMs:e.diagnostics.mainThreadTotalMs}}}async function Zd(e){let t=performance.now();return Xd({credential:await e,diagnostics:Yd(),requestConfirmationMs:Jd(t)})}async function Qd(e){let t=performance.now(),n=await e.context.signingEngine.requestRegistrationCredentialConfirmation({walletId:e.walletId,signerSlot:e.signerSlot,confirmerText:e.options.confirmerText,confirmationConfigOverride:e.confirmationConfigOverride,challengeB64u:e.registrationIntentDigestB64u}),r=Jd(t),i=n.registrationDiagnostics??Yd();return Xd({credential:n.credential,diagnostics:i,requestConfirmationMs:r})}function $d(e){let t=e.trim();if(!t)throw Error(`Registration finalize idempotency key is required`);return t}function ef(e){let t=l(e.materialActivation);if(!t.ok)throw Error(`Email OTP Ed25519 material activation is invalid`);let n=String(e.nearAccountId||``).trim(),r=String(e.operationalPublicKey||``).trim(),i=String(e.thresholdSessionId||``).trim(),a=Number(e.signerSlot);if(!n||!r||!i)throw Error(`Email OTP Ed25519 signer identity is incomplete`);if(!Number.isSafeInteger(a)||a<1)throw Error(`Email OTP Ed25519 signer slot is invalid`);let o=ae(e.runtimePolicyScope);if(!o)throw Error(`Email OTP Ed25519 runtime policy scope is invalid`);return{materialActivation:t.value,nearAccountId:n,signerSlot:a,operationalPublicKey:r,thresholdSessionId:i,runtimePolicyScope:o}}function tf(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Email OTP Ed25519 signer selection must be an object`);let t=e;if(t.kind===`absent`)return{kind:`absent`};if(t.kind!==`present`)throw Error(`Email OTP Ed25519 signer selection kind is invalid`);return{kind:`present`,...ef(t)}}function nf(e){let t=of(e,`wallet/email-otp/challenge signerSelection`);if(t.kind===`ed25519_only`)return{kind:`ed25519_only`,...ef(t)};if(t.kind!==`ecdsa`)throw Error(`wallet/email-otp/challenge signerSelection kind is invalid`);return{kind:`ecdsa`,keyHandle:Z(t.keyHandle,`wallet/email-otp/challenge keyHandle`),runtimePolicyScope:I(t.runtimePolicyScope),ed25519:tf(t.ed25519)}}var rf=class extends Error{code;status;retryAfterMs;resetAtMs;constructor(e){super(e.message),this.name=`EmailOtpRouteError`;let t=sf(e.code);t&&(this.code=t),this.status=e.status;let n=Number(e.retryAfterMs);Number.isFinite(n)&&n>=0&&(this.retryAfterMs=Math.floor(n));let r=Number(e.resetAtMs);Number.isFinite(r)&&r>=0&&(this.resetAtMs=Math.floor(r))}};function af(e){let t=e||globalThis.fetch;if(typeof t!=`function`)throw Error(`fetch is unavailable in this runtime`);return t}function of(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} returned invalid JSON`);return e}function Z(e,t){return T(e,t)}function sf(e){return v(e)}function cf(e){let t={"Content-Type":`application/json`},n=String(e.publishableKey||``).trim();return n&&(t.Authorization=`Bearer ${n}`),t}function lf(e){return e.routeFamily===`registration`?eu({routeFamily:`registration`,operation:He}):eu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function uf(e){let t=sf(e.challenge.action);if(t&&t!==e.expectedAction)throw Error(`${e.context} returned ${t}; expected ${e.expectedAction}`)}async function df(e){let t=await af(e.fetchImpl)(e.url,{method:`POST`,headers:cf({publishableKey:e.publishableKey}),credentials:`include`,body:JSON.stringify(e.body)}),n=await t.text(),r=null;try{r=n?JSON.parse(n):null}catch{throw Error(`${e.url} returned non-JSON response (HTTP ${t.status})`)}let i=of(r,e.url);if(!t.ok||i.ok===!1)throw new rf({message:typeof i.message==`string`&&i.message.trim()||`${e.url} failed (HTTP ${t.status})`,status:t.status,code:i.code,retryAfterMs:i.retryAfterMs,resetAtMs:i.resetAtMs});return i}async function ff(e){if(e.restartRegistrationOffer===!0&&e.accountMode!==`register`)throw Error(`restartRegistrationOffer is only valid with register account mode`);let t=await df({url:i(e.relayUrl,`/auth/google/verify`),fetchImpl:e.fetchImpl,publishableKey:Z(e.publishableKey,`publishableKey`),body:{id_token:Z(e.idToken,`idToken`),account_mode:e.accountMode,project_environment_id:Z(e.projectEnvironmentId,`projectEnvironmentId`),...e.loginWalletId?{wallet_id:Z(e.loginWalletId,`loginWalletId`)}:{},...e.restartRegistrationOffer===!0?{restart_registration_offer:!0}:{}}}),n=Z(t.mode,`auth/google/verify mode`),r=Z(t.walletId,`auth/google/verify walletId`),a=Z(t.providerSubject,`auth/google/verify providerSubject`),o=sf(t.email);if(n===`existing_wallet`){if(t.hasEmailOtpEnrollment!==!0)throw Error(`auth/google/verify existing wallet is missing Email OTP enrollment`);if(!o)throw Error(`auth/google/verify existing wallet is missing email`);return{mode:n,walletId:r,providerSubject:a,email:o,hasEmailOtpEnrollment:!0}}if(n!==`register_started`)throw Error(`auth/google/verify returned unsupported mode: ${n}`);if(!o)throw Error(`auth/google/verify registration is missing email`);let s=of(t.offer,`auth/google/verify offer`),c=(Array.isArray(s.candidates)?s.candidates:[]).map(pf),l=c[0];if(!l)throw Error(`auth/google/verify offer has no wallet candidates`);return{mode:n,walletId:r,providerSubject:a,email:o,registrationAttemptId:Z(t.registrationAttemptId,`auth/google/verify registrationAttemptId`),expiresAtMs:mf(t.expiresAtMs,`auth/google/verify expiresAtMs`),offer:{offerId:Z(s.offerId,`auth/google/verify offer.offerId`),selectedCandidateId:Z(s.selectedCandidateId,`auth/google/verify offer.selectedCandidateId`),candidates:[l,...c.slice(1)]}}}function pf(e){let t=of(e,`auth/google/verify offer candidate`);return{candidateId:Z(t.candidateId,`offer candidate candidateId`),walletId:Z(t.walletId,`offer candidate walletId`)}}function mf(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<=Date.now())throw Error(`${t} must be a future timestamp`);return n}async function hf(e){let t=e.operation??`wallet_unlock`;if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpChallenge`,payload:{relayUrl:Z(e.relayUrl,`relayUrl`),walletId:Z(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Z(e.walletAuthMethodId,`walletAuthMethodId`)}:{},routePlan:lf({routeFamily:`login`,operation:t}),otpChannel:Ke,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}});let n=await df({url:i(e.relayUrl,`/wallet/email-otp/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Z(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Z(e.walletAuthMethodId,`walletAuthMethodId`)}:{},otpChannel:e.otpChannel||`email_otp`,operation:t,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}),r=of(n.challenge,`wallet/email-otp/challenge`);uf({challenge:r,expectedAction:Ve.login,context:`wallet/email-otp/challenge`});let a=Ht(n.delivery,`wallet/email-otp/challenge delivery`),o=Number(r.expiresAtMs),s={challengeId:Z(r.challengeId,`wallet/email-otp/challenge challengeId`),otpChannel:Ke,delivery:a,emailHint:a.emailHint,ownerProofBindingDigest:Z(r.ownerProofBindingDigest,`wallet/email-otp/challenge ownerProofBindingDigest`),walletAuthMethodId:Z(n.walletAuthMethodId,`wallet/email-otp/challenge walletAuthMethodId`),signerSelection:nf(n.signerSelection)};return Number.isFinite(o)&&(s.expiresAtMs=o),s}async function gf(e){if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpEnrollmentChallenge`,payload:{relayUrl:Z(e.relayUrl,`relayUrl`),walletId:Z(e.walletId,`walletId`),routePlan:lf({routeFamily:`registration`}),otpChannel:Ke}}});let t=await df({url:i(e.relayUrl,`/wallet/email-otp/registration/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Z(e.walletId,`walletId`),otpChannel:e.otpChannel||`email_otp`}}),n=of(t.challenge,`wallet/email-otp/registration/challenge`);uf({challenge:n,expectedAction:Ve.registration,context:`wallet/email-otp/registration/challenge`});let r=Ht(t.delivery,`wallet/email-otp/registration/challenge delivery`),a=Number(n.expiresAtMs),o={challengeId:Z(n.challengeId,`wallet/email-otp/registration/challenge challengeId`),otpChannel:Ke,delivery:r,emailHint:r.emailHint};return Number.isFinite(a)&&(o.expiresAtMs=a),o}function _f(e,t){let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`${t} is required for Email OTP registration authority`);return n}async function vf(e){let t=_f(e.authMethod.email,`email`).toLowerCase(),n=_f(e.authMethod.providerSubject,`providerSubject`),r=_f(e.relayUrl,`relayUrl`),i=_f(e.walletId,`walletId`),a=_f(e.registrationIntentDigestB64u,`registrationIntentDigestB64u`);if(e.authMethod.proofKind===`google_sso_registration`){let r=_f(e.authMethod.googleEmailOtpRegistrationAttemptId,`googleEmailOtpRegistrationAttemptId`);return{kind:`email_otp`,proof:{version:`email_otp_registration_proof_v1`,proofKind:`google_sso_registration`,providerSubject:n,email:t,googleEmailOtpRegistrationAttemptId:r,googleEmailOtpRegistrationOfferId:_f(e.authMethod.googleEmailOtpRegistrationOfferId,`googleEmailOtpRegistrationOfferId`),googleEmailOtpRegistrationCandidateId:_f(e.authMethod.googleEmailOtpRegistrationCandidateId,`googleEmailOtpRegistrationCandidateId`),registrationIntentDigestB64u:a},registrationAuthorityId:r,providerSubject:n,email:t}}let o=_f(e.authMethod.otpCode,`otpCode`),s=typeof e.authMethod.challengeId==`string`?e.authMethod.challengeId.trim():``,c=s?null:await gf({relayUrl:r,walletId:i,fetchImpl:e.fetchImpl}),l=s||_f(c?.challengeId,`challengeId`);return{kind:`email_otp`,proof:{version:`email_otp_registration_proof_v1`,proofKind:`otp_challenge`,providerSubject:n,email:t,challengeId:l,otpCode:o,otpChannel:Ke,registrationIntentDigestB64u:a},registrationAuthorityId:l,providerSubject:n,email:t}}function yf(e,t,n){if(e!==t)throw Error(`${n} does not match the verified add-signer intent`)}function bf(e,t){if(e.length!==2||e[0]!==t[0]||e[1]!==t[1])throw Error(`Yao participant IDs do not match the verified add-signer intent`)}function xf(e){let t=w(e.verifiedIntent.addSignerIntentGrant,`add-signer intent grant`);return{routerOrigin:w(e.httpTransport.routerOrigin,`Yao Router origin`),routing:{kind:`discovery`},authorization:{kind:`bearer`,value:`Bearer ${t}`},fetch:e.httpTransport.fetch}}async function Sf(e){let t=e.verifiedIntent.intent,n=t.signerSelection.ed25519;yf(String(t.walletId),String(e.verifiedAuthority.walletId),`Passkey authority wallet ID`),yf(e.verifiedIntent.addSignerIntentDigestB64u,e.verifiedAuthority.addSignerIntentDigestB64u,`Passkey authority intent digest`),w(e.verifiedAuthority.credentialIdB64u,`passkey credential ID`);let r=I(t.runtimePolicyScope),i=F(r),a=Pt(e.admissionRequest);if(!a.ok)throw Error(a.message);let o=a.value,s=w(e.verifiedIntent.addSignerCeremonyId,`add-signer ceremony ID`);if(yf(o.scope.lifecycle_id,s,`Yao lifecycle ID`),yf(o.scope.threshold_session_id,s,`Yao Threshold Session ID`),yf(o.scope.account_id,String(t.walletId),`Yao account ID`),yf(o.scope.signer_set_id,String(Oe(n.signerSlot)),`Yao signer-set ID`),yf(o.scope.root_share_epoch,r.signingRootVersion,`Yao root-share epoch`),yf(o.application_binding.wallet_id,String(t.walletId),`Yao application wallet ID`),yf(o.application_binding.signing_root_id,i,`Yao signing-root ID`),o.application_binding.key_creation_signer_slot!==n.signerSlot)throw Error(`Yao signer slot does not match the verified add-signer intent`);bf(n.participantIds,o.participant_ids);let c=await Xt({kind:`wallet_add_signer_implicit_near_ed25519_key_v1`,walletId:t.walletId,signingRootId:i,signingRootVersion:r.signingRootVersion,signerSlot:n.signerSlot,participantIds:n.participantIds,keyPurpose:n.keyPurpose,keyVersion:n.keyVersion,derivationVersion:n.derivationVersion});return yf(o.application_binding.near_ed25519_signing_key_id,String(c),`Yao NEAR signing-key ID`),{kind:`prepared_passkey_ed25519_yao_add_signer_v1`,request:o,transportConfig:xf(e)}}async function Cf(e){let t=await Sf(e),n=await new ra(t.transportConfig).send({kind:`admit`,path:At,body:t.request});if(!n.ok)throw Error(n.message);let r=Rt(n.value);if(!r.ok)throw Error(r.message);return{request:t.request,receipt:r.value}}var wf=class e{kind=`restorable_mpc_material_ref`;durableMaterialRef;protocolProof=!0;constructor(e){this.durableMaterialRef=e,this.protocolProof}static build(t){let n=String(t||``).trim();if(!n)throw Error(`Restorable MPC material reference is required`);return new e(n)}};function Tf(e){return wf.build(e)}const Ef=`router_ab_ed25519_yao_active_client_v1`,Df=`chacha20poly1305-hkdf-sha256-prf-first-v1`,Of=(1n<<64n)-1n;function Q(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required for local Ed25519 material`);return n}function kf(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<1)throw Error(`${t} must be a positive safe integer`);return n}function Af(e,t){let n=s(e);if(!n.ok)throw Error(`${t}: ${n.error.message}`);return n.value}function jf(e,t){let n=Q(e,t);if(R(n).length!==32)throw Error(`${t} must encode 32 bytes`);return n}function Mf(e){if(!Array.isArray(e)||e.length!==2)throw Error(`participantIds must contain exactly two entries`);let t=[kf(e[0],`participantIds[0]`),kf(e[1],`participantIds[1]`)];if(t[0]>65535||t[1]>65535||t[0]===t[1])throw Error(`participantIds must contain two distinct u16 identifiers`);return t}function Nf(e,t){let n=Q(e,t);if(!/^(0|[1-9][0-9]*)$/.test(n)||BigInt(n)>Of)throw Error(`${t} must be a canonical u64`);return n}function Pf(e,t,n){let r=e.signingLane.identity.signer;return{walletId:Q(r.account.wallet.walletId,`walletId`),nearAccountId:Q(r.account.nearAccountId,`nearAccountId`),nearEd25519SigningKeyId:Q(r.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),thresholdSessionId:Af(e.signingLane.identity.thresholdSessionId,`thresholdSessionId`),signerSlot:kf(r.signerSlot,`signerSlot`),rpId:Q(t,`rpId`),credentialIdB64u:Q(n,`credentialIdB64u`),signingRootId:Q(e.signingRootId,`signingRootId`),signingRootVersion:Q(e.signingRootVersion,`signingRootVersion`),signingWorkerId:Q(e.routerAbNormalSigning.signingWorkerId,`signingWorkerId`)}}function Ff(e){let t=e.metadata;if(t.scope.account_id!==e.identity.walletId||t.applicationBinding.wallet_id!==e.identity.walletId||t.applicationBinding.near_ed25519_signing_key_id!==e.identity.nearEd25519SigningKeyId||t.scope.threshold_session_id!==e.identity.thresholdSessionId||t.applicationBinding.key_creation_signer_slot!==e.identity.signerSlot||t.applicationBinding.signing_root_id!==e.identity.signingRootId||t.scope.root_share_epoch!==e.identity.signingRootVersion||t.scope.signing_worker_id!==e.identity.signingWorkerId)throw Error(`Active Ed25519 Client metadata does not match the wallet signing lane`);return{kind:Ef,walletId:e.identity.walletId,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot,rpId:e.identity.rpId,credentialIdB64u:e.identity.credentialIdB64u,lifecycleId:Q(t.scope.lifecycle_id,`lifecycleId`),thresholdSessionId:Af(t.scope.threshold_session_id,`thresholdSessionId`),materialActivation:tr(t),signingRootId:e.identity.signingRootId,signingRootVersion:e.identity.signingRootVersion,signerSetId:Q(t.scope.signer_set_id,`signerSetId`),signingWorkerId:e.identity.signingWorkerId,participantIds:[t.participantIds[0],t.participantIds[1]],registeredPublicKeyB64u:L(t.registeredPublicKey),signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare),stateEpoch:t.stateEpoch.toString(10),activationTranscriptB64u:L(t.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(t.activeCapabilityBinding))}}function If(e){return new TextEncoder().encode(JSON.stringify([e.kind,e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,e.rpId,e.credentialIdB64u,e.lifecycleId,e.thresholdSessionId,e.materialActivation.kind,e.materialActivation.activationId,e.materialActivation.capability,e.materialActivation.materialOwner,e.materialActivation.keyBinding,e.materialActivation.lifecycleBinding,e.materialActivation.signingWorker,e.signingRootId,e.signingRootVersion,e.signerSetId,e.signingWorkerId,e.participantIds[0],e.participantIds[1],e.registeredPublicKeyB64u,e.signingWorkerVerifyingShareB64u,e.stateEpoch,e.activationTranscriptB64u,e.activationCapabilityBindingB64u]))}function Lf(e,t){if(e.walletId!==t.walletId||e.nearAccountId!==t.nearAccountId||e.nearEd25519SigningKeyId!==t.nearEd25519SigningKeyId||e.signerSlot!==t.signerSlot||e.rpId!==t.rpId||e.credentialIdB64u!==t.credentialIdB64u||e.signingRootId!==t.signingRootId||e.signingRootVersion!==t.signingRootVersion||e.signingWorkerId!==t.signingWorkerId)throw Error(`Stored Ed25519 Client material does not match the wallet signing lane`)}function Rf(e){let t=C(e);if(!t||t.kind!==Ef)throw Error(`Stored Ed25519 Client material binding is invalid`);let n=l(t.materialActivation);if(!n.ok)throw Error(n.error.message);let r={kind:Ef,walletId:Q(t.walletId,`binding.walletId`),nearAccountId:Q(t.nearAccountId,`binding.nearAccountId`),nearEd25519SigningKeyId:Q(t.nearEd25519SigningKeyId,`binding.nearEd25519SigningKeyId`),signerSlot:kf(t.signerSlot,`binding.signerSlot`),rpId:Q(t.rpId,`binding.rpId`),credentialIdB64u:Q(t.credentialIdB64u,`binding.credentialIdB64u`),lifecycleId:Q(t.lifecycleId,`binding.lifecycleId`),thresholdSessionId:Af(t.thresholdSessionId,`binding.thresholdSessionId`),materialActivation:n.value,signingRootId:Q(t.signingRootId,`binding.signingRootId`),signingRootVersion:Q(t.signingRootVersion,`binding.signingRootVersion`),signerSetId:Q(t.signerSetId,`binding.signerSetId`),signingWorkerId:Q(t.signingWorkerId,`binding.signingWorkerId`),participantIds:Mf(t.participantIds),registeredPublicKeyB64u:jf(t.registeredPublicKeyB64u,`binding.registeredPublicKeyB64u`),signingWorkerVerifyingShareB64u:jf(t.signingWorkerVerifyingShareB64u,`binding.signingWorkerVerifyingShareB64u`),stateEpoch:Nf(t.stateEpoch,`binding.stateEpoch`),activationTranscriptB64u:jf(t.activationTranscriptB64u,`binding.activationTranscriptB64u`),activationCapabilityBindingB64u:jf(t.activationCapabilityBindingB64u,`binding.activationCapabilityBindingB64u`)};if(r.materialActivation.materialOwner!==r.walletId||r.materialActivation.signingWorker!==r.signingWorkerId)throw Error(`Stored Ed25519 Client material activation does not match its binding`);return r}function zf(e,t){let n=Rf(e);return Lf(n,t),n}function Bf(e){let t=C(e);if(!t)throw Error(`Stored Ed25519 Client stable server scope is invalid`);let n=ae(t.runtimePolicyScope);if(!n)throw Error(`Stored Ed25519 Client server runtime policy scope is invalid`);return{relayerKeyId:Q(t.relayerKeyId,`stableServerScope.relayerKeyId`),participantIds:Mf(t.participantIds),runtimePolicyScope:n,routerAbNormalSigning:ce(t.routerAbNormalSigning)}}async function Vf(e){let t=e.stored.payload,n=C(t);if(!n)throw Error(`Stored Ed25519 Client local material locator is invalid`);let r=Rf(n.binding),i=`ed25519:${Ee(R(r.registeredPublicKeyB64u))}`,a=e.stored.payloadEnvelope;if(e.stored.profileId!==e.target.profileId||e.stored.chainIdKey!==e.target.chainIdKey||e.stored.accountAddress!==e.target.accountAddress||e.stored.keyKind!==Ef||e.stored.schemaVersion!==3||e.stored.publicKey!==i||e.stored.signerId!==r.nearEd25519SigningKeyId||a?.encVersion!==1||a.alg!==Df)throw Error(`Stored Ed25519 Client local material record is invalid`);let o=xt({walletId:r.walletId,factor:{kind:`passkey`,credentialIdB64u:r.credentialIdB64u},verifier:{kind:`webauthn`,rpId:r.rpId},bindingId:e.authority.walletAuthMethodId});if(!o)throw Error(`Stored Ed25519 Client local material authority is invalid`);let s=await ct({authority:o});if(s.authorityDigest!==e.authority.authorityDigest)throw Error(`Stored Ed25519 Client local material authority changed`);return{kind:`passkey_ed25519_yao_local_material_locator_v1`,authority:s,materialActivation:r.materialActivation,sealedMaterial:Tf(JSON.stringify([e.stored.profileId,e.stored.signerSlot,e.stored.chainIdKey,e.stored.keyKind,r.materialActivation.activationId])),stableServerScope:Bf(n.stableServerScope)}}function Hf(e){let t=C(e.stored.payload?.binding);if(e.stored.profileId!==e.target.profileId||e.stored.chainIdKey!==e.target.chainIdKey||e.stored.accountAddress!==e.target.accountAddress||e.stored.signerSlot!==e.input.signerSlot||e.stored.signerId!==e.input.nearEd25519SigningKeyId||e.stored.keyKind!==Ef||t?.kind!==Ef||t.walletId!==e.input.walletId||t.nearAccountId!==e.input.nearAccountId||t.nearEd25519SigningKeyId!==e.input.nearEd25519SigningKeyId||t.signerSlot!==e.input.signerSlot||t.rpId!==e.input.rpId||t.credentialIdB64u!==e.input.credentialIdB64u)throw Error(`Stored Ed25519 Client material locator does not match local custody`)}function Uf(e,t){let n=Q(t,`thresholdSessionId`);return{kind:Ni,scope:{lifecycle_id:e.lifecycleId,root_share_epoch:e.signingRootVersion,account_id:e.walletId,threshold_session_id:n,signer_set_id:e.signerSetId,signing_worker_id:e.signingWorkerId,material_activation:wt(e.materialActivation)},applicationBinding:{wallet_id:e.walletId,near_ed25519_signing_key_id:e.nearEd25519SigningKeyId,signing_root_id:e.signingRootId,key_creation_signer_slot:e.signerSlot},participantIds:e.participantIds,registeredPublicKey:R(e.registeredPublicKeyB64u),signingWorkerVerifyingShare:R(e.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(e.stateEpoch),transcript:R(e.activationTranscriptB64u),activeCapabilityBinding:Array.from(R(e.activationCapabilityBindingB64u)),materialActivation:e.materialActivation}}function Wf(){let e=new Uint8Array(12);return globalThis.crypto.getRandomValues(e),e}function Gf(e){let t=e.identity,n=e.activeClient.metadata(),r=Ff({identity:t,metadata:n}),i=Wf(),a=e.activeClient.sealLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:If(r),nonce:i}),o={binding:r,stableServerScope:e.stableServerScope};switch(e.lifecycle.kind){case`registration_or_rehydration`:break;case`recovery_promotion`:o.lifecycleReceipt=e.lifecycle.promotionReceipt;break;default:e.lifecycle}return{profileId:e.target.profileId,signerSlot:t.signerSlot,chainIdKey:e.target.chainIdKey,accountAddress:e.target.accountAddress,keyKind:Ef,algorithm:`ed25519`,publicKey:`ed25519:${Ee(n.registeredPublicKey)}`,signerId:t.nearEd25519SigningKeyId,payload:o,payloadEnvelope:{encVersion:1,alg:Df,nonce:L(a.nonce),ciphertext:L(a.ciphertext),aad:Ze({profileId:e.target.profileId,signerSlot:t.signerSlot,chainIdKey:e.target.chainIdKey,accountAddress:e.target.accountAddress,keyKind:Ef,schemaVersion:3,signerId:t.nearEd25519SigningKeyId})},timestamp:Date.now(),schemaVersion:3}}async function Kf(e){let t=await bn(e.store,{accountRefs:Bn(e.identity.nearAccountId)});if(!t)throw Error(`Local Ed25519 material requires a persisted wallet profile`);let n=Gf({target:t,activeClient:e.activeClient,identity:e.identity,stableServerScope:e.stableServerScope,ownedPasskeyPrfFirst:R(e.passkeyPrfFirstB64u),lifecycle:{kind:`registration_or_rehydration`}});await e.store.storeKeyMaterial(n)}async function qf(e){let t=Q(e.nearAccountId,`nearAccountId`),n=await bn(e.store,{accountRefs:Bn(t)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,kf(e.signerSlot,`signerSlot`),n.chainIdKey,Ef);return r?(Hf({stored:r,target:n,input:e}),{kind:`available`,locator:await Vf({stored:r,target:n,authority:e.authority})}):{kind:`unavailable`}}function Jf(e){return e.publicLocator.walletId===e.identity.walletId&&e.publicLocator.nearAccountId===e.identity.nearAccountId&&e.publicLocator.signerSlot===e.identity.signerSlot}async function Yf(e){let t=xt({walletId:e.identity.walletId,factor:{kind:`passkey`,credentialIdB64u:e.identity.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.identity.rpId},bindingId:e.authority.walletAuthMethodId});if(!t)throw Error(`Passkey Ed25519 authority is invalid`);let n=await ct({authority:t});if(n.authorityDigest!==e.authority.authorityDigest)throw Error(`Passkey Ed25519 authority does not match the Wallet Session`);return n}function Xf(e){if(!e||e.activeClient.status().kind!==`active`)return{kind:`absent`};let t=tr(e.activeClient.metadata());return{kind:`live`,runtime:Zn(t),materialActivation:t}}function Zf(e){return{kind:`blocked`,plan:e}}async function Qf(e){let t=await Yf(e),n=e.publicLocator.kind===`available`&&!Jf({publicLocator:e.publicLocator,identity:e.identity})?{kind:`conflict`}:e.publicLocator.kind===`available`?{...e.publicLocator,authority:t}:e.publicLocator,r;try{r=await qf({store:e.store,walletId:String(e.identity.walletId),nearAccountId:String(e.identity.nearAccountId),nearEd25519SigningKeyId:String(e.identity.nearEd25519SigningKeyId),signerSlot:e.identity.signerSlot,rpId:e.identity.rpId,credentialIdB64u:e.identity.credentialIdB64u,authority:t})}catch{return{expectedAuthority:t,publicLocator:n,sealed:{kind:`corrupt`}}}return{expectedAuthority:t,publicLocator:n,sealed:r.kind===`available`?{kind:`available`,authority:r.locator.authority,materialActivation:r.locator.materialActivation,sealedMaterial:r.locator.sealedMaterial}:{kind:`missing`}}}function $f(e,t){let n=$n({publicLocator:e,sealed:{kind:`corrupt`},runtime:t,unlockSource:{kind:`unavailable`}});if(n.kind!==`blocked`)throw Error(`Corrupt Near Ed25519 material resolved to an executable hydration plan`);return n}async function ep(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await Qf(e);if(r.kind===`corrupt`)return{kind:`blocked`,plan:$f(n,{kind:`absent`})};let i=$n({publicLocator:n,sealed:r,runtime:{kind:`absent`},unlockSource:{kind:`available`,authority:t}});switch(i.kind){case`rehydrate_material_activation`:return{kind:`prepared`,plan:i};case`blocked`:return{kind:`blocked`,plan:i};case`use_live_runtime`:case`reauthorize_public_anchor`:throw Error(`Sealed Near Ed25519 preparation resolved an invalid hydration plan`);default:throw Error(`Unsupported sealed Near Ed25519 preparation plan`)}}async function tp(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await Qf(e);if(r.kind===`corrupt`)return Zf($f(n,Xf(e.liveMaterial)));let i=e.unlockSource.kind===`available`?{kind:`available`,authority:t}:{kind:`unavailable`},a=$n({publicLocator:n,sealed:r,runtime:Xf(e.liveMaterial),unlockSource:i});switch(a.kind){case`use_live_runtime`:{let t=e.liveMaterial;if(!t||t.activeClient.status().kind!==`active`||!p(a.materialActivation,tr(t.activeClient.metadata())))throw Error(`Near Ed25519 live hydration plan lost its exact runtime`);return{kind:`live`,plan:a}}case`rehydrate_material_activation`:{if(e.unlockSource.kind!==`available`)throw Error(`Near Ed25519 rehydration plan lost its unlock source`);let t=await np({store:e.store,identity:e.identity,passkeyPrfFirstB64u:e.unlockSource.passkeyPrfFirstB64u});if(t.kind!==`rehydrated`)throw Error(`Near Ed25519 rehydration plan lost its sealed material`);let n=tr(t.activeClient.metadata());if(!p(a.materialActivation,n))throw t.activeClient.dispose(),Error(`Near Ed25519 rehydration changed the material activation`);return{kind:`rehydrated`,plan:a,activeClient:t.activeClient}}case`blocked`:return Zf(a);case`reauthorize_public_anchor`:throw Error(`Near Ed25519 material retirement requires explicit reauthorization`);default:throw Error(`Unsupported Near Ed25519 hydration plan`)}}async function np(e){let t=e.identity,n=await bn(e.store,{accountRefs:Bn(t.nearAccountId)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,t.signerSlot,n.chainIdKey,Ef);return r?rp({stored:r,target:n,identity:t,ownedPasskeyPrfFirst:R(e.passkeyPrfFirstB64u)}):{kind:`unavailable`}}async function rp(e){let t=e.identity,n=e.stored,r=e.target,i=n.payloadEnvelope;if(n.profileId!==r.profileId||n.accountAddress!==r.accountAddress||n.signerId!==t.nearEd25519SigningKeyId||n.keyKind!==Ef||n.schemaVersion!==3||i?.encVersion!==1||i.alg!==Df)throw Error(`Stored Ed25519 Client material record is invalid`);let a=zf(n.payload?.binding,t),o=Uf(a,t.thresholdSessionId),s=`ed25519:${Ee(o.registeredPublicKey)}`;if(n.publicKey!==s)throw Error(`Stored Ed25519 Client public key does not match its sealed binding`);return{kind:`rehydrated`,activeClient:(await ua.initializeBundled()).importLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:If(a),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:R(i.nonce),ciphertext:R(i.ciphertext)},metadata:o})}}function ip(e,t){return e.requestWorkerOperation(t)}function ap(e,t,n){return e.requestOperation({kind:`walletCustodyCeremony`,request:{type:t,payload:n}})}function op(e){return ap.bind(void 0,e)}let sp=null,cp=null,lp=null,up=null;function dp(e){up=e}function fp(e){let t=up;if(!t||e.kind!==`unlocked_wallet_ed25519_export_root_capability_v1`)return;let n=e.upgradedEnvelope;if(n!==void 0)try{t({walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,walletSessionId:e.walletSessionId,envelope:n})}catch(e){console.warn(`[walletCustody] the upgraded custody envelope was not forwarded:`,e instanceof Error?e.message:String(e||`unknown error`))}}function pp(e){return{requestOperation:ip.bind(void 0,e)}}function mp(){lp!==null&&(clearTimeout(lp),lp=null)}function hp(){mp(),sp=null,cp=null}function gp(e,t){mp();let n=Math.max(0,e.expiresAtMs-Date.now());lp=setTimeout(()=>{if(lp=null,!(sp!==e||cp!==t)){if(e.expiresAtMs>Date.now()){gp(e,t);return}Cp(t,{kind:`capability`,capabilityHandleId:e.capabilityHandleId})}},Math.min(n,2147483647))}function _p(e){if(!_(e))return null;if(e.kind===`unlocked_linked_device_ed25519_client_root_capability_v1`)return vp(e);let t=Object.keys(e),n=t.includes(`upgradedEnvelope`),r=n?[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`,`upgradedEnvelope`]:[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`];if(t.length!==r.length||t.some(e=>!r.includes(e))||e.kind!==`unlocked_wallet_ed25519_export_root_capability_v1`)return null;let i=u(e.capabilityHandleId),o=a(e.walletId),s=c(e.walletAuthMethodId),l=_e(e.walletSessionId);if(!i.ok||!o.ok||!s.ok||!l.ok)return null;let d;try{d=P(e.expiresAtMs,`unlocked Ed25519 export-root capability expiry`)}catch{return null}let f;if(n)try{f=$t(e.upgradedEnvelope)}catch{}return{kind:`unlocked_wallet_ed25519_export_root_capability_v1`,capabilityHandleId:i.value,walletId:o.value,walletAuthMethodId:s.value,walletSessionId:l.value,expiresAtMs:d,...f?{upgradedEnvelope:f}:{}}}function vp(e){let t=[`kind`,`capabilityHandleId`,`walletId`,`walletAuthMethodId`,`walletSessionId`,`expiresAtMs`],n=Object.keys(e);if(n.length!==t.length||n.some(e=>!t.includes(e)))return null;let r=u(e.capabilityHandleId),i=a(e.walletId),o=c(e.walletAuthMethodId),s=_e(e.walletSessionId);if(!r.ok||!i.ok||!o.ok||!s.ok)return null;let l;try{l=P(e.expiresAtMs,`unlocked Ed25519 Client-root capability expiry`)}catch{return null}return{kind:`unlocked_linked_device_ed25519_client_root_capability_v1`,capabilityHandleId:r.value,walletId:i.value,walletAuthMethodId:o.value,walletSessionId:s.value,expiresAtMs:l}}async function yp(e,t){let n=t.existingEnvelope.binding;if(!tn(n)&&n.kind!==`ed25519_yao_client_root_v1`)return;let r=t.existingFactorSecret.slice(),i;try{i=await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`establishUnlockedWalletEd25519ExportRootCapability`,payload:{existingEnvelope:t.existingEnvelope,existingFactorSecret:r.buffer,walletId:t.walletId,walletAuthMethodId:t.walletAuthMethodId,walletSessionId:t.walletSessionId,expiresAtMs:t.expiresAtMs},transfer:[r.buffer]}})}finally{r.byteLength>0&&r.fill(0)}let a=_p(i);if(a===null)throw Error(`unlocked Ed25519 export-root capability worker returned no reference`);return mp(),sp=a,cp=e,gp(a,e),fp(a),a}function bp(e){let t=xp(e);return t?.kind===`unlocked_wallet_ed25519_export_root_capability_v1`?t:void 0}function xp(e){let t=sp;if(t&&t.walletId===e){if(t.expiresAtMs<=Date.now()){let e=cp;e?Cp(e,{kind:`capability`,capabilityHandleId:t.capabilityHandleId}):hp();return}return t}}function Sp(){hp()}async function Cp(e,t){let n=sp;n!==null&&(t.kind===`all`||t.kind===`capability`&&t.capabilityHandleId===n.capabilityHandleId||t.kind===`wallet`&&t.walletId===n.walletId||t.kind===`wallet_session`&&t.walletSessionId===n.walletSessionId)&&hp();try{await e.requestOperation({kind:`walletCustodyCeremony`,request:{type:`destroyUnlockedWalletEd25519ExportRootCapabilities`,payload:{scope:t}}})}catch{}}function wp(e){let t=r(e);if(!t.ok)throw Error(t.error.message);return t.value}function Tp(e){let t=e.finalized.authMethod;if(!t||t.kind!==`passkey`)throw Error(`Passkey registration finalize returned non-passkey auth material`);let n=String(e.credential.rawId||e.credential.id||``).trim(),r=String(t.credentialIdB64u||``).trim();if(!n||r!==n)throw Error(`Passkey registration finalize returned credential id mismatch`);let i=String(t.credentialPublicKeyB64u||``).trim();if(!i)throw Error(`Passkey registration finalize returned missing credentialPublicKeyB64u`);return i}async function Ep(e){let t=e.configs.signing.emailOtp.authPolicy;return lr({policy:t,retention:`session`,reason:`login`,authority:e.authority})}async function Dp(e){switch(e.authMethod.kind){case`passkey`:if(!e.passkeyAuthority)throw Error(`Passkey registration authority was not collected`);return{kind:`passkey`,rpId:e.authMethod.rpId,credential:e.passkeyAuthority.credential,credentialPublicKeyB64u:Tp({finalized:e.finalized,credential:e.passkeyAuthority.credential})};case`email_otp`:{let t=String(e.email||``).trim(),n=String(e.providerSubject||``).trim(),r=String(e.registrationAuthorityId||``).trim();if(!t||!n||!r)throw Error(`Email OTP registration persistence requires provider identity`);if(!it(e.finalized.authority))throw Error(`Email OTP registration finalize returned a different authority`);if(e.finalized.foundingAuthMethod.kind!==`email_otp`)throw Error(`Email OTP registration finalize returned a different founding method`);let i=lt({...e.finalized.authority,bindingId:e.finalized.foundingAuthMethod.walletAuthMethodId});if(!i)throw Error(`Email OTP registration finalize returned an invalid exact authority`);return{kind:`email_otp`,email:t,registrationAuthorityId:r,emailOtpAuthContext:await Ep({configs:e.configs,authority:i}),authority:i}}default:return q(e.authMethod)}}function Op(e){let[t,...n]=e.walletKeys,[r,...i]=e.expectedChainTargets;if(!t||!r)throw Error(`ECDSA registration persistence requires session, key, and target material`);if(e.walletKeys.length!==e.expectedChainTargets.length)throw Error(`ECDSA registration persistence requires one family session projected to every target`);if(e.session.chainTargets.length!==e.expectedChainTargets.length||!Rc(e.session.chainTargets,e.expectedChainTargets))throw Error(`ECDSA registration family session target projection is incomplete`);return Fc(e.walletKeys),Ic({session:e.session,walletKeys:e.walletKeys}),qc({session:e.session,walletKeys:e.walletKeys}),{kind:`evm_family_ecdsa`,session:e.session,walletKeys:[t,...n],expectedChainTargets:[r,...i]}}function kp(e){let{walletId:t,authority:n,foundingAuthority:r,foundingAuthMethod:i,registrationDiagnostics:a,rpId:o,authMethod:s,custodyKeyManifestDigestB64u:c,ecdsa:l}=e,{activation:u,bootstrap:d,...f}=l,p={ok:!0,walletId:t,authority:n,foundingAuthority:r,foundingAuthMethod:i,...a?{registrationDiagnostics:a}:{},...c===void 0?{}:{custodyKeyManifestDigestB64u:c},kind:`evm_family_ecdsa`,ecdsa:f};if(s.kind===`passkey`){if(!o)throw Error(`Passkey activation is missing its relying-party id`);return{...p,rpId:o,authMethod:s}}if(o!==void 0)throw Error(`Email OTP activation returned a relying-party id`);return{...p,authMethod:s}}function Ap(e){return{kind:`registration_persistence_plan_v1`,walletId:e.walletId,auth:e.auth,ecdsa:e.ecdsa,foundingAuthority:e.foundingAuthority,foundingAuthMethod:e.foundingAuthMethod}}function jp(e){let t=En(e);if(!t)throw Error(`pending wallet registration commit is invalid`);return t}function Mp(e){let t=Ie(e.walletId),n=c(e.walletAuthMethodId);if(!n.ok)throw Error(n.error.message);let r=Np(e.auth),i={kind:`pending_wallet_registration_commit_v1`,registrationCeremonyId:Pp(e.registrationCeremonyId,`registrationCeremonyId`),idempotencyKey:Pp(e.idempotencyKey,`idempotencyKey`),walletId:t,walletAuthMethodId:n.value,signedSetup:Pp(e.signedSetup,`signedSetup`),auth:r,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs};if(e.operation===`registration_activate`)return jp({...i,operation:e.operation,signerPlanKind:e.signerPlanKind,localMaterial:e.localMaterial});if(e.signerPlanKind!==`near_ed25519`&&e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`near provisioning requires a NEAR signer plan`);return jp({...i,operation:e.operation,phase:`joined`,completion:e.completion,signerPlanKind:e.signerPlanKind,localMaterial:e.localMaterial})}function Np(e){if(e.kind===`passkey`){let t=wp(e.rpId),n=d(e.credentialIdB64u);if(!n.ok)throw Error(n.error.message);return{kind:`passkey`,rpId:t,credentialIdB64u:n.value,transports:[...e.transports]}}let t=h(e.email);if(!t.ok)throw Error(t.error.message);let n=f(e.registrationAuthorityId);if(!n.ok)throw Error(n.error.message);let r=m(e.providerSubject);if(!r.ok)throw Error(r.error.message);return{kind:`email_otp`,email:t.value,registrationAuthorityId:n.value,providerSubject:r.value,enrollment:{enrollmentSealKeyVersion:Pp(e.enrollment.enrollmentSealKeyVersion,`enrollment.enrollmentSealKeyVersion`),serverSealedFactorCiphertextB64u:Pp(e.enrollment.serverSealedFactorCiphertextB64u,`enrollment.serverSealedFactorCiphertextB64u`),clientUnlockPublicKeyB64u:Pp(e.enrollment.clientUnlockPublicKeyB64u,`enrollment.clientUnlockPublicKeyB64u`),unlockKeyVersion:Pp(e.enrollment.unlockKeyVersion,`enrollment.unlockKeyVersion`)}}}function Pp(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a non-empty canonical string`);return e}async function Fp(e){e.registrationTiming.record(`ecdsaRegistrationTargetCount`,e.plan.ecdsa.walletKeys.length);let t=performance.now();try{return await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ie(e.plan.walletId),session:e.plan.ecdsa.session,walletKeys:[...e.plan.ecdsa.walletKeys]})}finally{e.registrationTiming.record(`ecdsaRegistrationSessionFinalizeMs`,Ia(t))}}async function Ip(e){if(e.plan.auth.kind===`passkey`){await e.context.signingEngine.finalizeWalletEcdsaRegistration({walletId:e.plan.walletId,rpId:wp(e.plan.auth.rpId),credential:e.plan.auth.credential,credentialPublicKeyB64u:e.plan.auth.credentialPublicKeyB64u,walletKeys:e.walletKeys});return}await e.context.signingEngine.storeWalletEmailOtpEcdsaRegistrationData({walletId:e.plan.walletId,email:e.plan.auth.email,registrationAuthorityId:e.plan.auth.registrationAuthorityId,authority:e.plan.auth.authority,walletKeys:e.walletKeys})}async function Lp(e){let t=await Fp(e),n=performance.now();try{if(await Ip({context:e.context,plan:e.plan,walletKeys:t}),await V.persistFoundingWalletAuthority({authority:e.plan.foundingAuthority,authMethod:e.plan.foundingAuthMethod}),e.plan.auth.kind===`email_otp`){let t=h(e.plan.auth.email);if(!t.ok)throw Error(t.error.message);let n=await V.retainVerifiedEmailOtpLocalPresentation({walletId:e.plan.walletId,walletAuthMethodId:e.plan.foundingAuthMethod.walletAuthMethodId,emailAddress:t.value});if(n.kind!==`retained`)throw Error(`Verified Email OTP presentation was not retained: ${n.reason}`)}}finally{e.registrationTiming.record(`ecdsaRegistrationLocalRecordPersistenceMs`,Ia(n))}await yr(In,e.plan.ecdsa.session.registrationEstablishedSession)}function Rp(e){return Lp.bind(void 0,e)}async function zp(e){await e.registrationTiming.measure(`ecdsaRegistrationPersistenceMs`,Rp(e))}var Bp=e({REGISTRATION_TIMING_LABEL:()=>ya,addSigner:()=>ng,cancelHostedPasskeyRegistration:()=>Em,prepareHostedPasskeyRegistration:()=>Tm,registerPreparedHostedPasskeyRegistration:()=>Om,registerWallet:()=>Uh,resumeNearRegistrationAfterUnlock:()=>xh,startHostedPasskeyRegistrationCredential:()=>Dm});async function Vp(e,t,n,r){if(r.length!==10||new Set(r).size!==10)throw Error(`Wallet custody must issue exactly ten distinct recovery codes`);switch((await Hp({backup:n,context:e,request:{kind:`wallet_recovery_code_backup_request_v1`,walletId:t,recoveryCodes:r,continuation:`registration_may_defer`}}))?.kind){case`wallet_recovery_codes_backed_up_v1`:return;case`wallet_recovery_code_backup_deferred_v1`:await vr.write({walletId:t,recoveryCodes:r});return;default:throw Error(`Wallet recovery-code backup result is invalid`)}}async function Hp(e){if(!e.backup)return{kind:`wallet_recovery_code_backup_deferred_v1`};switch(e.backup.kind){case`defer_to_account_menu`:return{kind:`wallet_recovery_code_backup_deferred_v1`};case`show_builtin_dialog`:return await _r(e.request,e.context.signingEngine.getWalletIframeSurfaceMeasurementBinding());case`custom_handler`:return await e.backup.handler(e.request);default:return q(e.backup)}}function Up(e){e.byteLength>0&&new Uint8Array(e).fill(0)}function Wp(e){let t=e.established.metadata;return{binding:{kind:Qe,applicationBindingDigestB64u:e.established.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:L(t.registeredPublicKey),participantIds:t.participantIds,stateEpoch:String(t.stateEpoch),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,signingWorkerId:t.scope.signing_worker_id,signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:e.established.localMaterial.b64u,nonceB64u:e.established.localMaterial.nonceB64u}}}function Gp(e){let t=e.metadata;return{materialActivation:tr(t),registeredPublicKeyB64u:L(t.registeredPublicKey),signingWorkerVerifyingShareB64u:L(t.signingWorkerVerifyingShare),stateEpoch:String(t.stateEpoch),signingWorkerId:t.scope.signing_worker_id,participantIds:t.participantIds,nearEd25519SigningKeyId:t.applicationBinding.near_ed25519_signing_key_id,signerSlot:t.applicationBinding.key_creation_signer_slot}}function Kp(e){let t=e.establishedCustody;if(!t)throw Error(`Mixed registration custody commit is missing its established envelope`);return{bindingJson:t.envelopeBindingJson,nonceB64u:t.envelopeNonceB64u,ciphertextB64u:t.sealedCustodySecretB64u,aadHashB64u:t.envelopeAadHashB64u,ciphertextDigestB64u:t.envelopeCiphertextDigestB64u}}function qp(e){let t=e.commit.establishedCustody;if(!t)throw Error(`Passkey registration custody commit is missing its established envelope`);return Md({expectedWalletId:e.walletId,replacement:t,activatedAtMs:e.activatedAtMs})}async function Jp(e){await e.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:qp({commit:e.commit,walletId:e.walletId,activatedAtMs:Date.now()}),passkeyPrfFirstB64u:e.passkeyPrfFirstB64u,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,walletSessionId:e.walletSessionId,expiresAtMs:e.expiresAtMs})}async function Yp(e){try{await yp(pp(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:qp({commit:e.commit,walletId:e.walletId,activatedAtMs:Date.now()}),existingFactorSecret:e.factorSecret32,walletId:e.walletId,walletAuthMethodId:String(e.emailOtpAuthContext.authority.bindingId),walletSessionId:e.walletSessionId,expiresAtMs:e.expiresAtMs})}catch(e){console.warn(`[registration][email-otp] unlocked Ed25519 export-root capability was not established:`,e instanceof Error?e.message:String(e||`unknown error`))}}async function Xp(e){let t=qp(e);if(t.factor.kind!==`passkey`)throw Error(`Passkey registration custody commit has a non-passkey factor`);await Kd({walletId:e.walletId,credentialIdB64u:t.factor.credentialIdB64u,envelope:t})}function Zp(e){let t=e.joined.metadata,n=s(t.scope.threshold_session_id);if(!n.ok)throw Error(`Registration Ed25519 capability has an invalid threshold session`);return{kind:Bt,session:{walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,authorityScope:{kind:`email_otp`,provider:or(e.authContext),providerUserId:sr(e.authContext)},thresholdSessionId:n.value,authorizationId:e.sessionState.signingWalletSession.authorizationId,walletSessionId:e.sessionState.walletSessionId,quotaId:e.sessionState.quotaId,expiresAtMs:e.sessionState.signingWalletSession.expiresAtMs,participantIds:t.participantIds,remainingUses:e.sessionState.signingWalletSession.remainingUses,signingRootId:e.sessionState.signingRootId,signingRootVersion:e.sessionState.signingRootVersion,runtimePolicyScope:e.sessionState.runtimePolicyScope,routerAbNormalSigning:e.sessionState.routerAbNormalSigning},capability:{kind:`router_ab_ed25519_yao_active_capability_v1`,materialActivation:t.materialActivation,activeCapabilityBinding:t.activeCapabilityBinding,registeredPublicKey:[...t.registeredPublicKey],nearAccountId:e.nearAccountId,applicationBinding:t.applicationBinding,runtimePolicyScope:e.sessionState.runtimePolicyScope,participantIds:t.participantIds,lifecycle:{lifecycleId:t.scope.lifecycle_id,rootShareEpoch:t.scope.root_share_epoch,accountId:t.scope.account_id,thresholdSessionId:n.value,signerSetId:t.scope.signer_set_id,signingWorkerId:t.scope.signing_worker_id},stateEpoch:Number(t.stateEpoch),registrationContinuity:{kind:`registration`,admissionRequest:e.deferredNear.admissionRequest,admissionReceipt:e.admissionReceipt,activationTranscript:[...t.transcript]}}}}const Qp=Symbol(`hostedPasskeyRegistrationPrepared`),$p=new WeakMap;function em(e){let t=je(e);if(!t.ok)throw Error(t.message);return t.value}function tm(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function nm(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`implicit_account`:return t.kind===`implicit_account`&&e.accountIdSource===t.accountIdSource;case`sponsored_named_account`:return t.kind===`sponsored_named_account`&&e.requestedAccountId===t.requestedAccountId&&e.sponsor===t.sponsor;default:return q(e)}}function rm(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`near_ed25519`:return t.kind===`near_ed25519`&&nm(e.accountProvisioning,t.accountProvisioning)&&e.signerSlot===t.signerSlot&&tm(e.participantIds,t.participantIds)&&e.derivationVersion===t.derivationVersion;case`evm_family_ecdsa`:return t.kind===`evm_family_ecdsa`&&tm(e.participantIds,t.participantIds)&&Pe(e.chainTargets)===Pe(t.chainTargets);default:return q(e)}}function im(e,t){if(e.kind!==t.kind||e.signers.length!==t.signers.length)return!1;for(let n=0;n<e.signers.length;n+=1){let r=e.signers[n],i=t.signers[n];if(!r||!i||!rm(r,i))return!1}return!0}function am(e){return e.signingEngine.warmCriticalResources.bind(e.signingEngine,{kind:`none`})}function om(){return Promise.resolve($a())}function sm(e){return e.signers.some(e=>e.kind===`evm_family_ecdsa`)}function cm(e){return e.authMethod.kind!==`email_otp`||!Pr(e.signerSelection)?om:um.bind(void 0,{prewarm:e.context.signingEngine.prewarmEmailOtpYao.bind(e.context.signingEngine)})}function lm(e,t){let n=Ia(t);return{kind:`failed`,elapsedMs:n,workerPrewarmMs:n,yaoWasmInitMs:0,failureStage:`worker_ready`}}function um(e){let t=performance.now();return e.prewarm().catch(e=>lm(e,t))}function dm(e){let[t,n]=e;return{kind:`completed`,diagnostics:{...t,emailOtpWorkerPrewarmMs:n.workerPrewarmMs,emailOtpYaoWasmInitMs:n.yaoWasmInitMs,emailOtpYaoPrewarm:n}}}function fm(e){return{kind:`failed`,error:e}}function pm(e){Hn({relayerUrl:e.relayerUrl,nearEd25519:e.signerSelection.signers.some(e=>e.kind===`near_ed25519`),evmFamilyEcdsa:sm(e.signerSelection)}),Pr(e.signerSelection)&&Yc(e.authMethod,e.context.signingEngine.prewarmNearSigner.bind(e.context.signingEngine));let t=e.recorder.measure(`registrationWarmupMs`,am(e.context)),n=e.recorder.measure(`registrationWarmupEmailOtpYaoWasmInitMs`,cm({context:e.context,authMethod:e.authMethod,signerSelection:e.signerSelection}));return sm(e.signerSelection)&&e.context.signingEngine.prewarmEcdsaRegistrationCrypto?.().catch(()=>{}),Promise.all([t,n]).then(dm,fm)}function mm(e){e.warmup.then(t=>{t.kind===`completed`&&e.recorder.captureWarmupDiagnostics(t.diagnostics)})}function hm(e){return Ne(em(e))?.signerSlot??1}async function gm(e){return e.passkeyExecution?.kind===`use_hosted_preparation`?await e.passkeyExecution.authority:await Qd({context:e.context,walletId:e.walletId,signerSlot:e.signerSlot,registrationIntentDigestB64u:e.registrationIntentDigestB64u,options:e.options,confirmationConfigOverride:e.confirmationConfigOverride})}function _m(e){if(e[Qp]!==!0)throw Error(`Invalid hosted passkey registration preparation`);let t=$p.get(e);if(!t)throw Error(`Hosted passkey registration preparation is unknown`);return t}function vm(e){if(e.lifecycle!==`ready`)throw Error(`Hosted passkey registration preparation is no longer usable`);if(Date.now()>=e.prepared.expiresAtMs)throw Em(e.prepared),Error(`Hosted passkey registration preparation expired`);if(e.controller.signal.aborted)throw Error(`Hosted passkey registration preparation was cancelled`);if(!hr.isLiveReservation({reservation:e.prepared.reservation,owner:e.prepared.owner}))throw Em(e.prepared),Error(`Hosted passkey registration prompt reservation is no longer active`)}function ym(e){return x({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:e.walletId,signerSlot:e.signerSlot,rpId:e.rpId,challengeB64u:e.challengeB64u})}function bm(){return Error(`Hosted passkey registration preparation was cancelled`)}function xm(e){if(e.aborted)throw bm()}function Sm(e){let t=e.cancellation.signal;return xm(t),new Promise((n,r)=>{let i=!1,a=()=>{c(bm())},o=()=>{t.removeEventListener(`abort`,a)},s=e=>{i||(i=!0,o(),n(e))},c=e=>{i||(i=!0,o(),r(e))};t.addEventListener(`abort`,a,{once:!0}),e.operation.then(s,c)})}function Cm(e){switch(e.setup.kind){case`near_ed25519`:return{kind:`not_required`};case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:{let t=e.setup.registrationCeremonyId,n=nh(e.setup.ecdsa),r=e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony({kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:t,registration:n.strictRegistration});return r.catch(()=>void 0),{kind:`started`,ceremonyId:t,operation:r}}default:return q(e.setup)}}function wm(e){e.ceremony.kind!==`not_required`&&zc({context:e.context,ceremonyId:e.ceremony.ceremonyId})}async function Tm(e){let t=e.authMethod,n=wp(String(t.rpId));if(wp(String(e.context.signingEngine.getRpId()||``))!==n)throw Error(`Hosted passkey registration rpId does not match the wallet runtime`);let r=hm(e.signerSelection),i=e.expiresInMs??300*1e3;if(!Number.isSafeInteger(i)||i<=0)throw Error(`Hosted passkey registration expiry must be a positive safe integer`);let a=Date.now()+i,o={kind:`hosted_auth_menu_registration`,authMenuSessionId:e.authMenuSessionId,requestId:e.requestId},s=new AbortController,c=null,l=null,u={kind:`not_required`},d=()=>{s.abort(),c&&Em(c)},f=()=>{e.cancellation.signal.removeEventListener(`abort`,d)};xm(e.cancellation.signal),e.cancellation.signal.addEventListener(`abort`,d,{once:!0});let p=new Qa(performance.now());try{let i=await Sm({operation:Ym({context:e.context,authMethod:t,wallet:e.wallet,signerSelection:e.signerSelection,recorder:p}),cancellation:e.cancellation}),d=tl(i.setup.intent);if(String(d.authMethod.rpId)!==String(n)||!im(d.signerSelection,e.signerSelection))throw Error(`Hosted passkey registration setup changed its authority binding`);let m=qt(String(d.walletId)),h=String(i.setup.registrationIntentDigestB64u||``).trim();if(!h)throw Error(`Hosted passkey registration setup returned no challenge`);if(r!==hm(e.signerSelection))throw Error(`Hosted passkey registration signer slot changed during preparation`);if(u=Cm({context:e.context,setup:i.setup}),mm({recorder:p,warmup:i.registrationWarmup}),Date.now()>=a)throw Error(`Hosted passkey registration preparation expired before reservation`);let g=await hr.reserveRegistrationPrompt({owner:o,expiresAtMs:a,cancellation:e.cancellation});l=g;let _=ym({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:t,walletId:m,signerSlot:r,rpId:n,challengeB64u:h}),v=Object.freeze({kind:`hosted_passkey_registration_prepared_v1`,walletId:m,signerSlot:r,rpId:n,challengeB64u:h,registrationIntentDigestB64u:h,expiresAtMs:a,owner:o,reservation:g,cancellation:{kind:`abort_signal`,signal:s.signal},[Qp]:!0});return $p.set(v,{prepared:v,context:e.context,wallet:e.wallet,signerSelection:e.signerSelection,authMethod:t,options:e.options??{},...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{},setup:i,controller:s,removeExternalCancellationListener:f,binding:_,lifecycle:`ready`,authority:null,registrationStarted:!1,ecdsaClientCeremony:u}),c=v,v}catch(t){throw s.abort(),f(),wm({context:e.context,ceremony:u}),c?Em(c):l&&hr.releaseReservation(l),t}}function Em(e){let t=_m(e);t.lifecycle===`finished`||t.lifecycle===`cancelled`||(t.lifecycle=`cancelled`,t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,wm({context:t.context,ceremony:t.ecdsaClientCeremony}),hr.releaseReservation(e.reservation))}function Dm(e){let t=_m(e);vm(t),t.lifecycle=`consuming`;let n=Zd(t.context.signingEngine.startPreparedPasskeyRegistrationCredential({walletId:String(e.walletId),signerSlot:e.signerSlot,challengeB64u:e.challengeB64u,expectedRpId:String(e.rpId),reservation:e.reservation,owner:e.owner,cancellation:e.cancellation}));return t.authority=n,n.then(()=>{t.lifecycle===`consuming`&&(t.lifecycle=`consumed`)},()=>{Em(e)}),n}async function Om(e){let t=_m(e.prepared);if(t.lifecycle!==`consuming`&&t.lifecycle!==`consumed`||!t.authority)throw Error(`Hosted passkey registration credential must be started by its CTA`);if(t.registrationStarted)throw Error(`Hosted passkey registration continuation was already consumed`);t.registrationStarted=!0;try{return await Vh({context:t.context,authMethod:t.authMethod,wallet:t.wallet,signerSelection:t.signerSelection,options:t.options,authenticatorOptions:jn(t.context.configs.webauthn.authenticatorOptions),...t.confirmationConfigOverride?{confirmationConfigOverride:t.confirmationConfigOverride}:{},passkeyExecution:{kind:`use_hosted_preparation`,prepared:e.prepared,authority:t.authority}})}finally{t.lifecycle=`finished`,wm({context:t.context,ceremony:t.ecdsaClientCeremony}),t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,hr.releaseReservation(e.prepared.reservation)}}async function km(e){return $d(`wallet-registration-near-provisioning:${await S([`wallet-registration-near-provisioning`,e.registrationCeremonyId,e.activationReference.lifecycle_id,e.activationReference.session_id.map(e=>e.toString(16).padStart(2,`0`)).join(``)].join(`:`))}`)}function Am(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return $d(`${e}:${t.randomUUID()}`);let n=new Uint8Array(16);if(!t||typeof t.getRandomValues!=`function`)throw Error(`Secure randomness is required for registration finalization`);return t.getRandomValues(n),$d(`${e}:${[...n].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`)}function jm(e){return e.recorder.measure(`emailOtpEnrollmentMaterialMs`,()=>Nm({context:e.context,authMethod:e.authMethod,relayerUrl:e.relayerUrl,walletId:e.walletId,providerSubject:e.providerSubject,clientSecret32:e.clientSecret32}))}function Mm(e){if(e.emailOtpSessionHandle.kind!==`not_requested`)throw Error(`Strict ECDSA registration received obsolete Email OTP root-share material`)}async function Nm(e){if(e.authMethod.kind!==`email_otp`)throw Error(`Email OTP enrollment material requires Email OTP auth`);try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:e.relayerUrl,walletId:Ie(e.walletId),userId:e.providerSubject,clientSecret32:e.clientSecret32});return Mm(t),t}finally{e.clientSecret32.fill(0)}}function Pm(e){let t=e.event.authMethod,n=Fm(e.accountId);return hn({...e.event,flowId:`registration:${t}:${n}`,accountId:n,authMethod:t})}function Fm(e){let t=String(e||``).trim();if(!t)throw Error(`Registration event account id is required`);return t}function Im(e){return b(e)&&`code`in e?String(e.code||``).trim():``}function Lm(e,t){return Object.assign(Error(e),t?{code:t}:{})}function Rm(e){return Array.isArray(e)?e.filter(e=>{switch(e){case`ble`:case`hybrid`:case`internal`:case`nfc`:case`smart-card`:case`usb`:return!0;default:return!1}}):[]}function $(e,t,n){e?.(Pm({accountId:t,event:n}))}function zm(e,t,n){let r=!1;return async i=>{if(!e||r)return await i;let a=setTimeout(()=>{r||(r=!0,$(e,t,{authMethod:`passkey`,phase:n,status:`running`}))},5e3);try{return await i}finally{clearTimeout(a)}}}async function Bm(e){let t=String(e||``).trim().toLowerCase();if(!t)throw Error(`Email OTP registration auth context requires email`);return S(t)}function Vm(e){switch(e.proofKind){case`otp_challenge`:return`email`;case`google_sso_registration`:return`google`;default:return q(e)}}function Hm(e){switch(e.kind){case`passkey`:return{kind:`passkey`,webauthnRegistration:e.webauthnRegistration};case`email_otp`:return{kind:`email_otp`,emailOtpRegistrationProof:e.emailOtpRegistrationProof};default:return q(e)}}async function Um(e){let t=performance.now();try{let n=await il(e.deferredNear,{routerOrigin:new URL(e.relayerUrl).origin,routing:e.home,authorization:{kind:`bearer`,value:`Bearer ${e.signedSetup}`},fetch:globalThis.fetch,...e.traceContext?{traceContext:e.traceContext}:{}});return wa({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`success`}),{deferredNear:e.deferredNear,admissionReceipt:n}}catch(n){throw wa({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`failure`}),n}}function Wm(e){if(!e)throw Error(`Mixed registration did not start NEAR admission`);return e}function Gm(e,t,n){switch(e.kind){case`passkey`:return{auth:{kind:`passkey`,rpId:pt(e.rpId),credentialIdB64u:t}};case`email_otp`:return{auth:{kind:`email_otp`,providerSubjectId:sr(e.emailOtpAuthContext)},remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs};default:return q(e)}}async function Km(e){let t=ut(x({operation:`wallet_registration_activate_v2`,registrationCeremonyId:e.registrationCeremonyId,activationCorrelationId:e.activationCorrelationId,idempotencyKey:e.idempotencyKey,publicFacts:e.publicFacts}));return{canonicalRequest:t,requestDigest:xe(L(await A(String(t))))}}async function qm(e){let t={authority:e.materialAuthority,targetMemberships:e.chainTargets,evmFamilySigningKeySlotId:Gt(e.ecdsaPrepare.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:ln(e.ecdsaPrepare.prepare.ecdsaThresholdKeyId),signingRootId:ot(e.ecdsaPrepare.prepare.signingRootId),signingRootVersion:mt(e.ecdsaPrepare.prepare.signingRootVersion),runtimePolicyScope:e.ecdsaPrepare.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:sn(e.clientActivation.derivationClientSharePublicKey33B64u),participantIds:[Dt(e.ecdsaPrepare.prepare.participantIds[0]),Dt(e.ecdsaPrepare.prepare.participantIds[1])],relayerKeyId:cn(e.ecdsaPrepare.prepare.relayerKeyId),bindingDigest:pn(e.clientActivation.contextBinding32B64u),journalId:e.activationCorrelationId,requestDigest:e.activationCommand.requestDigest,canonicalRequest:e.activationCommand.canonicalRequest,createdAt:ye(new Date().toISOString())},n=await e.context.signingEngine.persistInitialCanonicalEcdsaActivation({kind:`persist_initial_canonical_ecdsa_activation_v1`,bootstrapOwner:`wallet_custody`,clientActivation:e.clientActivation,ceremonyId:e.ceremonyId,planInput:t});if(!n.ok)throw Error(`Canonical ECDSA activation persistence failed (${n.code}): ${n.message}`);return n}function Jm(e){let t=R(e);if(t.length!==20)throw Error(`ECDSA activation address must contain 20 bytes`);return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function Ym(e){let t=String(e.context.configs.network.relayer.url||``).trim();if(!t)throw Error(`registerWallet requires relayer.url`);let n=e.context.configs.registration,r=String(n?.publishableKey||``).trim(),i=String(n?.projectEnvironmentId||``).trim();if(!r||!i)throw Error(`registerWallet requires registration.publishableKey and registration.projectEnvironmentId`);let a=pm({recorder:e.recorder,context:e.context,relayerUrl:t,authMethod:e.authMethod,signerSelection:e.signerSelection}),o=await e.recorder.measure(`registrationIntentMs`,()=>Wn({relayerUrl:t,request:{...e.wallet.kind===`provided`?{wallet:e.wallet}:{},signerSelection:e.signerSelection,authMethod:e.authMethod},auth:{publishableKey:r,environmentId:i}}));if(!o.ok)throw Lm(o.message,o.code);return{relayerUrl:t,setup:o,registrationWarmup:a}}async function Xm(e){if(e.passkeyExecution.kind===`collect_during_registration`)return await Ym({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:e.recorder});if(e.authMethod.kind!==`passkey`)throw Error(`Hosted passkey preparation requires passkey registration`);let t=_m(e.passkeyExecution.prepared);if(t.context!==e.context||t.lifecycle===`cancelled`)throw Error(`Hosted passkey registration preparation belongs to a different operation`);let n=t.setup,r=tl(n.setup.intent),i=String(n.setup.registrationIntentDigestB64u||``).trim(),a=hm(e.signerSelection);if(ym({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:qt(String(r.walletId)),signerSlot:a,rpId:wp(String(e.authMethod.rpId)),challengeB64u:i})!==t.binding||String(r.walletId)!==String(e.passkeyExecution.prepared.walletId)||i!==e.passkeyExecution.prepared.challengeB64u)throw Error(`Hosted passkey registration preparation binding changed`);return n}function Zm(e){if(e.passkeyExecution.kind===`collect_during_registration`)return{kind:`create_after_authority`};let t=_m(e.passkeyExecution.prepared);if(t.ecdsaClientCeremony.kind!==`started`||t.ecdsaClientCeremony.ceremonyId!==e.ceremonyId)throw Error(`Hosted passkey registration has no matching ECDSA client ceremony`);return{kind:`use_hosted_preparation`,ceremonyId:t.ecdsaClientCeremony.ceremonyId,operation:t.ecdsaClientCeremony.operation}}async function Qm(e){return await e}function $m(e){switch(e.clientCeremony.kind){case`create_after_authority`:return e.context.signingEngine.createRouterAbEcdsaRegistrationCeremony.bind(e.context.signingEngine,{kind:`create_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:e.ceremonyId,registration:e.registration});case`use_hosted_preparation`:if(e.clientCeremony.ceremonyId!==e.ceremonyId)throw Error(`Prepared ECDSA client ceremony identity changed`);return Qm.bind(void 0,e.clientCeremony.operation);default:return q(e.clientCeremony)}}async function eh(e){let[t,...n]=e.ecdsaPrepare.chainTargets;if(!t)throw Error(`Strict ECDSA ceremony requires at least one EVM-family target`);let r=e.registrationCeremonyId,i=be(r),a=null;try{let o=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientCreateMs`,operation:$m({context:e.context,ceremonyId:r,registration:e.ecdsaPrepare.strictRegistration,clientCeremony:e.clientCeremony})}),s=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Un.bind(void 0,{relayerUrl:e.relayerUrl,headers:jc(e.traceContext),registrationCeremonyId:r,signerPlanKind:e.signerPlanKind,signedSetup:e.signedSetup,ecdsa:{kind:`router_ab_ecdsa_registration_v1`,strictRegistration:o.registrationRequest,requestDigestB64u:o.registrationRequestDigestB64u},...Hm(e.authority),onServerTiming:t=>xa(e.registrationTiming,`respond`,t)})});if(s.kind===`near_ed25519`)throw Error(`ECDSA registration ceremony received an Ed25519-only respond result`);let c=s.kind===`near_ed25519_and_evm_family_ecdsa`?s.ed25519:null,l=c?Um({home:e.home,relayerUrl:e.relayerUrl,registrationCeremonyId:r,signedSetup:e.signedSetup,deferredNear:c,traceContext:e.traceContext}):null;l?.catch(mh);let u=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientProofVerifyMs`,operation:e.context.signingEngine.verifyRouterAbEcdsaRegistrationClientProofs.bind(e.context.signingEngine,{kind:`verify_router_ab_ecdsa_registration_client_proofs_v1`,bootstrapOwner:`wallet_custody`,ceremonyId:r,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:s.ecdsa.strictResult.response.bundles}})}),d=await e.resolveActivateEmailOtp(),f=[t,...n],p=e.authority.kind===`passkey`?e.authority.walletCustodyFactorJson:d.walletCustodyFactorJson;if(!p)throw Error(`ECDSA registration has no wallet custody factor binding`);let m=e.authority.walletCustodyFactorSecret,h={},g=await e.context.signingEngine.establishWalletCustodyEvmFamilyKeySet({walletId:e.ecdsaPrepare.prepare.walletId,factorJson:p,factorSecret:m,evmFamilySigningKeySlotId:e.ecdsaPrepare.prepare.evmFamilySigningKeySlotId,applicationBindingDigestB64u:u.applicationBindingDigestB64u,confirmRecoveryCodesBackedUp:e.confirmRecoveryCodesBackedUp,runRelayerRound:async t=>{let n=ht({registrationRequestDigestB64u:u.registrationRequestDigestB64u,proofTranscriptDigestB64u:u.proofTranscriptDigestB64u,contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.clientSharePublicKey33B64u,clientShareRetryCounter:t.clientShareRetryCounter,participantId:1}),o=await Km({registrationCeremonyId:r,activationCorrelationId:i,idempotencyKey:e.idempotencyKey,publicFacts:n}),s=ql(t.preActivationCommitPayload),p={activationJournalId:i,clientActivation:n,activationRequestDigestB64u:o.requestDigest};if(e.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){if(!c)throw Error(`Mixed registration has no NEAR continuation`);await e.persistPendingCommit({signerPlanKind:e.signerPlanKind,localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:s,ecdsa:p},emailOtpEnrollment:d.enrollment,deferredNear:c}),a=e.startDeferredNearCustody({admission:Wm(l),establishedEvmCustodyCommit:t.preActivationCommitPayload}),a.catch(mh)}else await e.persistPendingCommit({signerPlanKind:e.signerPlanKind,localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:s,ecdsa:p},emailOtpEnrollment:d.enrollment});let m=await qm({context:e.context,ceremonyId:r,materialAuthority:e.materialAuthority,ecdsaPrepare:e.ecdsaPrepare,chainTargets:f,activationCorrelationId:i,activationCommand:o,clientActivation:n});if(String(m.journalId)!==String(i))throw Error(`ECDSA activation journal identity changed before activate`);let g=await Uc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Yn.bind(void 0,{relayerUrl:e.relayerUrl,headers:jc(e.traceContext),registrationCeremonyId:r,signerPlanKind:e.signerPlanKind,signedSetup:e.signedSetup,idempotencyKey:e.idempotencyKey,ecdsa:{clientActivation:n,activationCorrelationId:i,activationRequestDigestB64u:o.requestDigest},walletCustodyCommit:t.preActivationCommitPayload,...d.enrollment?{emailOtpEnrollment:d.enrollment}:{},onServerTiming:t=>xa(e.registrationTiming,`activate`,t)})});if(g.kind!==`evm_family_ecdsa`||!g.ecdsa)throw Error(`ECDSA registration ceremony received a non-ECDSA activate result`);h.value=g,h.journalId=m.journalId;let _=g.ecdsa.activation.ecdsa_activation.public_identity;return JSON.stringify({relayerKeyId:e.ecdsaPrepare.prepare.relayerKeyId,relayerPublicKey33B64u:_.server_public_key33_b64u,groupPublicKey33B64u:_.threshold_public_key33_b64u,ethereumAddress:Jm(_.ethereum_address20_b64u),relayerShareRetryCounter:_.server_share_retry_counter})}});if(!h.value||!h.journalId)throw Error(`Wallet custody ECDSA activation did not return its committed receipt`);let _=h.value;if(_.walletCustody?.status!==`committed`){let e=_.walletCustody?.status??`not_reported`;throw Error(`Wallet custody did not commit during ECDSA activation (${e})`)}let v=Bc({prepare:e.ecdsaPrepare.prepare,verified:g.clientBootstrap}),y=Gn({clientBootstrap:v,serverBootstrap:_.ecdsa.bootstrap,activationEpoch:_.ecdsa.activation.ecdsa_activation.activation_epoch}),b=await e.context.signingEngine.finalizeRouterAbEcdsaRegistrationActivation({kind:`finalize_router_ab_ecdsa_registration_activation_v1`,bootstrapOwner:`wallet_custody`,journalId:h.journalId,activationReceipt:_.ecdsa.activation,routerAbEcdsaDerivationNormalSigning:y.routerAbEcdsaDerivationNormalSigning,readyStateBlobB64u:g.localMaterial.readyStateBlobB64u,walletCustodyPublicFacts:g.localMaterial.publicFacts});return{session:{chainTargets:[t,...n],clientBootstrap:v,bootstrap:y,activatedThresholdSessionId:_.ecdsa.bootstrap.thresholdSessionId,roleLocalMaterial:b.roleLocalMaterial,authority:await ct({authority:_.authority}),materialActivation:b.materialActivation,clientPublicFacts:b.publicFacts,publicCapability:b.publicCapability,registrationEstablishedSession:Pc(_.registrationEstablishedSession)},activated:_,deferredNear:c,activateEmailOtp:{enrollment:d.enrollment},walletCustody:g,deferredNearCustodyWork:a}}catch(t){throw dh(a),await zc({context:e.context,ceremonyId:r}),t}}function th(e){switch(e.kind){case`evm`:return ze({chain:`evm`,chainId:e.chainId,networkSlug:e.networkSlug});case`tempo`:return ze({chain:`tempo`,chainId:e.chainId,networkSlug:e.networkSlug});default:return q(e)}}function nh(e){let[t,...n]=e.chainTargets;if(!t)throw Error(`Registration setup ECDSA chain targets are required`);return{kind:e.kind,chainTargets:[th(t),...n.map(th)],prepare:e.prepare,strictRegistration:e.strictRegistration}}function rh(e,t){switch(e.kind){case`near_ed25519`:throw Error(`Registration setup returned an Ed25519-only signer branch`);case`evm_family_ecdsa`:case`near_ed25519_and_evm_family_ecdsa`:if(e.kind!==t)throw Error(`Registration setup returned a different signer branch`);return e;default:return q(e)}}function ih(e){switch(e.kind){case`evm_family_ecdsa`:return 1;case`near_ed25519_and_evm_family_ecdsa`:return e.ed25519Selection.signerSlot;default:return q(e)}}function ah(e){if(e.authMethod.kind===`passkey`){if(!e.passkeyAuthority)throw Error(`Passkey registration authority was not collected`);return{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:String(e.passkeyAuthority.credential.rawId||e.passkeyAuthority.credential.id||``).trim(),transports:[...e.passkeyAuthority.webauthnRegistration.response.transports]}}return{kind:`email_otp`,email:e.email,registrationAuthorityId:e.registrationAuthorityId,providerSubject:e.providerSubject,enrollment:oh(e.emailOtpEnrollment)}}function oh(e){if(!e)throw Error(`Email OTP registration has no enrollment material for pending recovery`);return e}async function sh(e){let t=Date.now(),n=Mp({...e,createdAtMs:t,updatedAtMs:t});return await V.putPendingWalletRegistrationCommit(n),n}function ch(e){if(!e||e.operation!==`registration_activate`||e.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`Mixed registration activation commit was not persisted`);return e}async function lh(e){let t=e.walletKeys;if(e.auth.kind===`passkey`){let n=String(e.auth.credential.rawId||e.auth.credential.id||``).trim();if(!n)throw Error(`Passkey registration publication has no credential id`);return await nt({kind:`passkey`,walletId:e.walletId,rpId:wp(e.auth.rpId),credentialIdB64u:n,credentialPublicKeyB64u:e.auth.credentialPublicKeyB64u,transports:e.auth.credential.response?.transports??[],walletKeys:t})}return await nt({kind:`email_otp`,walletId:e.walletId,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:e.auth.authority,walletKeys:t})}async function uh(e){let t=await Fp({context:e.context,relayerUrl:e.relayerUrl,registrationTiming:e.registrationTiming,plan:e.plan}),n=await lh({auth:e.plan.auth,walletId:e.plan.walletId,walletKeys:t}),r=e.plan.ecdsa.session.registrationEstablishedSession;await V.publishPendingWalletRegistrationCommit({pending:e.pending,authority:e.activated.authority,foundingAuthority:{authority:e.activated.foundingAuthority,authMethod:e.activated.foundingAuthMethod},request:{operation:e.pending.operation,registrationCeremonyId:e.pending.registrationCeremonyId,idempotencyKey:e.pending.idempotencyKey,walletId:e.pending.walletId,walletAuthMethodId:e.pending.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:r.walletSession,operationCredential:r.operationCredential},ecdsaContinuity:[],registration:n})}async function dh(e){if(e)try{Up((await e).factorSecret32)}catch{}}function fh(e){switch(e.auth.kind){case`passkey`:{if(!e.passkeyAuthority)throw Error(`Deferred passkey registration requires authority material`);let t=String(e.passkeyAuthority.credential.rawId||e.passkeyAuthority.credential.id||``).trim(),n=String(e.passkeyAuthority.prfFirstB64u||``).trim();if(!t||!n)throw Error(`Deferred passkey registration requires credential PRF material`);return{kind:`passkey`,rpId:e.auth.rpId,credentialIdB64u:t,prfFirstB64u:n}}case`email_otp`:if(!e.emailOtpEnrollment)throw Error(`Deferred Email OTP registration requires enrollment material`);return{kind:`email_otp`,enrollment:e.emailOtpEnrollment,emailOtpAuthContext:e.auth.emailOtpAuthContext};default:return q(e.auth)}}async function ph(e,t,n){let r=performance.now();await V.advancePendingNearRegistration({expected:e,next:Tn(e,t,n)}),kr(e.registrationCeremonyId,`journal_prepared`,r)}function mh(){}async function hh(e,t){let n=e.factorSecretOwner.value;if(!n)throw Error(`Mixed registration has no NEAR custody factor secret`);e.factorSecretOwner.value=null;let r=performance.now(),i=`failure`;try{let r=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.registrationCeremonyId,operation:`near_provisioning`});if(!r||r.operation!==`near_provisioning`||r.phase!==`planned`)throw Error(`NEAR registration has no planned continuation`);let a;try{let e=await t.admission;if(!zt(e.deferredNear.admissionRequest,r.admissionRequest))throw Error(`NEAR admission changed the authorized request`);a=e.admissionReceipt}catch(e){if(e instanceof Error&&e.message===`NEAR admission changed the authorized request`)throw e;a=void 0}let{joined:o,admissionReceipt:s}=await _h({home:e.home,pending:r,signingEngine:e.context.signingEngine,relayerUrl:e.relayerUrl,credential:e.signedSetup,traceContext:e.traceContext,factorSecret:n,...a?{admitted:a}:{}});return i=`success`,{admissionReceipt:s,joined:o,admissionRequest:r.admissionRequest,envelope:qp({commit:t.establishedEvmCustodyCommit,walletId:r.walletId,activatedAtMs:Date.now()}),factorSecret32:n}}catch(e){throw Up(n),e}finally{wa({ceremonyId:e.registrationCeremonyId,stage:`custody_join`,startedAt:r,outcome:i})}}async function gh(e){return e.pending.phase===`execution_prepared`?e.pending.admissionReceipt:e.admitted?e.admitted:await il({status:`deferred`,admissionRequest:e.pending.admissionRequest},{routerOrigin:new URL(e.relayerUrl).origin,routing:e.home,authorization:{kind:`bearer`,value:`Bearer ${e.credential}`},fetch:globalThis.fetch,traceContext:e.traceContext})}async function _h(e){let t=e.pending;if(t.phase===`joined`&&t.completion.kind!==`encrypted_checkpoint`)throw Error(`Joined material has no encrypted execution checkpoint`);let n=t.phase===`joined`&&t.completion.kind===`encrypted_checkpoint`?t.completion.prepared:t;if(n.phase===`joined`)throw Error(`Invalid NEAR continuation phase`);let r=n.admissionRequest,i=performance.now(),a=await gh({home:e.home,pending:n,relayerUrl:e.relayerUrl,credential:e.credential,traceContext:e.traceContext,...e.admitted?{admitted:e.admitted}:{}});kr(n.registrationCeremonyId,`admission`,i);let o=await e.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:e.home,...n.phase===`planned`?{preparation:{kind:`fresh`},beforeRouterRound:ph.bind(void 0,n,a)}:{preparation:{kind:`checkpoint`,checkpointJson:n.checkpointJson}},custodyJson:Il(n.baseCustodyCommit),factorSecret:e.factorSecret,nearEd25519SigningKeyId:r.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:n.registrationCeremonyId,admissionRequest:r,admissionReceipt:a,participantIds:r.participant_ids,routerOrigin:new URL(e.relayerUrl).origin,authorization:`Bearer ${e.credential}`,traceContext:e.traceContext});if(t.phase===`joined`){if(L(o.metadata.registeredPublicKey)!==t.localMaterial.ed25519.metadata.registeredPublicKeyB64u||JSON.stringify(o.activationReference)!==JSON.stringify(t.localMaterial.ed25519.activationReference))throw Error(`Restored NEAR checkpoint changed the joined key`);return{joined:o,admissionReceipt:a}}let s=performance.now(),c=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:n.registrationCeremonyId,operation:`near_provisioning`});if(!c||c.operation!==`near_provisioning`||c.phase!==`execution_prepared`)throw Error(`NEAR execution checkpoint was not persisted`);let l=Mp({operation:`near_provisioning`,signerPlanKind:`near_ed25519_and_evm_family_ecdsa`,completion:{kind:`encrypted_checkpoint`,prepared:c},registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:await km({registrationCeremonyId:c.registrationCeremonyId,activationReference:o.activationReference}),walletId:c.walletId,walletAuthMethodId:c.walletAuthMethodId,signedSetup:c.signedSetup,auth:c.auth,createdAtMs:c.createdAtMs,updatedAtMs:Date.now(),localMaterial:{keyFamilies:[`ed25519`],custodyCommit:o.commitPayload,ed25519:{activationReference:o.activationReference,localMaterial:o.localMaterial,metadata:Gp(o)}}});if(l.operation!==`near_provisioning`||l.phase!==`joined`)throw Error(`Invalid joined NEAR continuation`);return await V.advancePendingNearRegistration({expected:c,next:l}),kr(n.registrationCeremonyId,`journal_joined`,s),{joined:o,admissionReceipt:a}}function vh(e){return e.chainTarget}function yh(e,t){if(e.auth.kind===`passkey`&&t.kind===`passkey`&&e.auth.rpId===t.rpId&&e.auth.credentialIdB64u===t.credentialIdB64u)return{kind:`passkey`,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u,prfFirstB64u:t.prfFirstB64u};if(e.auth.kind===`email_otp`&&t.kind===`email_otp`&&e.auth.providerSubject===t.providerSubject){let n=lt({walletId:e.walletId,bindingId:e.walletAuthMethodId,factor:{kind:`email_otp`,provider:t.provider,providerUserId:t.providerSubject},verifier:{kind:`email_otp_wallet_auth_method`,emailHashHex:t.emailHashHex}});if(!n)throw Error(`NEAR continuation requires its founding Email OTP method`);return{kind:`email_otp`,enrollment:e.auth.enrollment,emailOtpAuthContext:lr({policy:`session`,retention:`session`,reason:`login`,authority:n})}}throw Error(`NEAR continuation requires its founding authentication method`)}async function bh(e){if(await wh(e.sessionAuthority),e.pending.phase===`joined`&&e.pending.completion.kind===`sealed_material`){let t=await fd({pending:e.pending,relayerUrl:e.relayerUrl,operationCredential:e.sessionAuthority.operationCredential});return{joined:t.joined,admissionRequest:t.admissionRequest,admissionReceipt:t.admissionReceipt,envelope:e.envelope,factorSecret32:e.factorSecret}}let t=e.pending.phase===`joined`?e.pending.completion.prepared:e.pending;if(!t)throw Error(`NEAR continuation has no encrypted checkpoint`);let n=await _h({home:e.sessionAuthority.operationCredential.home,pending:e.pending,signingEngine:e.context.signingEngine,relayerUrl:e.relayerUrl,credential:e.sessionAuthority.operationCredential.token,traceContext:_n(),factorSecret:e.factorSecret});return{joined:n.joined,admissionReceipt:n.admissionReceipt,admissionRequest:t.admissionRequest,envelope:e.envelope,factorSecret32:e.factorSecret}}async function xh(e){let t=performance.now();try{let n=await V.listPendingWalletRegistrationCommits();for(let r of n){if(r.operation!==`near_provisioning`||r.walletId!==e.sessionAuthority.record.walletId||r.walletAuthMethodId!==e.sessionAuthority.record.authMethodId||r.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`||await V.getPendingWalletRegistrationCommit({registrationCeremonyId:r.registrationCeremonyId,operation:`registration_activate`}))continue;let n=e.context.configs.network.relayer.url,i=yh(r,e.factor),a=bh.bind(void 0,{context:e.context,pending:r,envelope:e.custodyEnvelope,relayerUrl:n,sessionAuthority:e.sessionAuthority,factorSecret:e.ownedFactorSecret});await Nh({context:e.context,walletId:r.walletId,commit:{context:e.context,registrationTiming:null,registrationStartedAt:t,relayerUrl:n,registrationCeremonyId:r.registrationCeremonyId,signedSetup:r.signedSetup,headers:jc(),nearCustodyWork:a,sessionAuthority:e.sessionAuthority,expectedChainTargets:Mr(e.context.configs.network.chains).map(vh),walletId:r.walletId,authMaterial:i}})}}catch(e){console.warn(`[registration] NEAR continuation remains pending`,e instanceof Error?e.message:`continuation failed`)}finally{Up(e.ownedFactorSecret)}}function Sh(e){if(!e)throw Error(`Mixed registration did not start its NEAR custody join`);return e}function Ch(e,t,n,r){if(t.kind!==`already_committed`||t.session.tokens.kind!==`near_ed25519_and_evm_family_ecdsa`)throw Error(`NEAR completion must extend the current Wallet Session`);let i=t.session,a=e.record,o=i.walletSession;if(i.walletId!==a.walletId||i.authorizationId!==a.authorizationId||i.quotaId!==a.quotaId||i.walletSessionId!==e.operationCredential.walletSessionId||o.authorityId!==a.authorityId||o.authMethodId!==a.authMethodId||o.issuedAtMs!==a.issuedAtMs||o.expiresAtMs!==a.expiresAtMs||o.authorityRevocationEpoch!==a.authorityRevocationEpoch||o.expiresAtMs<=Date.now()||!fe(a,o)||n.authorityId!==o.authorityId||n.walletId!==o.walletId||n.authorityDigestB64u!==o.authorityDigestB64u||n.revocationEpoch!==o.authorityRevocationEpoch||r.walletAuthMethodId!==o.authMethodId||r.walletId!==o.walletId||r.walletAuthorityId!==o.authorityId)throw Error(`NEAR completion changed the current Wallet Session authority`);return{kind:`registration_established_wallet_session_v2`,walletId:i.walletId,authorizationId:i.authorizationId,walletSessionId:i.walletSessionId,quotaId:i.quotaId,expiresAtMs:i.expiresAtMs,remainingUses:i.remainingUses,walletSession:o,operationCredential:e.operationCredential,tokens:i.tokens}}async function wh(e){let t=await In.readExactWithOperationCredential({walletId:e.record.walletId,authorityId:e.record.authorityId,authMethodId:e.record.authMethodId});if(t.kind!==`found`||t.record.expiresAtMs<=Date.now()||t.record.authorizationId!==e.record.authorizationId||t.record.authorityRevocationEpoch!==e.record.authorityRevocationEpoch||t.operationCredential.token!==e.operationCredential.token)throw Error(`NEAR continuation requires the current unlocked Wallet Session`)}async function Th(e){let t=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.registrationCeremonyId,operation:`near_provisioning`});if(!t||t.operation!==`near_provisioning`||t.phase!==`joined`||t.walletId!==e.walletId||t.walletAuthMethodId!==e.walletAuthMethodId)throw Error(`NEAR joined checkpoint was not persisted`);return t}async function Eh(e){let{metadata:t,materialFacts:n}=e,r={materialActivation:tr(t),lifecycleId:t.scope.lifecycle_id,signingRootVersion:t.scope.root_share_epoch,signingRootId:t.applicationBinding.signing_root_id,signerSetId:t.scope.signer_set_id,thresholdSessionId:n.identity.thresholdSessionId,activationTranscriptB64u:L(t.transcript),activationCapabilityBindingB64u:L(Uint8Array.from(t.activeCapabilityBinding))},i=null;try{i=await ha({material:e.material,activation:r,envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret}),await Kf({store:V,activeClient:i,identity:{walletId:n.identity.walletId,nearAccountId:n.identity.nearAccountId,nearEd25519SigningKeyId:n.identity.nearEd25519SigningKeyId,thresholdSessionId:n.identity.thresholdSessionId,signerSlot:n.identity.signerSlot,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,signingRootId:n.identity.signingRootId,signingRootVersion:n.identity.signingRootVersion,signingWorkerId:n.stableServerScope.routerAbNormalSigning.signingWorkerId},stableServerScope:n.stableServerScope,passkeyPrfFirstB64u:e.passkeyPrfFirstB64u}),await wh(e.sessionAuthority),await e.signingEngine.activateVerifiedNearEd25519YaoMaterial({activeClient:i,facts:{thresholdSessionId:n.identity.thresholdSessionId,signer:cr({walletId:Ie(n.identity.walletId),nearAccountId:z(n.identity.nearAccountId),nearEd25519SigningKeyId:Jt(n.identity.nearEd25519SigningKeyId),signerSlot:n.identity.signerSlot}),signingRootId:n.identity.signingRootId,signingRootVersion:n.identity.signingRootVersion,routerAbNormalSigning:n.stableServerScope.routerAbNormalSigning,runtimePolicyScope:n.stableServerScope.runtimePolicyScope,relayerUrl:e.relayerUrl}}),await wh(e.sessionAuthority),i=null}catch(e){throw i?.dispose(),e}finally{e.ownedFactorSecret.fill(0)}}async function Dh(e){let t=performance.now(),n=`failure`;try{return await e.signingEngine.hydrateSigningSession(e.input),n=`success`,{kind:`completed`}}catch(e){return{kind:`failed`,error:e}}finally{wa({ceremonyId:e.ceremonyId,stage:`session_hydration`,startedAt:t,outcome:n})}}async function Oh(e){let t=performance.now(),n=`failure`;try{return await e.signingEngine.prepareSigningSessionHydration(e.input),n=`success`,{kind:`completed`}}catch(e){return{kind:`failed`,error:e}}finally{wa({ceremonyId:e.ceremonyId,stage:`session_seal_preparation`,startedAt:t,outcome:n})}}function kh(e){let t=s(e.thresholdSessionId);if(!t.ok)throw Error(`Invalid admitted NEAR session identity`);let n=Am(`near-session-client-seal`);return{kind:`preparing`,thresholdSessionId:String(t.value),preparationId:n,result:Oh({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,input:{preparationId:n,thresholdSessionId:String(t.value),prfFirstB64u:e.prfFirstB64u}})}}async function Ah(e){try{await wh(e.sessionAuthority);let t=await V.getPendingWalletRegistrationCommit({registrationCeremonyId:e.ceremonyId,operation:`near_provisioning`});return!t||t.operation!==`near_provisioning`||t.phase===`joined`||t.walletId!==e.sessionAuthority.record.walletId||t.walletAuthMethodId!==e.sessionAuthority.record.authMethodId?{kind:`none`}:kh({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,thresholdSessionId:t.admissionRequest.scope.threshold_session_id,prfFirstB64u:e.prfFirstB64u})}catch{return{kind:`none`}}}function jh(){return null}async function Mh(e){let t=e.authMaterial,n=performance.now(),r=`failure`,i=null,a=Promise.resolve({kind:`completed`}),o={kind:`none`};try{t.kind===`passkey`&&(o=await Ah({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,sessionAuthority:e.sessionAuthority,prfFirstB64u:t.prfFirstB64u}));let n=await e.nearCustodyWork();i=n.factorSecret32;let s=n.joined,c=`ed25519:${Ee(s.metadata.registeredPublicKey)}`,l=s.activationReference,u=await km({registrationCeremonyId:e.registrationCeremonyId,activationReference:l}),d=await Th({registrationCeremonyId:e.registrationCeremonyId,walletId:e.walletId,walletAuthMethodId:String(e.sessionAuthority.record.authMethodId)});await wh(e.sessionAuthority),t.kind===`passkey`&&o.kind===`none`&&(o=kh({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,thresholdSessionId:s.metadata.scope.threshold_session_id,prfFirstB64u:t.prfFirstB64u}));let f;if(o.kind===`preparing`){let t=performance.now(),n=await o.result;if(wa({ceremonyId:e.registrationCeremonyId,stage:`session_seal_preparation_wait`,startedAt:t,outcome:n.kind===`completed`?`success`:`failure`}),n.kind===`failed`)throw n.error;await wh(e.sessionAuthority);let r=await e.context.signingEngine.readPreparedSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId});f={preparationId:o.preparationId,thresholdSessionId:o.thresholdSessionId,ciphertext:r.ciphertext}}let p=performance.now(),m={relayerUrl:e.relayerUrl,registrationCeremonyId:e.registrationCeremonyId,signedSetup:e.signedSetup,headers:{...e.headers,...te(e.sessionAuthority.operationCredential)},idempotencyKey:u,ed25519:{activationReference:l},walletCustodyCommit:s.commitPayload,onServerTiming:Sa.bind(void 0,e.registrationTiming)},h;if(f){if(e.authMaterial.kind!==`passkey`)throw Error(`Prepared session sealing requires a passkey authority`);h=await Qn({...m,auth:{kind:`passkey`},sessionSeal:{thresholdSessionId:f.thresholdSessionId,ciphertext:f.ciphertext}})}else h=await Qn({...m,auth:e.authMaterial});if(!h.ok)throw Error(`Deferred NEAR provisioning did not complete`);let g=h;if(g.kind!==`near_ed25519`)throw Error(`Deferred Ed25519 finalize returned a different signer branch`);if(g.walletCustody?.status!==`joined`){let e=g.walletCustody?.status??`not_reported`;throw Error(`Deferred NEAR custody join did not commit (${e})`)}if(f&&!g.sessionSeal)throw Error(`Deferred NEAR finalization did not return the prepared session seal`);wa({ceremonyId:e.registrationCeremonyId,stage:`server_finalize`,startedAt:p,outcome:`success`});let _=Ch(e.sessionAuthority,g.registrationEstablishedSession,g.foundingAuthority,g.foundingAuthMethod),v=z(g.ed25519.nearAccountId),y=e.authMaterial.kind===`passkey`?e.authMaterial.credentialIdB64u:``;t.kind===`passkey`?nl({clientPublicKey:c,finalized:g,expectedRpId:t.rpId,expectedWalletId:e.walletId}):rl({clientPublicKey:c,finalized:g,expectedRegistrationAuthorityId:d.auth.kind===`email_otp`?d.auth.registrationAuthorityId:``,expectedWalletId:e.walletId});let b=Qc({admissionRequest:n.admissionRequest,finalized:g.ed25519,walletId:e.walletId,expectedRuntimePolicyScope:I(g.ed25519.runtimePolicyScope)}),x=s.metadata,S=tr(x),C=Wp({established:s,walletId:String(e.walletId),nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,signerSlot:g.ed25519.signerSlot}),w=performance.now(),T=await sd(d,g);await wh(e.sessionAuthority);let E=(await V.publishPendingWalletRegistrationCommitAndRetain({pending:d,ecdsaContinuity:[],authority:g.authority,foundingAuthority:{authority:g.foundingAuthority,authMethod:g.foundingAuthMethod},request:{operation:d.operation,registrationCeremonyId:e.registrationCeremonyId,idempotencyKey:d.idempotencyKey,walletId:e.walletId,walletAuthMethodId:g.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`credential_free_projection`,walletSession:_.walletSession},registration:T})).signerActivations[0];if(!E||E.signerSlot!==g.ed25519.signerSlot)throw Error(`Deferred Ed25519 registration persisted a different signer slot`);let D=new fr;for(let t of e.expectedChainTargets)vd({signingEngine:e.context.signingEngine,walletId:e.walletId,chainTarget:t,trigger:`registration`,statusReads:D});wa({ceremonyId:e.registrationCeremonyId,stage:`local_publication`,startedAt:w,outcome:`success`}),await wh(e.sessionAuthority),e.authMaterial.kind===`passkey`&&_.remainingUses>0&&(a=Dh({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,input:al({session:_,ceremonyId:e.registrationCeremonyId,walletId:String(e.walletId),relayerUrl:e.relayerUrl,prfFirstB64u:e.authMaterial.prfFirstB64u,preparedServerSeal:f&&g.sessionSeal?{preparationId:f.preparationId,...g.sessionSeal}:null,restore:{rpId:e.authMaterial.rpId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,relayerKeyId:g.ed25519.relayerKeyId,participantIds:g.ed25519.participantIds,signerSlot:g.ed25519.signerSlot,credentialIdB64u:e.authMaterial.credentialIdB64u,materialActivation:S}})}));let O=performance.now();await e.context.signingEngine.activateAuthenticatedWalletState({walletId:e.walletId,nearAccountId:v,signerSlot:g.ed25519.signerSlot,nearClient:e.context.nearClient}),await e.context.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:e.walletId,nearAccountId:v,thresholdSessionId:b.identity.thresholdSessionId,runtimePolicyScope:b.stableServerScope.runtimePolicyScope,materialActivation:S,...Gm(t,y,_),nearEd25519SigningKeyId:Jt(g.ed25519.nearEd25519SigningKeyId),signerSlot:g.ed25519.signerSlot}),wa({ceremonyId:e.registrationCeremonyId,stage:`session_install`,startedAt:O,outcome:`success`});let k=performance.now();if(t.kind===`email_otp`&&_.remainingUses>0){let r=await el({registrationEstablishedSession:_,walletId:e.walletId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,thresholdSessionId:b.identity.thresholdSessionId,runtimePolicyScope:b.stableServerScope.runtimePolicyScope,signerSlot:g.ed25519.signerSlot,relayerUrl:e.relayerUrl,emailOtpAuthContext:t.emailOtpAuthContext}),a=Zp({walletId:e.walletId,nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,sessionState:r,joined:s,deferredNear:{status:`deferred`,admissionRequest:n.admissionRequest},admissionReceipt:n.admissionReceipt,authContext:t.emailOtpAuthContext});await e.context.signingEngine.activateEmailOtpEd25519RegistrationMaterialInternal({walletSession:{walletId:e.walletId,walletSessionUserId:String(e.walletId)},providerSubject:sr(t.emailOtpAuthContext),emailHashHex:ur(t.emailOtpAuthContext),signerSlot:g.ed25519.signerSlot,expectedOperationalPublicKey:c,expectedThresholdSessionId:b.identity.thresholdSessionId,bootstrap:a,material:C,envelope:pa(n.envelope),factorSecret32:i}),i=null}else if(t.kind===`passkey`){if(e.authMaterial.kind!==`passkey`)throw Error(`Deferred passkey registration has no Passkey authorization material`);if(!i)throw Error(`Deferred passkey registration has no custody factor secret`);await Eh({signingEngine:e.context.signingEngine,sessionAuthority:e.sessionAuthority,metadata:x,material:C,materialFacts:b,envelope:pa(n.envelope),ownedFactorSecret:new Uint8Array(i),rpId:e.authMaterial.rpId,credentialIdB64u:e.authMaterial.credentialIdB64u,passkeyPrfFirstB64u:e.authMaterial.prfFirstB64u,relayerUrl:e.relayerUrl}),i=null}e.authMaterial.kind===`passkey`&&await Kd({walletId:String(e.walletId),credentialIdB64u:e.authMaterial.credentialIdB64u,envelope:n.envelope}),wa({ceremonyId:e.registrationCeremonyId,stage:`signer_activation`,startedAt:k,outcome:`success`}),await wh(e.sessionAuthority);let A=performance.now(),j=await a;if(wa({ceremonyId:e.registrationCeremonyId,stage:`session_hydration_wait`,startedAt:A,outcome:j.kind===`completed`?`success`:`failure`}),j.kind===`failed`)throw j.error;await wh(e.sessionAuthority);let M=performance.now();return await V.completePendingNearRegistration({pending:d,walletSession:_.walletSession,operationCredential:_.operationCredential,nearAccountId:String(v)}),wa({ceremonyId:e.registrationCeremonyId,stage:`durable_ready`,startedAt:M,outcome:`success`}),r=`success`,{status:`near_ready`,updatedAtMs:Date.now(),nearAccountId:String(v)}}catch(t){let n=await V.getProfile(String(e.walletId)).catch(jh);if(n?.nearProvisioning?.status===`near_ready`)return n.nearProvisioning;let r=Ph(t);try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:r})}catch{}return{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:Se(t,`registration`,String(e.walletId)),errorCode:r}}finally{await a,o.kind===`preparing`&&(await o.result,await e.context.signingEngine.discardSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}).catch(mh)),i&&Up(i),wa({ceremonyId:e.registrationCeremonyId,stage:`provisioning_total`,startedAt:n,outcome:r}),wa({ceremonyId:e.registrationCeremonyId,stage:`registration_total`,startedAt:e.registrationStartedAt,outcome:r})}}async function Nh(e){try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_provisioning`})}catch(t){let n=Ph(t),r={status:`near_failed_retryable`,updatedAtMs:Date.now(),error:Se(t,`registration`,String(e.walletId)),errorCode:n};try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:n})}catch{}Td(e.walletId,r);return}await Dd({walletId:e.walletId,nowMs:Date.now,attempt:Mh.bind(void 0,e.commit)})}function Ph(e){let t=e instanceof Error?e.message:String(e);return t.includes(`finalize`)?`near_finalize_failed`:t.includes(`seal`)||t.includes(`Yao`)?`near_seal_failed`:t.includes(`wallet session`)?`near_capability_persist_failed`:`near_provisioning_failed`}async function Fh(e){let t=Ph(e.error),n=Se(e.error,`registration`,String(e.walletId));try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:t})}catch{}return Td(e.walletId,{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:n,errorCode:t}),{status:`retryable`,error:n,errorCode:t}}async function Ih(e){try{return await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_pending`}),Td(e.walletId,{status:`near_pending`,updatedAtMs:Date.now()}),{status:`pending`}}catch(t){return await Fh({context:e.context,walletId:e.walletId,error:t})}}async function Lh(e){let{context:t,wallet:n,signerSelection:r}=e,i=e.options||{},{onEvent:a,onError:o,afterCall:s}=i,l=performance.now(),u=new Qa(l),f=_n(),p=null,m=null,h=Fm(n.kind===`provided`?String(n.walletId):`wallet-registration`);$(a,h,{authMethod:e.authMethod.kind,phase:B.STEP_01_STARTED,status:`started`});try{let o=Am(`wallet-registration-finalize`),h=await Xm({context:t,authMethod:e.authMethod,wallet:n,signerSelection:r,recorder:u,passkeyExecution:e.passkeyExecution});e.authMethod.kind===`email_otp`&&mm({recorder:u,warmup:h.registrationWarmup});let{relayerUrl:g,setup:_}=h,v=nh(rh(_,e.kind).ecdsa),y=Zm({passkeyExecution:e.passkeyExecution,ceremonyId:_.registrationCeremonyId}),b={intent:_.intent,registrationIntentDigestB64u:_.registrationIntentDigestB64u},x=b.intent.walletId,S=Fm(String(x)),C=null,w=``,T=``,E=``,D=null,O=null,k=null,A;if(e.authMethod.kind===`passkey`){$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_create`,overlay:`show`}});let n={uiMode:`modal`,behavior:`requireClick`,...e.confirmationConfigOverride??i?.confirmationConfig??{}};k=await u.measure(`authProofMs`,()=>gm({context:t,walletId:x,signerSlot:ih(e),registrationIntentDigestB64u:b.registrationIntentDigestB64u,options:i,confirmationConfigOverride:n,passkeyExecution:e.passkeyExecution})),u.capturePasskeyAuthDiagnostics(k.diagnostics),p=performance.now();let r=d(String(k.credential.rawId||k.credential.id||``).trim());if(!r.ok)throw Error(`passkey credential id ${r.error.message}`);A={kind:`passkey`,webauthnRegistration:k.webauthnRegistration,walletCustodyFactorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Qt({rpId:wp(e.authMethod.rpId),credentialIdB64u:r.value}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId}),walletCustodyFactorSecret:R(k.prfFirstB64u).buffer},$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_create`,overlay:`hide`}})}else{let n=e.authMethod,r=crypto.getRandomValues(new Uint8Array(32));m=r.slice(),O=r.slice().buffer;let i=await u.measure(`authProofMs`,()=>vf({authMethod:n,relayUrl:g,walletId:String(x),registrationIntentDigestB64u:b.registrationIntentDigestB64u}));C=jm({recorder:u,context:t,authMethod:n,relayerUrl:g,walletId:String(x),providerSubject:i.providerSubject,clientSecret32:r}),w=i.registrationAuthorityId,T=i.email,E=i.providerSubject,D=Vm(i.proof),A={kind:`email_otp`,emailOtpRegistrationProof:i.proof,walletCustodyFactorSecret:O}}let j=c(_.walletAuthMethodId);if(!j.ok)throw Error(`Registration setup auth-method identity is invalid: ${j.error.message}`);let M;if(e.authMethod.kind===`passkey`){if(!k)throw Error(`ECDSA registration is missing its verified passkey authority`);M=await ct({authority:{...Xc({walletId:x,rpId:e.authMethod.rpId,credential:k.credential}),bindingId:j.value}})}else{if(!D)throw Error(`Email OTP registration is missing its verified provider`);M=await ct({authority:{...Ot({walletId:x,provider:D,providerUserId:E,emailHashHex:await Bm(T)}),bindingId:j.value}})}$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_STARTED,status:`running`});let N={value:e.kind===`near_ed25519_and_evm_family_ecdsa`?A.walletCustodyFactorSecret.slice(0):null},ee=null,P;try{P=await u.measure(`ecdsaRegistrationTotalMs`,()=>eh({home:_.home,context:t,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signerPlanKind:e.kind,signedSetup:_.signedSetup,ecdsaPrepare:v,clientCeremony:y,authority:A,materialAuthority:M,idempotencyKey:o,resolveActivateEmailOtp:async()=>{let t=null,n=null;if(e.authMethod.kind===`email_otp`){let e=await Zc({material:C,operation:`activate`});t=e.emailOtpEnrollment??null,n=JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Zt({enrollmentId:e.enrollmentId,enrollmentSealKeyVersion:e.enrollmentSealKeyVersion}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId})}return{enrollment:t,walletCustodyFactorJson:n}},traceContext:f,registrationTiming:u,confirmRecoveryCodesBackedUp:Vp.bind(void 0,t,String(x),i.recoveryCodeBackup),persistPendingCommit:async t=>{let n={operation:`registration_activate`,registrationCeremonyId:_.registrationCeremonyId,idempotencyKey:o,walletId:String(x),walletAuthMethodId:String(b.intent.foundingWalletAuthMethodId),signedSetup:String(_.signedSetup),auth:ah({authMethod:e.authMethod,passkeyAuthority:k,email:T,registrationAuthorityId:w,providerSubject:E,emailOtpEnrollment:t.emailOtpEnrollment})};if(t.signerPlanKind===`near_ed25519_and_evm_family_ecdsa`){let e=Date.now(),r=ch(Mp({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial,createdAtMs:e,updatedAtMs:e})),i=yn(r,t.deferredNear.admissionRequest);await V.putPendingWalletRegistrationCommits([r,i]),ee=r;return}ee=await sh({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial})},startDeferredNearCustody:hh.bind(void 0,{home:_.home,context:t,factorSecretOwner:N,registrationCeremonyId:_.registrationCeremonyId,relayerUrl:g,signedSetup:String(_.signedSetup),traceContext:f})}))}finally{Up(A.walletCustodyFactorSecret),N.value&&=(Up(N.value),null)}let te=P.session;if(P.activated.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration activate returned a different signer branch`);let F=kp(P.activated),ne=P.activateEmailOtp.enrollment;if(F.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration finalize returned a different signer branch`);if(e.authMethod.kind===`email_otp`&&!nr(F))throw Error(`Email OTP registration finalize returned a different auth method`);u.captureRouteDiagnostics(F.registrationDiagnostics);let re=F.ecdsa.walletKeys;if(re.length===0)throw Error(`Wallet registration finalize did not return ECDSA wallet keys`);let I=await Dp({authMethod:e.authMethod,configs:t.configs,walletId:Ie(F.walletId),finalized:F,passkeyAuthority:k,email:T,providerSubject:E,registrationAuthorityId:w}),L=Ap({walletId:Ie(F.walletId),auth:I,foundingAuthority:F.foundingAuthority,foundingAuthMethod:F.foundingAuthMethod,ecdsa:Op({session:te,walletKeys:re,expectedChainTargets:te.chainTargets})});$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`}),$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let ie=Ie(F.walletId),ae={status:`pending`};e.kind===`near_ed25519_and_evm_family_ecdsa`?(await uh({context:t,relayerUrl:g,registrationTiming:u,pending:ch(ee),plan:L,activated:P.activated}),ae=await Ih({context:t,walletId:ie})):await zp({context:t,relayerUrl:g,registrationTiming:u,plan:L});let oe=fr.fromRegistration(g,L.ecdsa.session.registrationEstablishedSession);for(let e of te.chainTargets)vd({signingEngine:t.signingEngine,walletId:ie,chainTarget:e,trigger:`registration`,statusReads:oe});let se=L.ecdsa.walletKeys[0];if(e.authMethod.kind===`passkey`){if(!k)throw Error(`Passkey registration authority was not collected`);let n=L.ecdsa.session.registrationEstablishedSession;try{await Jp({signingEngine:t.signingEngine,commit:P.walletCustody.commitPayload,passkeyPrfFirstB64u:k.prfFirstB64u,walletId:String(x),walletAuthMethodId:String(L.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(n.walletSessionId),expiresAtMs:n.expiresAtMs})}catch(n){if(e.kind!==`near_ed25519_and_evm_family_ecdsa`)throw n;ae=await Fh({context:t,walletId:ie,error:n})}}else{if(I.kind!==`email_otp`||!m)throw Error(`Email OTP registration has no custody capability material`);let e=L.ecdsa.session.registrationEstablishedSession;await Yp({context:t,commit:P.walletCustody.commitPayload,factorSecret32:m,emailOtpAuthContext:I.emailOtpAuthContext,walletId:String(x),walletSessionId:String(e.walletSessionId),expiresAtMs:e.expiresAtMs})}if(e.kind===`near_ed25519_and_evm_family_ecdsa`){let e=fh({auth:L.auth,emailOtpEnrollment:ne,passkeyAuthority:k});try{Nh({context:t,walletId:ie,commit:{context:t,registrationTiming:u,registrationStartedAt:l,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signedSetup:_.signedSetup,headers:jc(f),nearCustodyWork:Sh.bind(void 0,P.deferredNearCustodyWork),sessionAuthority:{record:L.ecdsa.session.registrationEstablishedSession.walletSession,operationCredential:L.ecdsa.session.registrationEstablishedSession.operationCredential},expectedChainTargets:L.ecdsa.expectedChainTargets,walletId:ie,authMaterial:e}})}catch(e){let t=Ph(e);ae={status:`retryable`,error:Se(e,`registration`,String(ie)),errorCode:t},Td(ie,{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:ae.error,errorCode:t})}}e.kind===`evm_family_ecdsa`&&await V.deletePendingWalletRegistrationCommit({registrationCeremonyId:_.registrationCeremonyId,operation:`registration_activate`});let ce=e.kind===`near_ed25519_and_evm_family_ecdsa`?{success:!0,kind:`ecdsa_wallet_registered_near_pending`,walletId:F.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}],nearProvisioning:ae}:{success:!0,kind:`wallet_registered`,walletId:F.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}]};if($(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),$(a,S,{authMethod:e.authMethod.kind,phase:B.STEP_11_COMPLETED,status:`succeeded`}),p!==null){let e=performance.now();ro({callback:i.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-p,traceContext:f}),ro({callback:i.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:f})}return no(eo({recorder:u,authMethod:e.authMethod.kind,signerSet:Pa(e.signerPlan)})),Hh(e.context,ce,e.authMethod.kind),s?.(!0,ce),ce}catch(t){let n=Im(t),r=Se(t,`registration`,h);p!==null&&ro({callback:i.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-p,traceContext:f});let c=Lm(r,n);o?.(c),$(a,h,{authMethod:e.authMethod.kind,phase:B.FAILED,status:`failed`,message:r,interaction:{kind:`passkey_create`,overlay:`hide`},error:{...n?{code:n}:{},message:r}});let l={success:!1,error:r,...n?{errorCode:n}:{}};return no(to({recorder:u,authMethod:e.authMethod.kind,signerSet:Pa(e.signerPlan),errorCode:n||null})),s?.(!1),l}finally{m?.fill(0)}}async function Rh(e){let{context:t,options:n}=e,r=Fm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),i=new Qa(performance.now()),a=null;$(n.onEvent,r,{authMethod:`email_otp`,phase:B.STEP_01_STARTED,status:`started`});try{let r=await Ym({context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:i});mm({recorder:i,warmup:r.registrationWarmup});let{relayerUrl:o,setup:s}=r,c=s.intent.walletId,l=Fm(String(c)),u=await i.measure(`authProofMs`,vf.bind(void 0,{authMethod:e.authMethod,relayUrl:o,walletId:String(c),registrationIntentDigestB64u:s.registrationIntentDigestB64u})),d=crypto.getRandomValues(new Uint8Array(32));a=d.slice();let f=d.slice().buffer,p=jm({recorder:i,context:t,authMethod:e.authMethod,relayerUrl:o,walletId:String(c),providerSubject:u.providerSubject,clientSecret32:d});$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_05_ED25519_SIGNER_PREPARE_STARTED,status:`running`});let m=await i.measure(`walletRegisterStartMs`,Un.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:s.signedSetup,headers:{...jc(),...j(s.home)},kind:`email_otp`,emailOtpRegistrationProof:u.proof}));if(m.kind!==`near_ed25519`)throw Error(`Ed25519-only registration respond returned a different signer branch`);let h=await Zc({material:p,operation:`finalize`}),g;try{g=await t.signingEngine.establishWalletCustodyNearEd25519KeySet({home:s.home,walletId:String(c),factor:{factorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Zt({enrollmentId:h.enrollmentId,enrollmentSealKeyVersion:h.enrollmentSealKeyVersion}),walletAuthMethodId:s.intent.foundingWalletAuthMethodId}),factorSecret:f},nearEd25519SigningKeyId:m.ed25519.admissionRequest.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:s.registrationCeremonyId,admissionRequest:m.ed25519.admissionRequest,admissionReceipt:m.ed25519.admissionReceipt,participantIds:m.ed25519.admissionRequest.participant_ids,routerOrigin:new URL(o).origin,authorization:`Bearer ${String(s.signedSetup)}`})}finally{Up(f)}await Vp(t,String(c),n.recoveryCodeBackup,g.recoveryCodes);let _=rn(g.commitPayload);if(!g.localMaterial)throw Error(`Email OTP registration produced no sealed local custody material`);let v=await km({registrationCeremonyId:s.registrationCeremonyId,activationReference:g.activationReference}),y=await sh({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:v,walletId:String(c),walletAuthMethodId:String(s.intent.foundingWalletAuthMethodId),signedSetup:String(s.signedSetup),auth:{kind:`email_otp`,email:u.email,registrationAuthorityId:u.registrationAuthorityId,providerSubject:u.providerSubject,enrollment:h.emailOtpEnrollment},localMaterial:{keyFamilies:[`ed25519`],custodyCommit:_,ed25519:{activationReference:g.activationReference,localMaterial:g.localMaterial,metadata:Gp(g)}}}),b=`ed25519:${Ee(g.metadata.registeredPublicKey)}`,x=await i.measure(`walletRegisterFinalizeMs`,Qn.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signedSetup:s.signedSetup,headers:{...jc(),...j(s.home)},idempotencyKey:v,ed25519:{activationReference:g.activationReference},auth:{kind:`email_otp`,enrollment:h.emailOtpEnrollment},walletCustodyCommit:_}));if(!x.ok)throw Error(`Deferred NEAR provisioning did not complete`);if(i.captureRouteDiagnostics(x.registrationDiagnostics),x.kind!==`near_ed25519`)throw Error(`Wallet registration finalize returned a different signer branch`);if(!nr(x))throw Error(`Email OTP registration finalize returned a different auth method`);if(x.walletCustody?.status!==`committed`){let e=x.walletCustody?.status??`not_reported`;throw Error(`Wallet custody did not commit (${e})`)}if(x.ed25519.signerSlot!==e.ed25519Selection.signerSlot)throw Error(`Ed25519 Yao finalize returned a different signer slot`);let S=Pc(x.registrationEstablishedSession);rl({clientPublicKey:b,finalized:x,expectedRegistrationAuthorityId:u.registrationAuthorityId,expectedWalletId:c});let C=await Dp({authMethod:e.authMethod,configs:t.configs,walletId:Ie(x.walletId),finalized:x,passkeyAuthority:null,email:u.email,providerSubject:u.providerSubject,registrationAuthorityId:u.registrationAuthorityId});if(C.kind!==`email_otp`)throw Error(`Email OTP Ed25519 registration produced a different persistence authority`);$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_05_ED25519_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let w=Qc({admissionRequest:m.ed25519.admissionRequest,finalized:x.ed25519,walletId:c,expectedRuntimePolicyScope:I(s.intent.runtimePolicyScope)}),T=g.metadata,E=z(x.ed25519.nearAccountId),D=Wp({established:g,walletId:String(x.walletId),nearAccountId:String(E),nearEd25519SigningKeyId:x.ed25519.nearEd25519SigningKeyId,signerSlot:x.ed25519.signerSlot}),O=await tt({walletId:x.walletId,nearAccountId:E,nearEd25519SigningKeyId:x.ed25519.nearEd25519SigningKeyId,email:C.email,registrationAuthorityId:C.registrationAuthorityId,authority:C.authority,signerSlot:x.ed25519.signerSlot,operationalPublicKey:b,relayerKeyId:x.ed25519.relayerKeyId,keyVersion:x.ed25519.keyVersion,participantIds:[...x.ed25519.participantIds],custodyMaterial:D}),k=await V.publishPendingWalletRegistrationCommit({pending:y,ecdsaContinuity:[],authority:x.authority,foundingAuthority:{authority:x.foundingAuthority,authMethod:x.foundingAuthMethod},request:{operation:`near_provisioning`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:v,walletId:x.walletId,walletAuthMethodId:x.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:S.walletSession,operationCredential:S.operationCredential},registration:O});fr.acceptRegistrationSession(o,S);let A=k.signerActivations[1];if(!A||A.signerSlot!==x.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);if(await t.signingEngine.activateAuthenticatedWalletState({walletId:x.walletId,nearAccountId:E,signerSlot:x.ed25519.signerSlot,nearClient:t.nearClient}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:x.walletId,nearAccountId:E,thresholdSessionId:w.identity.thresholdSessionId,runtimePolicyScope:w.stableServerScope.runtimePolicyScope,materialActivation:tr(T),auth:{kind:`email_otp`,providerSubjectId:u.providerSubject},nearEd25519SigningKeyId:Jt(x.ed25519.nearEd25519SigningKeyId),signerSlot:x.ed25519.signerSlot,remainingUses:S.remainingUses,expiresAtMs:S.expiresAtMs}),!a)throw Error(`Email OTP registration has no custody capability material`);await Yp({context:t,commit:_,factorSecret32:a,emailOtpAuthContext:C.emailOtpAuthContext,walletId:String(x.walletId),walletSessionId:String(S.walletSessionId),expiresAtMs:S.expiresAtMs}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),$(n.onEvent,l,{authMethod:`email_otp`,phase:B.STEP_11_COMPLETED,status:`succeeded`});let M={success:!0,kind:`wallet_registered`,walletId:x.walletId,capabilities:[{kind:`near_ed25519`,accountProvisioning:x.accountProvisioning,resolvedAccount:x.resolvedAccount,nearEd25519SigningKeyId:Jt(x.ed25519.nearEd25519SigningKeyId),operationalPublicKey:b,nearAccountId:z(x.ed25519.nearAccountId),transactionId:x.resolvedAccount.kind===`sponsored_named_account`?x.resolvedAccount.transactionHash:null}]};return no(eo({recorder:i,authMethod:`email_otp`,signerSet:Pa(e.signerPlan)})),Hh(t,M,`email_otp`),n.afterCall?.(!0,M),M}catch(t){let a=Im(t),o=Se(t,`registration`,r);n.onError?.(Lm(o,a)),$(n.onEvent,r,{authMethod:`email_otp`,phase:B.FAILED,status:`failed`,message:o,error:{...a?{code:a}:{},message:o}});let s={success:!1,error:o,...a?{errorCode:a}:{}};return no(to({recorder:i,authMethod:`email_otp`,signerSet:Pa(e.signerPlan),errorCode:a||null})),n.afterCall?.(!1),s}finally{a?.fill(0)}}function zh(){}async function Bh(e){let{context:t,options:n}=e,r=Fm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),i=_n(),a=null,o={kind:`none`};$(n.onEvent,r,{authMethod:`passkey`,phase:B.STEP_01_STARTED,status:`started`});try{let r=new Qa(performance.now()),{relayerUrl:s,setup:c}=await Xm({context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:r,passkeyExecution:e.passkeyExecution});r.markNearStage(c.registrationCeremonyId,`near_only.setup`);let l=tl(c.intent),u=Fm(String(l.walletId));$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_create`,overlay:`show`}});let f=c.kind===`near_ed25519`&&c.ed25519.status===`described`?c.ed25519:null,p=gm({context:t,walletId:l.walletId,signerSlot:e.ed25519Selection.signerSlot,registrationIntentDigestB64u:c.registrationIntentDigestB64u,options:n,confirmationConfigOverride:{uiMode:`modal`,behavior:`requireClick`,...e.confirmationConfigOverride??n.confirmationConfig??{}},passkeyExecution:e.passkeyExecution}).then(e=>(a=performance.now(),r.capturePasskeyAuthDiagnostics(e.diagnostics),r.markNearStage(c.registrationCeremonyId,`near_only.authentication`),$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_create`,overlay:`hide`}}),e)),m=zm(n.onEvent,u,B.STEP_05_ED25519_SIGNER_PROVISION_DELAYED),h=async(e,t)=>{let n=await m(Un({relayerUrl:s,registrationCeremonyId:c.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:c.signedSetup,headers:{...jc(i),...j(c.home)},kind:`passkey`,webauthnRegistration:e.webauthnRegistration,...t?{ed25519Execution:t}:{},onServerTiming:Sa.bind(void 0,r)}));if(r.markNearStage(c.registrationCeremonyId,`near_only.respond`),n.kind!==`near_ed25519`)throw Error(`Ed25519-only registration respond returned a different signer branch`);return n.ed25519},g=e=>{let t=d(String(e.credential.rawId||e.credential.id||``).trim());if(!t.ok)throw Error(`passkey credential id ${t.error.message}`);return t.value},_=null,v=t=>(_=R(t.prfFirstB64u).buffer,{factorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Qt({rpId:wp(e.authMethod.rpId),credentialIdB64u:g(t)}),walletAuthMethodId:c.intent.foundingWalletAuthMethodId}),factorSecret:_}),y=(e,n)=>kh({signingEngine:t.signingEngine,ceremonyId:c.registrationCeremonyId,thresholdSessionId:n,prfFirstB64u:e.prfFirstB64u}),b=e=>({home:c.home,walletId:String(l.walletId),nearEd25519SigningKeyId:e.admissionRequest.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:c.registrationCeremonyId,admissionRequest:e.admissionRequest,admissionReceipt:e.admissionReceipt,participantIds:e.admissionRequest.participant_ids,routerOrigin:new URL(s).origin,authorization:`Bearer ${String(c.signedSetup)}`,traceContext:i}),x,S,C;try{if(f){S=f;let e=t.signingEngine.establishWalletCustodyNearEd25519KeySet({...b(f),factor:{factorAfterRouterRound:async()=>v(await p)},executeWithProof:async e=>{let t=await h(await p,JSON.parse(e));if(!Nt(t.admissionReceipt.binding,f.admissionReceipt.binding))throw Error(`Registration respond issued another admission than setup described`);return t.status===`executed`?JSON.stringify(t.activationResult):null}});e.catch(zh),x=await p,o=y(x,f.admissionRequest.scope.threshold_session_id),C=await m(e)}else x=await p,S=await h(x),o=y(x,S.admissionRequest.scope.threshold_session_id),C=await m(t.signingEngine.establishWalletCustodyNearEd25519KeySet({...b(S),factor:v(x)}))}finally{_&&Up(_)}let w={value:g(x)};r.markNearStage(c.registrationCeremonyId,`near_only.custody`),await Vp(t,String(l.walletId),n.recoveryCodeBackup,C.recoveryCodes);let T=rn(C.commitPayload);if(!C.localMaterial)throw Error(`Passkey registration produced no sealed local custody material`);let E=await km({registrationCeremonyId:c.registrationCeremonyId,activationReference:C.activationReference}),D=await sh({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:E,walletId:String(l.walletId),walletAuthMethodId:String(c.intent.foundingWalletAuthMethodId),signedSetup:String(c.signedSetup),auth:{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:w.value,transports:[...x.webauthnRegistration.response.transports]},localMaterial:{keyFamilies:[`ed25519`],custodyCommit:T,ed25519:{activationReference:C.activationReference,localMaterial:C.localMaterial,metadata:Gp(C)}}}),O=`ed25519:${Ee(C.metadata.registeredPublicKey)}`;if(r.markNearStage(c.registrationCeremonyId,`near_only.provision_checkpoint`),o.kind!==`preparing`)throw Error(`NEAR registration session seal preparation is missing`);let k=await o.result;if(k.kind===`failed`)throw k.error;let A=await t.signingEngine.readPreparedSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}),M=await zm(n.onEvent,u,B.STEP_06_RELAY_BOOTSTRAP_DELAYED)(Qn({relayerUrl:s,registrationCeremonyId:c.registrationCeremonyId,signedSetup:c.signedSetup,headers:{...jc(i),...j(c.home)},idempotencyKey:E,ed25519:{activationReference:C.activationReference},auth:{kind:`passkey`},sessionSeal:{thresholdSessionId:o.thresholdSessionId,ciphertext:A.ciphertext},walletCustodyCommit:T}));if(r.markNearStage(c.registrationCeremonyId,`near_only.finalize`),!M.ok||M.kind!==`near_ed25519`)throw Error(`Deferred NEAR provisioning returned a different signer branch`);if(!M.sessionSeal)throw Error(`NEAR finalization did not return the prepared session seal`);if(C.commitPayload&&M.walletCustody?.status!==`committed`){let e=M.walletCustody?.status??`not_reported`,t=M.walletCustody?.status===`rejected`?`: ${M.walletCustody.reason}`:``;throw Error(`Wallet custody did not commit (${e})${t}. The recovery codes shown are not usable.`)}let N=Pc(M.registrationEstablishedSession),ee=nl({clientPublicKey:O,finalized:M,expectedRpId:e.authMethod.rpId,expectedWalletId:l.walletId}),P=z(M.ed25519.nearAccountId),te=Tp({finalized:M,credential:x.credential}),F=Qc({admissionRequest:S.admissionRequest,finalized:M.ed25519,walletId:l.walletId,expectedRuntimePolicyScope:I(l.runtimePolicyScope)}),ne=C.metadata,re=Wp({established:C,walletId:String(M.walletId),nearAccountId:String(P),nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,signerSlot:M.ed25519.signerSlot});await Xp({commit:C.commitPayload,walletId:String(M.walletId),activatedAtMs:Date.now()}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:M.walletId,nearAccountId:z(M.ed25519.nearAccountId),thresholdSessionId:F.identity.thresholdSessionId,runtimePolicyScope:F.stableServerScope.runtimePolicyScope,materialActivation:tr(ne),auth:{kind:`passkey`,rpId:pt(ee.rpId),credentialIdB64u:ee.credentialIdB64u},nearEd25519SigningKeyId:Jt(M.ed25519.nearEd25519SigningKeyId),signerSlot:M.ed25519.signerSlot});let L=et({walletId:M.walletId,nearAccountId:P,nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,rpId:wp(ee.rpId),credential:x.credential,credentialPublicKeyB64u:te,signerSlot:M.ed25519.signerSlot,operationalPublicKey:O,relayerKeyId:M.ed25519.relayerKeyId,keyVersion:M.ed25519.keyVersion,participantIds:[...M.ed25519.participantIds],custodyMaterial:re}),ie=await V.publishPendingWalletRegistrationCommit({pending:D,ecdsaContinuity:[],authority:M.authority,foundingAuthority:{authority:M.foundingAuthority,authMethod:M.foundingAuthMethod},request:{operation:`near_provisioning`,registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:E,walletId:M.walletId,walletAuthMethodId:M.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:N.walletSession,operationCredential:N.operationCredential},registration:L});fr.acceptRegistrationSession(s,N);let ae=ie.signerActivations[1];if(!ae||ae.signerSlot!==M.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);r.markNearStage(c.registrationCeremonyId,`near_only.publication`);let oe=await Dh({signingEngine:t.signingEngine,ceremonyId:c.registrationCeremonyId,input:al({session:N,ceremonyId:c.registrationCeremonyId,walletId:String(M.walletId),relayerUrl:s,prfFirstB64u:x.prfFirstB64u,preparedServerSeal:{preparationId:o.preparationId,...M.sessionSeal},restore:{rpId:ee.rpId,nearAccountId:String(P),nearEd25519SigningKeyId:M.ed25519.nearEd25519SigningKeyId,relayerKeyId:M.ed25519.relayerKeyId,participantIds:M.ed25519.participantIds,signerSlot:M.ed25519.signerSlot,credentialIdB64u:ee.credentialIdB64u,materialActivation:tr(ne)}})});if(oe.kind===`failed`)throw oe.error;if(o={kind:`consumed`},r.markNearStage(c.registrationCeremonyId,`near_only.session_hydration`),await Eh({signingEngine:t.signingEngine,sessionAuthority:{record:N.walletSession,operationCredential:N.operationCredential},metadata:ne,material:re,materialFacts:F,envelope:Kp(C.commitPayload),ownedFactorSecret:R(x.prfFirstB64u),rpId:ee.rpId,credentialIdB64u:ee.credentialIdB64u,passkeyPrfFirstB64u:x.prfFirstB64u,relayerUrl:s}),r.markNearStage(c.registrationCeremonyId,`near_only.material_activation`),await Jp({signingEngine:t.signingEngine,commit:C.commitPayload,passkeyPrfFirstB64u:x.prfFirstB64u,walletId:String(M.walletId),walletAuthMethodId:String(M.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(N.walletSessionId),expiresAtMs:N.expiresAtMs}),r.markNearStage(c.registrationCeremonyId,`near_only.export_capability`),await t.signingEngine.activateAuthenticatedWalletState({walletId:M.walletId,nearAccountId:P,signerSlot:M.ed25519.signerSlot,nearClient:t.nearClient}),$(n.onEvent,u,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),a!==null){let e=performance.now();ro({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-a,traceContext:i}),ro({callback:n.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:i})}r.markNearStage(c.registrationCeremonyId,`near_only.wallet_ready`),no(eo({recorder:r,authMethod:`passkey`,signerSet:Pa(e.signerPlan)}));let se={success:!0,kind:`wallet_registered`,walletId:M.walletId,capabilities:[{kind:`near_ed25519`,accountProvisioning:M.accountProvisioning,resolvedAccount:M.resolvedAccount,nearEd25519SigningKeyId:Jt(M.ed25519.nearEd25519SigningKeyId),operationalPublicKey:O,nearAccountId:z(M.ed25519.nearAccountId),transactionId:M.resolvedAccount.kind===`sponsored_named_account`?M.resolvedAccount.transactionHash:null}]};return Hh(t,se,`passkey`),n.afterCall?.(!0,se),se}catch(e){let t=Im(e),o=Se(e,`registration`,r);a!==null&&ro({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-a,traceContext:i}),n.onError?.(Lm(o,t)),$(n.onEvent,r,{authMethod:`passkey`,phase:B.FAILED,status:`failed`,message:o,interaction:{kind:`passkey_create`,overlay:`hide`},error:{...t?{code:t}:{},message:o}});let s={success:!1,error:o,...t?{errorCode:t}:{}};return n.afterCall?.(!1),s}finally{o.kind===`preparing`&&(await o.result,await t.signingEngine.discardSigningSessionHydration({thresholdSessionId:o.thresholdSessionId,preparationId:o.preparationId}).catch(mh))}}async function Vh(e){let t=em(e.signerSelection),n=Ne(t);if(n){let r=Me(t);if(r)return await Lh({kind:`near_ed25519_and_evm_family_ecdsa`,context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,ecdsaSelection:r,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}});if(e.authMethod.kind===`email_otp`){if(e.passkeyExecution.kind!==`collect_during_registration`)throw Error(`Prepared registration authority requires passkey authentication`);return await Rh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,options:e.options,passkeyExecution:e.passkeyExecution})}return await Bh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}})}let r=Me(t);if(!r)throw Error(`Wallet registration requires an ECDSA signer branch`);return await Lh({kind:`evm_family_ecdsa`,context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ecdsaSelection:r,options:e.options,passkeyExecution:e.passkeyExecution,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{}})}function Hh(e,t,n){e.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.walletId,authMethod:n})}async function Uh(e){try{return await Vh({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,options:e.options,authenticatorOptions:e.authenticatorOptions,...e.confirmationConfigOverride?{confirmationConfigOverride:e.confirmationConfigOverride}:{},passkeyExecution:{kind:`collect_during_registration`}})}finally{e.context.signingEngine.closeRegistrationPreparationModal()}}function Wh(e,t,n){try{$(e,t,n)}catch{}}function Gh(e,t){try{e?.(t)}catch{}}function Kh(e,t,n){try{t&&n?e?.(!0,n):e?.(!1)}catch{}}function qh(e){let t=[];for(let n of e){let e=String(n.credentialId||``).trim();e&&t.push({id:e,type:`public-key`,transports:Rm(n.transports)})}if(t.length===0)throw Error(`Wallet add-signer requires an existing passkey credential`);return t}function Jh(e,t){let n=String(e.id||``).trim(),r=String(e.rawId||``).trim();if(!n||!r||n!==r)throw Error(`Wallet add-signer selected an invalid passkey credential identity`);for(let e of t)if(e.id===r)return r;throw Error(`Wallet add-signer selected a passkey outside the authorized wallet`)}async function Yh(e){if(e.started.intent.walletId!==e.walletId)throw Error(`Wallet add-signer start returned a different wallet`);if(await gr(e.started.intent)!==e.expectedDigestB64u)throw Error(`Wallet add-signer start returned a different intent`);if(!String(e.started.addSignerCeremonyId||``).trim())throw Error(`Wallet add-signer start returned an invalid ceremony ID`)}function Xh(e,t){return e.length===2&&t.length===2&&e[0]===t[0]&&e[1]===t[1]}function Zh(e){let t=e.started.intent.signerSelection;if(t.mode!==`ed25519`)throw Error(`Wallet add-signer start intent changed signer branch`);let n=t.ed25519,r=e.started.ed25519.admissionRequest,i=e.finalized,a=i.ed25519,o=De(e.clientPublicKey);if(i.walletId!==e.walletId||i.rpId!==e.rpId||i.credentialIdB64u!==e.credentialIdB64u||a.publicKey!==e.clientPublicKey||a.nearAccountId!==o||a.signerSlot!==n.signerSlot||a.keyVersion!==n.keyVersion||a.recoveryExportCapable!==!0||!Xh(a.participantIds,n.participantIds)||a.nearEd25519SigningKeyId!==r.application_binding.near_ed25519_signing_key_id||a.relayerKeyId!==r.scope.signing_worker_id||r.application_binding.wallet_id!==e.walletId||r.application_binding.key_creation_signer_slot!==n.signerSlot)throw Error(`Wallet add-signer finalize returned mismatched Ed25519 Yao identity`);return i}function Qh(e){let t=e.intent.signerSelection;if(t.mode!==`ed25519`)throw Error(`Wallet add-signer start intent changed signer branch`);return{version:e.intent.version,walletId:e.intent.walletId,signerSelection:t,...e.intent.runtimePolicyScope?{runtimePolicyScope:e.intent.runtimePolicyScope}:{},nonceB64u:e.intent.nonceB64u}}async function $h(e){if(e.started.intent.signerSelection.mode!==`ed25519`)throw Error(`Wallet add-signer start returned a different signer branch`);let t=null,n=null,r=null;try{if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody Ed25519 add-signer requires WebAuthn authorization`);let i=await Cf({kind:`verified_passkey_ed25519_yao_add_signer_input_v1`,verifiedIntent:{kind:`verified_passkey_ed25519_add_signer_intent_v1`,intent:Qh(e.started),addSignerIntentDigestB64u:e.intentResponse.addSignerIntentDigestB64u,addSignerIntentGrant:e.intentResponse.addSignerIntentGrant,addSignerCeremonyId:e.started.addSignerCeremonyId},verifiedAuthority:{kind:`verified_passkey_ed25519_add_signer_authority_v1`,walletId:e.walletId,addSignerIntentDigestB64u:e.intentResponse.addSignerIntentDigestB64u,credentialIdB64u:e.credentialIdB64u},admissionRequest:e.started.ed25519.admissionRequest,httpTransport:{kind:`passkey_ed25519_yao_http_transport_v1`,routerOrigin:new URL(e.relayerUrl).origin,fetch:globalThis.fetch}}),a=Ac(e.started.ed25519.custodyEnvelope);if(!a.ok)throw Error(a.reason);r=Uint8Array.from(R(e.passkeyPrfFirstB64u)).buffer;let o=await e.context.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:{kind:`discovery`},preparation:{kind:`fresh`},custodyJson:a.custodyJson,factorSecret:r,nearEd25519SigningKeyId:i.request.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:e.started.addSignerCeremonyId,admissionRequest:i.request,admissionReceipt:i.receipt,participantIds:i.request.participant_ids,routerOrigin:new URL(e.relayerUrl).origin,authorization:`Bearer ${String(e.intentResponse.addSignerIntentGrant)}`}),c=`ed25519:${Ee(o.metadata.registeredPublicKey)}`,l=await rr({relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:Am(`wallet-ed25519-add-signer-finalize`),kind:`near_ed25519`,ed25519:{activationReference:o.activationReference},custodyKeySet:{kind:`near_ed25519_v1`,keyManifestDigestB64u:o.commitPayload.keyManifestDigestB64u,registeredPublicKeyB64u:L(o.metadata.registeredPublicKey)}});if(l.kind!==`near_ed25519`)throw Error(`Wallet add-signer finalize returned a different signer branch`);let u=Zh({finalized:l,started:e.started,walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,clientPublicKey:c});Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let d=await e.context.signingEngine.finalizeWalletEd25519SignerRegistration({walletId:e.walletId,nearAccountId:z(u.ed25519.nearAccountId),nearEd25519SigningKeyId:u.ed25519.nearEd25519SigningKeyId,auth:{kind:`passkey`,credential:e.credential},signerSlot:u.ed25519.signerSlot,operationalPublicKey:c,relayerKeyId:u.ed25519.relayerKeyId,keyVersion:u.ed25519.keyVersion,participantIds:[...u.ed25519.participantIds]});if(d.signerSlot!==u.ed25519.signerSlot)throw Error(`Wallet add-signer persisted a different Ed25519 signer slot`);t=d.rollbackReceipt;let f=e.started.ed25519.admissionRequest,p=s(f.scope.threshold_session_id);if(!p.ok)throw Error(`Wallet add-signer threshold-session identity is invalid`);let m=o.metadata;return await e.context.signingEngine.persistWalletCustodyEd25519Material({binding:{kind:Qe,applicationBindingDigestB64u:o.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:L(m.registeredPublicKey),participantIds:m.participantIds,stateEpoch:String(m.stateEpoch),walletId:String(u.walletId),nearAccountId:String(u.ed25519.nearAccountId),nearEd25519SigningKeyId:u.ed25519.nearEd25519SigningKeyId,signerSlot:u.ed25519.signerSlot,signingWorkerId:m.scope.signing_worker_id,signingWorkerVerifyingShareB64u:L(m.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:o.localMaterial.b64u,nonceB64u:o.localMaterial.nonceB64u}}),n={nearAccountId:u.ed25519.nearAccountId,signerSlot:u.ed25519.signerSlot},await e.context.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:u.walletId,nearAccountId:z(u.ed25519.nearAccountId),thresholdSessionId:p.value,runtimePolicyScope:I(e.started.intent.runtimePolicyScope),materialActivation:tr(m),auth:{kind:`passkey`,rpId:pt(e.rpId),credentialIdB64u:e.credentialIdB64u},nearEd25519SigningKeyId:Jt(u.ed25519.nearEd25519SigningKeyId),signerSlot:u.ed25519.signerSlot}),t=null,Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),{success:!0,kind:`wallet_signer_added`,walletId:u.walletId,capabilities:[{kind:`near_ed25519`,nearEd25519SigningKeyId:Jt(u.ed25519.nearEd25519SigningKeyId),operationalPublicKey:c,nearAccountId:z(u.ed25519.nearAccountId)}]}}catch(r){let i=[];if(n)try{await e.context.signingEngine.deleteWalletCustodyEd25519Material({nearAccountId:n.nearAccountId,signerSlot:n.signerSlot})}catch(e){i.push(e instanceof Error?e.message:String(e))}if(t)try{await e.context.signingEngine.rollbackWalletEd25519SignerRegistration(t)}catch(e){i.push(e instanceof Error?e.message:String(e))}if(i.length>0){let e=r instanceof Error?r.message:String(r);throw Error(`${e}; add-signer cleanup failed: ${i.join(`; `)}`)}throw r}finally{r&&Up(r)}}async function eg(e){if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody ECDSA add-signer requires WebAuthn authorization`);let t=await Ad({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}),n=Uint8Array.from(R(e.passkeyPrfFirstB64u)).buffer,r;try{r=await Wc({context:e.context,relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,started:e.started.ecdsa,custodyEnvelope:e.started.ecdsa.custodyEnvelope,factorSecret:n,authority:t,registrationTiming:null})}finally{Up(n)}let i={relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:Am(`wallet-add-signer-finalize`),kind:`evm_family_ecdsa`,ecdsa:{expectedKeyHandles:[r.bootstrap.keyHandle]},custodyKeySet:r.custodyKeySet},a;try{a=await rr(i)}catch(e){if(!(e instanceof TypeError))throw e;a=await rr(i)}if(a.kind!==`evm_family_ecdsa`||a.walletId!==e.walletId||a.rpId!==e.rpId)throw Error(`Wallet add-signer finalize returned a different ECDSA identity`);let o=a.ecdsa.walletKeys,s=o[0];if(!s)throw Error(`Wallet add-signer finalize did not return ECDSA wallet keys`);let c=await Gc({context:e.context,pending:r});Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let l=await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ie(e.walletId),session:c,walletKeys:[s,...o.slice(1)]});return await e.context.signingEngine.storeWalletEcdsaSignerRecords({walletId:e.walletId,walletKeys:l}),await V.adoptAddedEcdsaSignerAuthority({authority:a.authority,materialActivation:c.materialActivation}),Wh(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),{success:!0,kind:`wallet_signer_added`,walletId:e.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:s.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:s.thresholdEcdsaPublicKeyB64u}]}}async function tg(e){switch(e.signerSelection.mode){case`ed25519`:if(e.started.kind!==`near_ed25519`)throw Error(`Wallet add-signer start returned a different signer branch`);return await $h({context:e.input.context,walletId:e.input.walletId,rpId:e.input.rpId,relayerUrl:e.input.relayerUrl,intentResponse:e.input.intentResponse,credential:e.input.credential,credentialIdB64u:e.input.credentialIdB64u,passkeyPrfFirstB64u:e.input.passkeyPrfFirstB64u,eventAccountId:e.input.eventAccountId,onEvent:e.input.onEvent,started:e.started});case`ecdsa`:if(e.started.kind!==`evm_family_ecdsa`)throw Error(`Wallet add-signer start returned a different signer branch`);return await eg({context:e.input.context,walletId:e.input.walletId,rpId:e.input.rpId,relayerUrl:e.input.relayerUrl,intentResponse:e.input.intentResponse,credential:e.input.credential,credentialIdB64u:e.input.credentialIdB64u,passkeyPrfFirstB64u:e.input.passkeyPrfFirstB64u,eventAccountId:e.input.eventAccountId,onEvent:e.input.onEvent,started:e.started});default:return q(e.signerSelection)}}async function ng(e){let{context:t,signerSelection:n}=e,r=e.options||{},i=qt(String(e.walletId||``).trim()),a=Fm(String(i)),o=wp(String(e.rpId||``).trim());Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_01_STARTED,status:`started`});try{let e=String(t.configs.network.relayer.url||``).trim();if(!e)throw Error(`addSigner requires relayer.url`);let s=Od(t.configs);if(!s)throw Error(`addSigner requires registration.publishableKey and registration.projectEnvironmentId`);let c=await Xn({relayerUrl:e,walletId:i,request:{walletId:i,rpId:o,signerSelection:n},auth:{publishableKey:s.publishableKey,environmentId:s.projectEnvironmentId}});if(await gr(c.intent)!==c.addSignerIntentDigestB64u)throw Error(`Add-signer intent digest mismatch`);Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_assert`,overlay:`show`}});let l=qh(await V.listProfileAuthenticators(String(i))),u=await t.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(i),challengeB64u:c.addSignerIntentDigestB64u,allowCredentials:l,includeSecondPrfOutput:!1}),d=Jh(u,l),f=wl(u,`Wallet add-signer authorization`);Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let p=await Vn({relayerUrl:e,walletId:i,addSignerIntentGrant:c.addSignerIntentGrant,addSignerIntentDigestB64u:c.addSignerIntentDigestB64u,intent:c.intent,auth:{kind:`webauthn_assertion`,rpId:o,credential:zn(u),expectedChallengeDigestB64u:c.addSignerIntentDigestB64u}});await Yh({started:p,walletId:i,expectedDigestB64u:c.addSignerIntentDigestB64u});let m=await tg({input:{context:t,walletId:i,rpId:o,relayerUrl:e,intentResponse:c,credential:u,credentialIdB64u:d,passkeyPrfFirstB64u:f,eventAccountId:a,onEvent:r.onEvent},signerSelection:n,started:p});return Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),Kh(r.afterCall,!0,m),m}catch(e){let t=Im(e),n=Se(e,`registration`,a);Gh(r.onError,Lm(n,t)),Wh(r.onEvent,a,{authMethod:`passkey`,phase:B.FAILED,status:`failed`,message:n,interaction:{kind:`passkey_assert`,overlay:`hide`},error:{...t?{code:t}:{},message:n}});let i={success:!1,error:n,...t?{errorCode:t}:{}};return Kh(r.afterCall,!1),i}}export{cu as $,Jr as $t,Ad as A,qs as At,Iu as B,Eo as Bt,vf as C,oc as Ct,qd as D,hc as Dt,Bd as E,dc as Et,Ed as F,Xs as Ft,mu as G,va as Gt,xu as H,so as Ht,vd as I,Us as It,du as J,fa as Jt,lu as K,ga as Kt,gd as L,Hs as Lt,Od as M,Ls as Mt,wd as N,Is as Nt,Kd as O,_c as Ot,Cd as P,Ps as Pt,iu as Q,ra as Qt,_d as R,zs as Rt,Tf as S,Dc as St,ff as T,rc as Tt,wu as U,co as Ut,Fu as V,ho as Vt,Cu as W,_a as Wt,au as X,Ni as Xt,pu as Y,pa as Yt,ou as Z,ua as Zt,Pf as _,Ac as _t,Uh as a,Nr as an,Zl as at,ep as b,Cc as bt,Cp as c,Hl as ct,xp as d,Pl as dt,Ir as en,ru as et,bp as f,Nl as ft,op as g,Jc as gt,ip as h,wl as ht,Om as i,Mr as in,Rl as it,kd as j,Rs as jt,Md as k,Ys as kt,Sp as l,Ql as lt,pp as m,Cl as mt,Em as n,Pr as nn,Ll as nt,Bp as o,Vl as ot,dp as p,Tl as pt,fu as q,ha as qt,Tm as r,Vr as rn,Fl as rt,Dm as s,Xl as st,ng as t,Fr as tn,eu as tt,yp as u,Ml as ut,tp as v,bc as vt,hf as w,ic as wt,qf as x,Sc as xt,Kf as y,xc as yt,md as z,ss as zt};
|