@seams/wallet 0.30.0 → 0.33.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.
Files changed (100) hide show
  1. package/README.md +7 -7
  2. package/THIRD_PARTY_NOTICES.md +1 -127
  3. package/dist/.build-inputs.sha256 +1 -1
  4. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuFooter.js +38 -10
  5. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +23 -67
  6. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/RecoveryOptions.js +60 -0
  7. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.js +6 -0
  8. package/dist/esm/SeamsWeb/walletIframe/shared/authMenuPresentation.js +28 -0
  9. package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +21 -10
  10. package/dist/esm/SeamsWeb/walletIframe/shared/walletAlternatives.js +4 -14
  11. package/dist/esm/core/ui/walletIcon.js +11 -3
  12. package/dist/esm/externalNear/controller.js +3 -2
  13. package/dist/esm/externalNear/meteor.js +1 -1
  14. package/dist/esm/externalNear/meteorRequest.js +8 -2
  15. package/dist/esm/react/components/HostedSeamsAuthMenu/shell.js +17 -1
  16. package/dist/esm/sdk/{host-Csu5L7VF.js → host-BsVFOugh.js} +1 -1
  17. package/dist/esm/sdk/ownerNearOperation-BsIdSH0C.js +1 -0
  18. package/dist/esm/sdk/registration-Coh0_Nva.js +1 -0
  19. package/dist/esm/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  20. package/dist/esm/sdk/runtime-auth-CJCU2yJi.js +1 -0
  21. package/dist/esm/sdk/{runtime-device-link-DQe0aqRi.js → runtime-device-link-C0oXLSnz.js} +1 -1
  22. package/dist/esm/sdk/{runtime-ecdsa-tempo-DKkeMMpm.js → runtime-ecdsa-tempo-BC8u9NuI.js} +1 -1
  23. package/dist/esm/sdk/{runtime-email-otp-CzTe7r9I.js → runtime-email-otp-Cl4iu0z7.js} +1 -1
  24. package/dist/esm/sdk/{runtime-export-BiyLbdCe.js → runtime-export-BdhfErGJ.js} +1 -1
  25. package/dist/esm/sdk/{runtime-near-Kk0n1FSf.js → runtime-near-CT2ALBct.js} +1 -1
  26. package/dist/esm/sdk/{runtime-preferences-B-A3hddU.js → runtime-preferences-fN2G9tct.js} +1 -1
  27. package/dist/esm/sdk/{runtime-recovery-C9p1TU1w.js → runtime-recovery-n-TGLkwz.js} +1 -1
  28. package/dist/esm/sdk/{runtimeContext-ChuvOC0h.js → runtimeContext-DI28d8Qu.js} +1 -1
  29. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  30. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  31. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  32. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  33. package/dist/esm/sdk/wallet-service.css +2 -0
  34. package/dist/esm/sdk/wallet-ui.css +1 -1
  35. package/dist/esm/wasm/near_signer/pkg/wasm_signer_worker_bg.wasm +0 -0
  36. package/dist/esm/wasm/router_ab_ecdsa_client/pkg/router_ab_ecdsa_client_bg.wasm +0 -0
  37. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.d.ts +212 -233
  38. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client.js +675 -694
  39. package/dist/esm/wasm/router_ab_ed25519_yao_client/pkg/router_ab_ed25519_yao_client_bg.wasm +0 -0
  40. package/dist/public/headers.manifest.json +1 -1
  41. package/dist/public/sdk/{host-Csu5L7VF.js → host-BsVFOugh.js} +1 -1
  42. package/dist/public/sdk/ownerNearOperation-BsIdSH0C.js +1 -0
  43. package/dist/public/sdk/registration-Coh0_Nva.js +1 -0
  44. package/dist/public/sdk/router_ab_ed25519_yao_client_bg.wasm +0 -0
  45. package/dist/public/sdk/runtime-auth-CJCU2yJi.js +1 -0
  46. package/dist/public/sdk/{runtime-device-link-DQe0aqRi.js → runtime-device-link-C0oXLSnz.js} +1 -1
  47. package/dist/public/sdk/{runtime-ecdsa-tempo-DKkeMMpm.js → runtime-ecdsa-tempo-BC8u9NuI.js} +1 -1
  48. package/dist/public/sdk/{runtime-email-otp-CzTe7r9I.js → runtime-email-otp-Cl4iu0z7.js} +1 -1
  49. package/dist/public/sdk/{runtime-export-BiyLbdCe.js → runtime-export-BdhfErGJ.js} +1 -1
  50. package/dist/public/sdk/{runtime-near-Kk0n1FSf.js → runtime-near-CT2ALBct.js} +1 -1
  51. package/dist/public/sdk/{runtime-preferences-B-A3hddU.js → runtime-preferences-fN2G9tct.js} +1 -1
  52. package/dist/public/sdk/{runtime-recovery-C9p1TU1w.js → runtime-recovery-n-TGLkwz.js} +1 -1
  53. package/dist/public/sdk/{runtimeContext-ChuvOC0h.js → runtimeContext-DI28d8Qu.js} +1 -1
  54. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  55. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  56. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  57. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  58. package/dist/public/sdk/wallet-service.css +2 -0
  59. package/dist/public/sdk/wallet-ui.css +1 -1
  60. package/dist/public/sdk/workers/device-linking-key.worker.js +454 -947
  61. package/dist/public/sdk/workers/email-otp.worker.js +588 -820
  62. package/dist/public/sdk/workers/evm_crypto_bg.wasm +0 -0
  63. package/dist/public/sdk/workers/passkey-mpc-export.worker.js +572 -804
  64. package/dist/public/sdk/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  65. package/dist/public/sdk/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  66. package/dist/public/sdk/workers/tempo_signer_bg.wasm +0 -0
  67. package/dist/public/sdk/workers/wallet-custody-ceremony.worker.js +524 -971
  68. package/dist/public/sdk/workers/wallet_custody_ceremony_bg.wasm +0 -0
  69. package/dist/public/sdk/workers/wasm_signer_worker_bg.wasm +0 -0
  70. package/dist/public/wallet-assets.manifest.json +29 -29
  71. package/dist/public/wallet-service/index.html +4 -4
  72. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuFooter.d.ts +4 -0
  73. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +3 -1
  74. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/RecoveryOptions.d.ts +11 -0
  75. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.d.ts +3 -0
  76. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/authMenuPresentation.d.ts +13 -0
  77. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +7 -1
  78. package/dist/types/wallet/src/core/ui/walletIcon.d.ts +1 -0
  79. package/dist/types/wallet/src/externalNear/meteorRequest.d.ts +3 -0
  80. package/dist/types/wallet/src/index.d.ts +1 -1
  81. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/public.d.ts +1 -1
  82. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/types.d.ts +6 -2
  83. package/dist/types/wallet/src/react/index.d.ts +1 -1
  84. package/dist/workers/device-linking-key.worker.js +454 -947
  85. package/dist/workers/email-otp.worker.js +588 -820
  86. package/dist/workers/evm_crypto_bg.wasm +0 -0
  87. package/dist/workers/passkey-mpc-export.worker.js +572 -804
  88. package/dist/workers/router_ab_ecdsa_client_bg.wasm +0 -0
  89. package/dist/workers/router_ab_ed25519_yao_client_bg.wasm +0 -0
  90. package/dist/workers/tempo_signer_bg.wasm +0 -0
  91. package/dist/workers/wallet-custody-ceremony.worker.js +524 -971
  92. package/dist/workers/wallet_custody_ceremony_bg.wasm +0 -0
  93. package/dist/workers/wasm_signer_worker_bg.wasm +0 -0
  94. package/package.json +17 -17
  95. package/dist/esm/sdk/ownerNearOperation-DCxxHcwX.js +0 -1
  96. package/dist/esm/sdk/registration-C7w_51wE.js +0 -1
  97. package/dist/esm/sdk/runtime-auth-BMT_gIKI.js +0 -1
  98. package/dist/public/sdk/ownerNearOperation-DCxxHcwX.js +0 -1
  99. package/dist/public/sdk/registration-C7w_51wE.js +0 -1
  100. package/dist/public/sdk/runtime-auth-BMT_gIKI.js +0 -1
@@ -0,0 +1 @@
1
+ import{n as e}from"./chunk-dVx5-UGu.js";import{C as t,E as n,L as r,M as i,N as a,O as o,P as s,S as c,T as l,c as u,g as d,i as f,s as p,z as m}from"./domainIds-t1lp25yU.js";import{S as h,T as g,a as _,h as v,i as y,l as b,n as x,r as S,t as C,w,x as T}from"./digests-BIaE0DMd.js";import{c as E,r as D,s as O,t as k}from"./participants-BXdREC5k.js";import{i as A,r as j}from"./base64-BmKR3UqU.js";import{r as M}from"./secureRandomId-8LSc91aN.js";import{s as N}from"./walletDbName-B6-CV_Rq.js";import{J as P,Q as F,X as I,Y as ee,Z as te,a as L,i as ne,n as re}from"./activeWalletSession-HAOgRKzn.js";import{n as ie,t as R}from"./chains-B72I4PDH.js";import{c as z,d as ae,f as oe,l as se,s as ce,u as le}from"./signingSessionSeal-BFOBKj-J.js";import{d as ue,g as de,h as fe,m as pe}from"./capabilityKinds-Cafn86Y1.js";import{i as me,n as he,r as ge}from"./canonicalPrimitives-DKeS3M40.js";import{n as _e,s as ve,t as ye}from"./errors-BJBDbwHk.js";import{c as be,f as xe,g as Se,h as Ce,l as we,n as Te}from"./signerDomain-D-EUTlLK.js";import{c as Ee,r as De}from"./types-D2Zk1W7I.js";import{c as Oe,d as ke,r as Ae,t as je}from"./accountIds-DGWFzEnw.js";import{E as Me,S as Ne,d as Pe,g as Fe,p as Ie,u as Le,v as Re,x as ze,y as Be}from"./registrationIntent-Cb3tggIM.js";import{a as Ve,i as He,n as Ue,r as We}from"./presignatures-B9KnQyfE.js";import{a as Ge,c as Ke,i as qe,o as Je,r as Ye,s as Xe}from"./ecdsaChainTarget-BoRVQtjQ.js";import{t as Ze}from"./keyMaterialEnvelope-Czkks9Ki.js";import{B as Qe,E as $e,N as et,Q as tt,R as nt,T as rt,X as it,Z as at,d as ot,et as st,j as ct,k as lt,p as ut,q as dt,w as ft,z as pt}from"./walletAuthority-CU9nO0Ze.js";import{A as mt,D as ht,Et as gt,Ft as _t,G as vt,J as yt,Nt as bt,P as xt,Pt as St,S as Ct,Tt as wt,W as Tt,X as Et,Z as Dt,_ as Ot,at as kt,ct as At,dt as jt,k as Mt,kt as Nt,nt as Pt,ot as Ft,q as It,ut as Lt,x as Rt}from"./digestEncoding-Rx8Vjy4J.js";import{r as zt}from"./walletAuthMethodRecord--fvGr8r1.js";import{a as Bt,i as Vt,n as Ht,o as Ut,t as Wt}from"./signerSlot-BlijMq8C.js";import{A as Gt,B as Kt,I as qt,N as Jt,P as Yt,i as Xt,j as Zt}from"./ecdsaCapabilityManifest-BbPXL-qh.js";import{g as Qt,i as B,p as $t,s as en}from"./sdkSentEvents-BFwv3mBw.js";import{C as tn,E as nn,S as rn,T as an,b as on,c as sn,f as cn,o as ln,t as V,w as un,x as dn}from"./indexedDB-BqsYXybq.js";import{c as fn,d as pn,i as mn,l as hn,n as gn,r as _n,s as vn}from"./registrationSignerPlan-CeMidFme.js";import{n as yn}from"./authenticatorOptions-B4q62CLs.js";import{X as bn,j as xn}from"./walletOwnershipGeneration-B3uE9GRG.js";import{T as Sn,w as Cn}from"./emailOtpEcdsaDerivationIdentity-DJmMyqL-.js";import{o as wn}from"./walletSessionAuthorizationStore-CGt-s5fX.js";import{t as Tn}from"./walletSessionAuthorizationStatus-CQ3qA9tI.js";import{r as En,s as Dn,u as On}from"./unlockedEd25519ExportRootCapability-BbGMlikr.js";import{C as kn,D as An,E as jn,T as Mn,a as Nn,c as Pn,f as Fn,g as In,h as Ln,i as Rn,m as zn,n as Bn,o as Vn,t as Hn,v as Un,x as Wn,y as Gn}from"./authorization-D_NueqAv.js";import{i as Kn}from"./profileAccountProjection-dvLchPBo.js";import{c as qn,r as Jn}from"./walletCustodyEcdsaContinuity-BUdDyRl_.js";import{o as Yn,u as Xn}from"./helpers-B7c1zc7h.js";import{P as Zn,d as Qn,f as $n,p as er,u as tr}from"./accountLifecycle-B5a9SCM7.js";import{A as nr,a as rr,d as ir,f as ar,j as or,o as sr,u as cr}from"./nearEd25519YaoSigningPreparation-Cz2Gb95g.js";import{n as lr}from"./lanes-0WT2w1Xz.js";import{i as ur,n as dr,o as fr,t as pr}from"./pendingWalletRecoveryCodeBackup-8iMhQU-E.js";import{c as mr,o as hr,s as gr}from"./wallet-recovery-Bfm-oUoP.js";import{n as _r}from"./prfCache-DEHaUPSW.js";import{u as vr}from"./trace-BA8jya7O.js";import{n as yr,o as br,t as xr}from"./walletSessionAuthorizationProjection-BzUH6gHV.js";import{t as Sr}from"./webauthnPromptCoordinator-npsSRD51.js";import{t as Cr}from"./intentDigest-gM3r4SVX.js";import{n as wr}from"./challengeDelivery-Dj9HrjW9.js";let H,U=0,Tr=null;function Er(){return(Tr===null||Tr.byteLength===0)&&(Tr=new Uint8Array(H.memory.buffer)),Tr}const Dr=typeof TextEncoder<`u`?new TextEncoder(`utf-8`):{encode:()=>{throw Error(`TextEncoder not available`)}},Or=typeof Dr.encodeInto==`function`?function(e,t){return Dr.encodeInto(e,t)}:function(e,t){let n=Dr.encode(e);return t.set(n),{read:e.length,written:n.length}};function W(e,t,n){if(n===void 0){let n=Dr.encode(e),r=t(n.length,1)>>>0;return Er().subarray(r,r+n.length).set(n),U=n.length,r}let r=e.length,i=t(r,1)>>>0,a=Er(),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=Er().subarray(i+o,i+r),a=Or(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return U=o,i}let kr=null;function Ar(){return(kr===null||kr.buffer.detached===!0||kr.buffer.detached===void 0&&kr.buffer!==H.memory.buffer)&&(kr=new DataView(H.memory.buffer)),kr}function jr(e){let t=H.__externref_table_alloc();return H.__wbindgen_export_4.set(t,e),t}function Mr(e,t){try{return e.apply(this,t)}catch(e){let t=jr(e);H.__wbindgen_exn_store(t)}}const Nr=typeof TextDecoder<`u`?new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error(`TextDecoder not available`)}};typeof TextDecoder<`u`&&Nr.decode();function Pr(e,t){return e>>>=0,Nr.decode(Er().subarray(e,e+t))}function Fr(e){return e==null}function Ir(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+=Ir(e[0]));for(let r=1;r<t;r++)n+=`, `+Ir(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 G(e,t){let n=t(e.length*1,1)>>>0;return Er().set(e,n/1),U=e.length,n}function Lr(e){let t=H.__wbindgen_export_4.get(e);return H.__externref_table_dealloc(e),t}function Rr(e,t,n,r,i,a,o,s,c,l,u,d,f,p){let m=G(e,H.__wbindgen_malloc),h=U,g=W(t,H.__wbindgen_malloc,H.__wbindgen_realloc),_=U,v=G(n,H.__wbindgen_malloc),y=U,b=G(r,H.__wbindgen_malloc),x=U,S=G(i,H.__wbindgen_malloc),C=U,w=G(a,H.__wbindgen_malloc),T=U,E=G(o,H.__wbindgen_malloc),D=U,O=G(s,H.__wbindgen_malloc),k=U,A=G(d,H.__wbindgen_malloc),j=U,M=G(f,H.__wbindgen_malloc),N=U,P=G(p,H.__wbindgen_malloc),F=U,I=H.openWalletCustodyEd25519MaterialV1(m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,c,l,u,A,j,M,N,P,F);if(I[2])throw Lr(I[1]);return Vr.__wrap(I[0])}function zr(e,t){return e>>>=0,Er().subarray(e/1,e/1+t)}const Br=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>H.__wbg_wasmactivatedclientv1_free(e>>>0,1));var Vr=class e{static __wrap(t){t>>>=0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Br.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Br.unregister(this),e}free(){let e=this.__destroy_into_raw();H.__wbg_wasmactivatedclientv1_free(e,0)}state_epoch(){let e=H.wasmactivatedclientv1_state_epoch(this.__wbg_ptr);return BigInt.asUintN(64,e)}seal_local_material(e,t,n){let r=G(e,H.__wbindgen_malloc),i=U,a=G(t,H.__wbindgen_malloc),o=U,s=G(n,H.__wbindgen_malloc),c=U,l=H.wasmactivatedclientv1_seal_local_material(this.__wbg_ptr,r,i,a,o,s,c);if(l[3])throw Lr(l[2]);var u=zr(l[0],l[1]).slice();return H.__wbindgen_free(l[0],l[1]*1,1),u}create_signing_share(e,t,n,r,i){let a=G(n,H.__wbindgen_malloc),o=U,s=W(r,H.__wbindgen_malloc,H.__wbindgen_realloc),c=U,l=G(i,H.__wbindgen_malloc),u=U,d=H.wasmactivatedclientv1_create_signing_share(this.__wbg_ptr,e,t,a,o,s,c,l,u);if(d[2])throw Lr(d[1]);return Ur.__wrap(d[0])}static import_local_material(t,n,r,i,a,o,s,c,l){let u=G(t,H.__wbindgen_malloc),d=U,f=G(n,H.__wbindgen_malloc),p=U,m=G(r,H.__wbindgen_malloc),h=U,g=G(i,H.__wbindgen_malloc),_=U,v=G(a,H.__wbindgen_malloc),y=U,b=G(l,H.__wbindgen_malloc),x=U,S=H.wasmactivatedclientv1_import_local_material(u,d,f,p,m,h,g,_,v,y,o,s,c,b,x);if(S[2])throw Lr(S[1]);return e.__wrap(S[0])}registered_public_key(){let e=H.wasmactivatedclientv1_registered_public_key(this.__wbg_ptr);var t=zr(e[0],e[1]).slice();return H.__wbindgen_free(e[0],e[1]*1,1),t}static import_linked_material(t,n,r,i){let a=G(t,H.__wbindgen_malloc),o=U,s=W(i,H.__wbindgen_malloc,H.__wbindgen_realloc),c=U,l=H.wasmactivatedclientv1_import_linked_material(a,o,n,r,s,c);if(l[2])throw Lr(l[1]);return e.__wrap(l[0])}};const Hr=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>H.__wbg_wasmclientsigningsharev1_free(e>>>0,1));var Ur=class e{static __wrap(t){t>>>=0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Hr.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Hr.unregister(this),e}free(){let e=this.__destroy_into_raw();H.__wbg_wasmclientsigningsharev1_free(e,0)}client_verifying_share(){let e=H.wasmclientsigningsharev1_client_verifying_share(this.__wbg_ptr);var t=zr(e[0],e[1]).slice();return H.__wbindgen_free(e[0],e[1]*1,1),t}client_commitments_json(){let e,t;try{let n=H.wasmclientsigningsharev1_client_commitments_json(this.__wbg_ptr);return e=n[0],t=n[1],Pr(n[0],n[1])}finally{H.__wbindgen_free(e,t,1)}}client_signature_share_b64u(){let e,t;try{let n=H.wasmclientsigningsharev1_client_signature_share_b64u(this.__wbg_ptr);return e=n[0],t=n[1],Pr(n[0],n[1])}finally{H.__wbindgen_free(e,t,1)}}};const Wr=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>H.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e>>>0,1));var Gr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Wr.unregister(this),e}free(){let e=this.__destroy_into_raw();H.__wbg_wasmed25519yaoclientrootexportsessionv1_free(e,0)}execute_request_json(){let e,t;try{let n=H.wasmed25519yaoclientrootexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],Pr(n[0],n[1])}finally{H.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=W(e,H.__wbindgen_malloc,H.__wbindgen_realloc),m=U,h=W(t,H.__wbindgen_malloc,H.__wbindgen_realloc),g=U,_=G(i,H.__wbindgen_malloc),v=U,y=W(a,H.__wbindgen_malloc,H.__wbindgen_realloc),b=U,x=G(o,H.__wbindgen_malloc),S=U,C=G(s,H.__wbindgen_malloc),w=U,T=G(c,H.__wbindgen_malloc),E=U,D=G(l,H.__wbindgen_malloc),O=U,k=G(u,H.__wbindgen_malloc),A=U,j=G(d,H.__wbindgen_malloc),M=U,N=G(f,H.__wbindgen_malloc),P=U,F=H.wasmed25519yaoclientrootexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,P);if(F[2])throw Lr(F[1]);return this.__wbg_ptr=F[0]>>>0,Wr.register(this,this.__wbg_ptr,this),this}complete(e){let t=W(e,H.__wbindgen_malloc,H.__wbindgen_realloc),n=U,r=H.wasmed25519yaoclientrootexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw Lr(r[1]);return qr.__wrap(r[0])}};typeof FinalizationRegistry>`u`||new FinalizationRegistry(e=>H.__wbg_wasmed25519yaolaneclientv1_free(e>>>0,1)),typeof FinalizationRegistry>`u`||new FinalizationRegistry(e=>H.__wbg_wasmed25519yaolanesourcev1_free(e>>>0,1)),typeof FinalizationRegistry>`u`||new FinalizationRegistry(e=>H.__wbg_wasmed25519yaosourcepreservingregistrationsessionv1_free(e>>>0,1));const Kr=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>H.__wbg_wasmexporteded25519seedv1_free(e>>>0,1));var qr=class e{static __wrap(t){t>>>=0;let n=Object.create(e.prototype);return n.__wbg_ptr=t,Kr.register(n,n.__wbg_ptr,n),n}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Kr.unregister(this),e}free(){let e=this.__destroy_into_raw();H.__wbg_wasmexporteded25519seedv1_free(e,0)}take_export_artifact_json(){let e,t;try{let i=H.wasmexporteded25519seedv1_take_export_artifact_json(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,Lr(i[2]);return e=n,t=r,Pr(n,r)}finally{H.__wbindgen_free(e,t,1)}}};typeof FinalizationRegistry>`u`||new FinalizationRegistry(e=>H.__wbg_wasmordinaryed25519activationclientmaterialv1_free(e>>>0,1));const Jr=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>H.__wbg_wasmwalletcustodyseedexportsessionv1_free(e>>>0,1));var Yr=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Jr.unregister(this),e}free(){let e=this.__destroy_into_raw();H.__wbg_wasmwalletcustodyseedexportsessionv1_free(e,0)}execute_request_json(){let e,t;try{let n=H.wasmwalletcustodyseedexportsessionv1_execute_request_json(this.__wbg_ptr);return e=n[0],t=n[1],Pr(n[0],n[1])}finally{H.__wbindgen_free(e,t,1)}}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=W(e,H.__wbindgen_malloc,H.__wbindgen_realloc),m=U,h=W(t,H.__wbindgen_malloc,H.__wbindgen_realloc),g=U,_=G(i,H.__wbindgen_malloc),v=U,y=W(a,H.__wbindgen_malloc,H.__wbindgen_realloc),b=U,x=G(o,H.__wbindgen_malloc),S=U,C=G(s,H.__wbindgen_malloc),w=U,T=G(c,H.__wbindgen_malloc),E=U,D=G(l,H.__wbindgen_malloc),O=U,k=G(u,H.__wbindgen_malloc),A=U,j=G(d,H.__wbindgen_malloc),M=U,N=G(f,H.__wbindgen_malloc),P=U,F=H.wasmwalletcustodyseedexportsessionv1_new(p,m,h,g,n,r,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,M,N,P);if(F[2])throw Lr(F[1]);return this.__wbg_ptr=F[0]>>>0,Jr.register(this,this.__wbg_ptr,this),this}complete(e){let t=W(e,H.__wbindgen_malloc,H.__wbindgen_realloc),n=U,r=H.wasmwalletcustodyseedexportsessionv1_complete(this.__wbg_ptr,t,n);if(r[2])throw Lr(r[1]);return qr.__wrap(r[0])}};async function Xr(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.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 n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}function Zr(){let e={};return e.wbg={},e.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,t){let n=W(String(t),H.__wbindgen_malloc,H.__wbindgen_realloc),r=U;Ar().setInt32(e+4,r,!0),Ar().setInt32(e+0,n,!0)},e.wbg.__wbg_buffer_609cc3eee51ed158=function(e){return e.buffer},e.wbg.__wbg_call_672a4d21634d4a24=function(){return Mr(function(e,t){return e.call(t)},arguments)},e.wbg.__wbg_call_7cccdd69e0791ae2=function(){return Mr(function(e,t,n){return e.call(t,n)},arguments)},e.wbg.__wbg_crypto_86f2631e91b51511=function(e){return e.crypto},e.wbg.__wbg_done_769e5ede4b31c67b=function(e){return e.done},e.wbg.__wbg_entries_3265d4158b33e5dc=function(e){return Object.entries(e)},e.wbg.__wbg_getRandomValues_b3f15fcbfabb0f8b=function(){return Mr(function(e,t){e.getRandomValues(t)},arguments)},e.wbg.__wbg_get_67b2ba62fc30de12=function(){return Mr(function(e,t){return Reflect.get(e,t)},arguments)},e.wbg.__wbg_get_b9b93047fe3cf45b=function(e,t){return e[t>>>0]},e.wbg.__wbg_getwithrefkey_1dc361bd10053bfe=function(e,t){return e[t]},e.wbg.__wbg_instanceof_ArrayBuffer_e14585432e3737fc=function(e){let t;try{t=e instanceof ArrayBuffer}catch{t=!1}return t},e.wbg.__wbg_instanceof_Map_f3469ce2244d2430=function(e){let t;try{t=e instanceof Map}catch{t=!1}return t},e.wbg.__wbg_instanceof_Uint8Array_17156bcf118086a9=function(e){let t;try{t=e instanceof Uint8Array}catch{t=!1}return t},e.wbg.__wbg_isArray_a1eab7e0d067391b=function(e){return Array.isArray(e)},e.wbg.__wbg_isSafeInteger_343e2beeeece1bb0=function(e){return Number.isSafeInteger(e)},e.wbg.__wbg_iterator_9a24c88df860dc65=function(){return Symbol.iterator},e.wbg.__wbg_length_a446193dc22c12f8=function(e){return e.length},e.wbg.__wbg_length_e2d2a49132c1b256=function(e){return e.length},e.wbg.__wbg_msCrypto_d562bbe83e0d4b91=function(e){return e.msCrypto},e.wbg.__wbg_new_405e22f390576ce2=function(){return{}},e.wbg.__wbg_new_a12002a7f91c75be=function(e){return new Uint8Array(e)},e.wbg.__wbg_newnoargs_105ed471475aaf50=function(e,t){return Function(Pr(e,t))},e.wbg.__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a=function(e,t,n){return new Uint8Array(e,t>>>0,n>>>0)},e.wbg.__wbg_newwithlength_a381634e90c276d4=function(e){return new Uint8Array(e>>>0)},e.wbg.__wbg_next_25feadfc0913fea9=function(e){return e.next},e.wbg.__wbg_next_6574e1a8a62d1055=function(){return Mr(function(e){return e.next()},arguments)},e.wbg.__wbg_node_e1f24f89a7336c2e=function(e){return e.node},e.wbg.__wbg_process_3975fd6c72f520aa=function(e){return e.process},e.wbg.__wbg_randomFillSync_f8c153b79f285817=function(){return Mr(function(e,t){e.randomFillSync(t)},arguments)},e.wbg.__wbg_require_b74f47fc2d022fd6=function(){return Mr(function(){return module.require},arguments)},e.wbg.__wbg_set_3f1d0b984ed272ed=function(e,t,n){e[t]=n},e.wbg.__wbg_set_65595bdd868b3009=function(e,t,n){e.set(t,n>>>0)},e.wbg.__wbg_set_bb8cecf6a62b9f46=function(){return Mr(function(e,t,n){return Reflect.set(e,t,n)},arguments)},e.wbg.__wbg_static_accessor_GLOBAL_88a902d13a557d07=function(){let e=typeof global>`u`?null:global;return Fr(e)?0:jr(e)},e.wbg.__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0=function(){let e=typeof globalThis>`u`?null:globalThis;return Fr(e)?0:jr(e)},e.wbg.__wbg_static_accessor_SELF_37c5d418e4bf5819=function(){let e=typeof self>`u`?null:self;return Fr(e)?0:jr(e)},e.wbg.__wbg_static_accessor_WINDOW_5de37043a91a9c40=function(){let e=typeof window>`u`?null:window;return Fr(e)?0:jr(e)},e.wbg.__wbg_subarray_aa9065fa9dc5df96=function(e,t,n){return e.subarray(t>>>0,n>>>0)},e.wbg.__wbg_value_cd1ffa7b1ab794f1=function(e){return e.value},e.wbg.__wbg_versions_4e31226f5e8dc909=function(e){return e.versions},e.wbg.__wbindgen_as_number=function(e){return+e},e.wbg.__wbindgen_bigint_from_i64=function(e){return e},e.wbg.__wbindgen_bigint_from_u64=function(e){return BigInt.asUintN(64,e)},e.wbg.__wbindgen_bigint_get_as_i64=function(e,t){let n=t,r=typeof n==`bigint`?n:void 0;Ar().setBigInt64(e+8,Fr(r)?BigInt(0):r,!0),Ar().setInt32(e+0,!Fr(r),!0)},e.wbg.__wbindgen_boolean_get=function(e){let t=e;return typeof t==`boolean`?t?1:0:2},e.wbg.__wbindgen_debug_string=function(e,t){let n=W(Ir(t),H.__wbindgen_malloc,H.__wbindgen_realloc),r=U;Ar().setInt32(e+4,r,!0),Ar().setInt32(e+0,n,!0)},e.wbg.__wbindgen_error_new=function(e,t){return Error(Pr(e,t))},e.wbg.__wbindgen_in=function(e,t){return e in t},e.wbg.__wbindgen_init_externref_table=function(){let e=H.__wbindgen_export_4,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)},e.wbg.__wbindgen_is_bigint=function(e){return typeof e==`bigint`},e.wbg.__wbindgen_is_function=function(e){return typeof e==`function`},e.wbg.__wbindgen_is_object=function(e){let t=e;return typeof t==`object`&&!!t},e.wbg.__wbindgen_is_string=function(e){return typeof e==`string`},e.wbg.__wbindgen_is_undefined=function(e){return e===void 0},e.wbg.__wbindgen_jsval_eq=function(e,t){return e===t},e.wbg.__wbindgen_jsval_loose_eq=function(e,t){return e==t},e.wbg.__wbindgen_memory=function(){return H.memory},e.wbg.__wbindgen_number_get=function(e,t){let n=t,r=typeof n==`number`?n:void 0;Ar().setFloat64(e+8,Fr(r)?0:r,!0),Ar().setInt32(e+0,!Fr(r),!0)},e.wbg.__wbindgen_number_new=function(e){return e},e.wbg.__wbindgen_string_get=function(e,t){let n=t,r=typeof n==`string`?n:void 0;var i=Fr(r)?0:W(r,H.__wbindgen_malloc,H.__wbindgen_realloc),a=U;Ar().setInt32(e+4,a,!0),Ar().setInt32(e+0,i,!0)},e.wbg.__wbindgen_string_new=function(e,t){return Pr(e,t)},e.wbg.__wbindgen_throw=function(e,t){throw Error(Pr(e,t))},e}function Qr(e,t){return H=e.exports,$r.__wbindgen_wasm_module=t,kr=null,Tr=null,H.__wbindgen_start(),H}async function $r(e){if(H!==void 0)return H;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=Zr();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await Xr(await e,t);return Qr(n,r)}const ei=`router_ab_ed25519_yao_active_client_v1`;function ti(e){switch(e.authorization.kind){case`passkey`:return{protocol:e.protocol,authorization:{kind:`passkey`,webauthnAuthentication:Xn(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 ni=Symbol(`router-ab-ed25519-yao-active-client-construction`);function ri(e,t){if(!(e instanceof Uint8Array)||e.length!==32)throw Error(`${t} must contain 32 bytes`);return e}function ii(e){return e.authorization.kind===`passkey`}function ai(e){switch(e.kind){case`wallet_custody_seed_v1`:return Yr;case`ed25519_yao_client_root_v1`:return Gr;default:return fi(e.kind)}}function oi(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(ai(e.custodyEnvelope))(...t)}function si(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 ci(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=nt(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:si(Reflect.get(e,`factorRelease`))}}function li(){return{recipientKeyMaterial:mi(),deriverASealSeed:mi(),deriverBSealSeed:mi()}}function ui(e){e.recipientKeyMaterial.fill(0),e.deriverASealSeed.fill(0),e.deriverBSealSeed.fill(0)}function di(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 fi(e){throw Error(`Unhandled Ed25519 Yao Client lifecycle: ${String(e)}`)}function pi(e){switch(e.kind){case`active`:return e.activated;case`disposed`:throw Error(`Ed25519 Yao Client state is disposed`);default:return fi(e)}}function mi(){let e=new Uint8Array(32);do globalThis.crypto.getRandomValues(e);while(e.every(hi));return e}function hi(e){return e===0}function gi(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 _i(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&&_t(t.binding.ceremony.material_activation,e.scope.material_activation)&&t.binding.state_epoch===e.state_epoch&&di(t.binding.registered_public_key,e.registered_public_key)&&di(t.binding.runtime_policy_binding,e.runtime_policy_binding)&&di(t.binding.authorization_digest,e.authorization.authorization_digest)}function vi(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 yi(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:bi(e.traceContext)}}function bi(e){if(!e)return an();if(e.kind!==`router_ab_trace_context_v1`)throw Error(`Router trace context kind is invalid`);let t=nn(e.value);if(!t.ok)throw Error(t.message);return t.value}async function xi(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||Si(e.url);return{ok:!0,value:n,...r?{serverTiming:r}:{}}}let r=_(n)?.code;return{ok:!1,message:JSON.stringify(n),...typeof r==`string`?{code:r}:{}}}function Si(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=Ci(Reflect.get(n,`serverTiming`));if(r)return r}return null}function Ci(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 wi=class{config;constructor(e){this.config=yi(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:{...Mi(this.config.routing),...n?{authorization:n}:{},...r?{[lt]:r}:{},"content-type":`application/json`,[un]: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 xi(t)}},Ti=class{activeMetadata;lifecycle;constructor(e){if(e[ni]!==!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=pi(this.lifecycle);try{return{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:e.nonce.slice(),ciphertext:t.seal_local_material(ri(e.ownedPasskeyPrfFirst,`passkey PRF.first`),e.binding,e.nonce)}}finally{e.ownedPasskeyPrfFirst.fill(0)}}async createSigningShare(e){let t=pi(this.lifecycle),n=ri(e.admittedDigest,`admitted digest`),r=ri(e.signingWorkerVerifyingShare,`SigningWorker verifying share`);if(!di(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:gi(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 fi(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 fi(this.lifecycle)}}};function Ei(e){let t=null;try{return t=Vr.import_local_material(ri(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 Ti({[ni]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedPasskeyPrfFirst.fill(0)}}function Di(e){let t=null;try{if(t=Vr.import_linked_material(ri(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||!di(t.registered_public_key(),e.metadata.registeredPublicKey)||!di(e.publicReceipt.signing_worker_verifying_share,e.metadata.signingWorkerVerifyingShare))throw Error(`linked-device Ed25519 material metadata does not match its receipt`);return new Ti({[ni]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedClientScalarShare.fill(0)}}function Oi(e){let t=null;try{return t=Rr(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 Ti({[ni]:!0,metadata:e.metadata,activated:t})}catch(e){throw t?.free(),e}finally{e.ownedFactorSecret.fill(0)}}let ki=null;function Ai(e){throw ki=null,e}var ji=class e{constructor(){}static async initializeBundled(){return ki??=$r().catch(Ai),await ki,new e}importLocalMaterial(e){return Ei(e)}importLinkedMaterial(e){return Di(e)}openCustodyCache(e){return Oi(e)}async exportSeed(e){let t=await e.transport.send({kind:`export_admit`,path:rt,body:ti({protocol:e.request,authorization:e.authorization})});if(!t.ok)return t;let n;try{n=ci(t.value)}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}if(!_i(e.request,n.protocol))return{ok:!1,message:`Router export admission does not match the requested exact capability`};let r;if(ii(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=li(),a;try{a=oi({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=pt(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:$e,body:{protocol:t.value}});if(!n.ok)return n;let r=Qe(n.value);if(!r.ok)return{ok:!1,message:r.message};let i=a.complete(JSON.stringify(r.value));try{return{ok:!0,artifact:vi(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 Mi(e){switch(e.kind){case`discovery`:return{};case`direct`:case`regional`:return O(e);default:return fi(e)}}var Ni=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 Pi(e){return Ni.build(e)}const Fi=`router_ab_ed25519_yao_active_client_v1`,Ii=`chacha20poly1305-hkdf-sha256-prf-first-v1`,Li=(1n<<64n)-1n;function K(e,t){let n=String(e??``).trim();if(!n)throw Error(`${t} is required for local Ed25519 material`);return n}function Ri(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<1)throw Error(`${t} must be a positive safe integer`);return n}function zi(e,n){let r=t(e);if(!r.ok)throw Error(`${n}: ${r.error.message}`);return r.value}function Bi(e,t){let n=K(e,t);if(j(n).length!==32)throw Error(`${t} must encode 32 bytes`);return n}function Vi(e){if(!Array.isArray(e)||e.length!==2)throw Error(`participantIds must contain exactly two entries`);let t=[Ri(e[0],`participantIds[0]`),Ri(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 Hi(e,t){let n=K(e,t);if(!/^(0|[1-9][0-9]*)$/.test(n)||BigInt(n)>Li)throw Error(`${t} must be a canonical u64`);return n}function Ui(e,t,n){let r=e.signingLane.identity.signer;return{walletId:K(r.account.wallet.walletId,`walletId`),nearAccountId:K(r.account.nearAccountId,`nearAccountId`),nearEd25519SigningKeyId:K(r.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),thresholdSessionId:zi(e.signingLane.identity.thresholdSessionId,`thresholdSessionId`),signerSlot:Ri(r.signerSlot,`signerSlot`),rpId:K(t,`rpId`),credentialIdB64u:K(n,`credentialIdB64u`),signingRootId:K(e.signingRootId,`signingRootId`),signingRootVersion:K(e.signingRootVersion,`signingRootVersion`),signingWorkerId:K(e.routerAbNormalSigning.signingWorkerId,`signingWorkerId`)}}function Wi(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:Fi,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:K(t.scope.lifecycle_id,`lifecycleId`),thresholdSessionId:zi(t.scope.threshold_session_id,`thresholdSessionId`),materialActivation:Mn(t),signingRootId:e.identity.signingRootId,signingRootVersion:e.identity.signingRootVersion,signerSetId:K(t.scope.signer_set_id,`signerSetId`),signingWorkerId:e.identity.signingWorkerId,participantIds:[t.participantIds[0],t.participantIds[1]],registeredPublicKeyB64u:A(t.registeredPublicKey),signingWorkerVerifyingShareB64u:A(t.signingWorkerVerifyingShare),stateEpoch:t.stateEpoch.toString(10),activationTranscriptB64u:A(t.transcript),activationCapabilityBindingB64u:A(Uint8Array.from(t.activeCapabilityBinding))}}function Gi(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 Ki(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 qi(e){let t=_(e);if(!t||t.kind!==Fi)throw Error(`Stored Ed25519 Client material binding is invalid`);let n=d(t.materialActivation);if(!n.ok)throw Error(n.error.message);let r={kind:Fi,walletId:K(t.walletId,`binding.walletId`),nearAccountId:K(t.nearAccountId,`binding.nearAccountId`),nearEd25519SigningKeyId:K(t.nearEd25519SigningKeyId,`binding.nearEd25519SigningKeyId`),signerSlot:Ri(t.signerSlot,`binding.signerSlot`),rpId:K(t.rpId,`binding.rpId`),credentialIdB64u:K(t.credentialIdB64u,`binding.credentialIdB64u`),lifecycleId:K(t.lifecycleId,`binding.lifecycleId`),thresholdSessionId:zi(t.thresholdSessionId,`binding.thresholdSessionId`),materialActivation:n.value,signingRootId:K(t.signingRootId,`binding.signingRootId`),signingRootVersion:K(t.signingRootVersion,`binding.signingRootVersion`),signerSetId:K(t.signerSetId,`binding.signerSetId`),signingWorkerId:K(t.signingWorkerId,`binding.signingWorkerId`),participantIds:Vi(t.participantIds),registeredPublicKeyB64u:Bi(t.registeredPublicKeyB64u,`binding.registeredPublicKeyB64u`),signingWorkerVerifyingShareB64u:Bi(t.signingWorkerVerifyingShareB64u,`binding.signingWorkerVerifyingShareB64u`),stateEpoch:Hi(t.stateEpoch,`binding.stateEpoch`),activationTranscriptB64u:Bi(t.activationTranscriptB64u,`binding.activationTranscriptB64u`),activationCapabilityBindingB64u:Bi(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 Ji(e,t){let n=qi(e);return Ki(n,t),n}function Yi(e){let t=_(e);if(!t)throw Error(`Stored Ed25519 Client stable server scope is invalid`);let n=N(t.runtimePolicyScope);if(!n)throw Error(`Stored Ed25519 Client server runtime policy scope is invalid`);return{relayerKeyId:K(t.relayerKeyId,`stableServerScope.relayerKeyId`),participantIds:Vi(t.participantIds),runtimePolicyScope:n,routerAbNormalSigning:oe(t.routerAbNormalSigning)}}async function Xi(e){let t=e.stored.payload,n=_(t);if(!n)throw Error(`Stored Ed25519 Client local material locator is invalid`);let r=qi(n.binding),i=`ed25519:${ke(j(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!==Fi||e.stored.schemaVersion!==3||e.stored.publicKey!==i||e.stored.signerId!==r.nearEd25519SigningKeyId||a?.encVersion!==1||a.alg!==Ii)throw Error(`Stored Ed25519 Client local material record is invalid`);let o=Ft({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 Lt({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:Pi(JSON.stringify([e.stored.profileId,e.stored.signerSlot,e.stored.chainIdKey,e.stored.keyKind,r.materialActivation.activationId])),stableServerScope:Yi(n.stableServerScope)}}function Zi(e){let t=_(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!==Fi||t?.kind!==Fi||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 Qi(e,t){let n=K(t,`thresholdSessionId`);return{kind:ei,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:St(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:j(e.registeredPublicKeyB64u),signingWorkerVerifyingShare:j(e.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(e.stateEpoch),transcript:j(e.activationTranscriptB64u),activeCapabilityBinding:Array.from(j(e.activationCapabilityBindingB64u)),materialActivation:e.materialActivation}}function $i(){let e=new Uint8Array(12);return globalThis.crypto.getRandomValues(e),e}function ea(e){let t=e.identity,n=e.activeClient.metadata(),r=Wi({identity:t,metadata:n}),i=$i(),a=e.activeClient.sealLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:Gi(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:Fi,algorithm:`ed25519`,publicKey:`ed25519:${ke(n.registeredPublicKey)}`,signerId:t.nearEd25519SigningKeyId,payload:o,payloadEnvelope:{encVersion:1,alg:Ii,nonce:A(a.nonce),ciphertext:A(a.ciphertext),aad:Ze({profileId:e.target.profileId,signerSlot:t.signerSlot,chainIdKey:e.target.chainIdKey,accountAddress:e.target.accountAddress,keyKind:Fi,schemaVersion:3,signerId:t.nearEd25519SigningKeyId})},timestamp:Date.now(),schemaVersion:3}}async function ta(e){let t=await qn(e.store,{accountRefs:Kn(e.identity.nearAccountId)});if(!t)throw Error(`Local Ed25519 material requires a persisted wallet profile`);let n=ea({target:t,activeClient:e.activeClient,identity:e.identity,stableServerScope:e.stableServerScope,ownedPasskeyPrfFirst:j(e.passkeyPrfFirstB64u),lifecycle:{kind:`registration_or_rehydration`}});await e.store.storeKeyMaterial(n)}async function na(e){let t=K(e.nearAccountId,`nearAccountId`),n=await qn(e.store,{accountRefs:Kn(t)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,Ri(e.signerSlot,`signerSlot`),n.chainIdKey,Fi);return r?(Zi({stored:r,target:n,input:e}),{kind:`available`,locator:await Xi({stored:r,target:n,authority:e.authority})}):{kind:`unavailable`}}function ra(e){return e.publicLocator.walletId===e.identity.walletId&&e.publicLocator.nearAccountId===e.identity.nearAccountId&&e.publicLocator.signerSlot===e.identity.signerSlot}async function ia(e){let t=Ft({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 Lt({authority:t});if(n.authorityDigest!==e.authority.authorityDigest)throw Error(`Passkey Ed25519 authority does not match the Wallet Session`);return n}function aa(e){if(!e||e.activeClient.status().kind!==`active`)return{kind:`absent`};let t=Mn(e.activeClient.metadata());return{kind:`live`,runtime:jn(t),materialActivation:t}}function oa(e){return{kind:`blocked`,plan:e}}async function sa(e){let t=await ia(e),n=e.publicLocator.kind===`available`&&!ra({publicLocator:e.publicLocator,identity:e.identity})?{kind:`conflict`}:e.publicLocator.kind===`available`?{...e.publicLocator,authority:t}:e.publicLocator,r;try{r=await na({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 ca(e,t){let n=An({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 la(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await sa(e);if(r.kind===`corrupt`)return{kind:`blocked`,plan:ca(n,{kind:`absent`})};let i=An({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 ua(e){let{expectedAuthority:t,publicLocator:n,sealed:r}=await sa(e);if(r.kind===`corrupt`)return oa(ca(n,aa(e.liveMaterial)));let i=e.unlockSource.kind===`available`?{kind:`available`,authority:t}:{kind:`unavailable`},a=An({publicLocator:n,sealed:r,runtime:aa(e.liveMaterial),unlockSource:i});switch(a.kind){case`use_live_runtime`:{let t=e.liveMaterial;if(!t||t.activeClient.status().kind!==`active`||!f(a.materialActivation,Mn(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 da({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=Mn(t.activeClient.metadata());if(!f(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 oa(a);case`reauthorize_public_anchor`:throw Error(`Near Ed25519 material retirement requires explicit reauthorization`);default:throw Error(`Unsupported Near Ed25519 hydration plan`)}}async function da(e){let t=e.identity,n=await qn(e.store,{accountRefs:Kn(t.nearAccountId)});if(!n)return{kind:`unavailable`};let r=await e.store.getKeyMaterial(n.profileId,t.signerSlot,n.chainIdKey,Fi);return r?fa({stored:r,target:n,identity:t,ownedPasskeyPrfFirst:j(e.passkeyPrfFirstB64u)}):{kind:`unavailable`}}async function fa(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!==Fi||n.schemaVersion!==3||i?.encVersion!==1||i.alg!==Ii)throw Error(`Stored Ed25519 Client material record is invalid`);let a=Ji(n.payload?.binding,t),o=Qi(a,t.thresholdSessionId),s=`ed25519:${ke(o.registeredPublicKey)}`;if(n.publicKey!==s)throw Error(`Stored Ed25519 Client public key does not match its sealed binding`);return{kind:`rehydrated`,activeClient:(await ji.initializeBundled()).importLocalMaterial({ownedPasskeyPrfFirst:e.ownedPasskeyPrfFirst,binding:Gi(a),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:j(i.nonce),ciphertext:j(i.ciphertext)},metadata:o})}}function pa(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:A(e.transcript),activationCapabilityBindingB64u:A(Uint8Array.from(e.activeCapabilityBinding))}}function ma(e){if(!Me(e.binding))throw Error(`wallet custody cache accepts wallet custody seed envelopes only`);return{bindingJson:Re(e),nonceB64u:e.nonceB64u,ciphertextB64u:e.sealedCustodySecretB64u,aadHashB64u:e.aadHashB64u,ciphertextDigestB64u:e.ciphertextDigestB64u}}function ha(e){let{binding:t}=e.material,{activation:n}=e;return{kind:ei,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:St(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:j(t.registeredPublicKeyB64u),signingWorkerVerifyingShare:j(t.signingWorkerVerifyingShareB64u),stateEpoch:BigInt(t.stateEpoch),transcript:j(n.activationTranscriptB64u),activeCapabilityBinding:Array.from(j(n.activationCapabilityBindingB64u)),materialActivation:n.materialActivation}}async function ga(e){let t=ha({material:e.material,activation:e.activation});return(await ji.initializeBundled()).openCustodyCache({ownedFactorSecret:e.ownedFactorSecret,envelope:{bindingJson:e.envelope.bindingJson,nonce:j(e.envelope.nonceB64u),ciphertext:j(e.envelope.ciphertextB64u),aadHash:j(e.envelope.aadHashB64u),ciphertextDigest:j(e.envelope.ciphertextDigestB64u)},applicationBindingDigest:j(e.material.binding.applicationBindingDigestB64u),sealed:{kind:`router_ab_ed25519_yao_sealed_local_material_v1`,nonce:j(e.material.sealed.nonceB64u),ciphertext:j(e.material.sealed.ciphertextB64u)},metadata:t})}async function _a(e){let t=await e.loadCachedMaterial();return t.kind===`found`?{kind:`opened`,activeClient:await ga({material:t.material,activation:e.activation,envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret})}:(e.ownedFactorSecret.fill(0),{kind:`rejoin_required`})}async function va(e){let t=e.metadata;return await ga({material:e.material,activation:{materialActivation:Mn(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:e.materialFacts.identity.thresholdSessionId,activationTranscriptB64u:A(t.transcript),activationCapabilityBindingB64u:A(Uint8Array.from(t.activeCapabilityBinding))},envelope:e.envelope,ownedFactorSecret:e.ownedFactorSecret})}function ya(e,t,n){return{walletId:e.identity.walletId,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,thresholdSessionId:e.identity.thresholdSessionId,signerSlot:e.identity.signerSlot,rpId:t,credentialIdB64u:n,signingRootId:e.identity.signingRootId,signingRootVersion:e.identity.signingRootVersion,signingWorkerId:e.stableServerScope.routerAbNormalSigning.signingWorkerId}}async function ba(e){let t=j(e.passkeyPrfFirstB64u),n=null;try{n=await va(e);let r=e.registration.keyMaterials.find(xa);if(!r)throw Error(`The owner registration has no NEAR material target.`);let i=ea({target:{profileId:r.profileId,chainIdKey:r.chainIdKey,accountAddress:r.accountAddress},activeClient:n,identity:ya(e.materialFacts,e.rpId,e.credentialIdB64u),stableServerScope:e.materialFacts.stableServerScope,ownedPasskeyPrfFirst:t,lifecycle:{kind:`registration_or_rehydration`}});return{profiles:e.registration.profiles,initialAuthMethod:e.registration.initialAuthMethod,authenticators:e.registration.authenticators,signerActivations:e.registration.signerActivations,keyMaterials:[...e.registration.keyMaterials,i],lastProfileState:e.registration.lastProfileState}}finally{n?.dispose(),t.fill(0),e.ownedFactorSecret.fill(0)}}function xa(e){return e.keyKind===Zn}function Sa(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=D(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 Ca(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||!f(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})}function wa(){return Reflect.get(globalThis,`__SEAMS_REGISTRATION_BENCHMARK_DIAGNOSTICS`)===!0}const Ta=`[Registration] wallet timing summary`,Ea=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 Da(e,t,n){wa()&&console.info(`[Registration] ECDSA Server-Timing header presence`,{leg:t,present:!!n?.trim()}),Oa(e,n)}function Oa(e,t){if(e)for(let[n,r]of ka(t))e.record(n,r)}function ka(e){if(!e)return[];let t=[];for(let n of e.split(`,`)){let e=n.split(`;`),r=String(e[0]||``).trim(),i=Ea.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 q(e){ja({ceremonyId:e.ceremonyId,stage:e.stage,durationMs:Math.max(0,performance.now()-e.startedAt),outcome:e.outcome})}function Aa(e,t,n){ja({ceremonyId:e,stage:`session_hydration.${t}`,durationMs:n,outcome:`success`})}function ja(e){if(wa())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 Ma=[`passkeyAuthConfirmationMs`,`passkeyAuthPrfExtractionMs`,`passkeyAuthCredentialRedactionMs`,`passkeyAuthWorkerReadyMs`,`passkeyAuthWorkerRequestRoundTripMs`,`passkeyAuthWorkerResponseValidationMs`,`passkeyAuthRequestSetupMs`,`passkeyAuthPromptUserMs`,`passkeyAuthPromptElementDefineMs`,`passkeyAuthPromptMountMs`,`passkeyAuthPromptHostFirstUpdateMs`,`passkeyAuthPromptHostInteractiveMs`,`passkeyAuthPromptConfirmEventMs`,`passkeyAuthPromptDecisionWaitMs`,`passkeyAuthCredentialCreateStartMs`,`passkeyAuthCredentialCreateMs`,`passkeyAuthCredentialSerializeMs`,`passkeyAuthDuplicateRetryCount`,`passkeyAuthMainThreadTotalMs`],Na=[`emailOtpYaoEnrollmentMaterialWaitMs`,`emailOtpYaoWorkerRegistrationMs`,`emailOtpYaoTotalMs`],Pa=[`ecdsaClientBootstrapMs`,`ecdsaRegistrationTotalMs`,`ecdsaRegistrationClientCreateMs`,`ecdsaRegistrationGatewayRespondMs`,`ecdsaRegistrationClientProofVerifyMs`,`ecdsaRegistrationGatewayActivateMs`,`ecdsaRegistrationClientActivationFinalizeMs`],Fa=[`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`],Ia=[...Pa,...Fa],La=[`registrationWarmupMs`,`registrationWarmupWaitMs`,`registrationWarmupAuthenticatedWalletStateMs`,`registrationWarmupNoncePrefetchMs`,`registrationWarmupKeyMaterialReadMs`,`registrationWarmupUiConfirmPrewarmMs`,`registrationWarmupEmailOtpWorkerPrewarmMs`,`registrationWarmupEmailOtpYaoWasmInitMs`,`managedRegistrationGrantMs`,`registrationIntentMs`,`registrationIntentDigestMs`,`authProofMs`,...Ma,`emailOtpEnrollmentMaterialMs`,...Na,`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`,...Pa,`emailOtpRecoveryCodeBackupMs`,`walletRegisterFinalizeMs`,...Fa];function J(e){throw Error(`Unexpected registration timing branch: ${String(e)}`)}function Ra(e){switch(e.kind){case`near_ed25519`:return`near_ed25519`;case`evm_family_ecdsa`:return`evm_family_ecdsa`;default:return J(e)}}function za(e){return{kind:`signer_set`,branches:e.branches.map(Ra)}}function Ba(e,t){return e.branches.includes(t)}function Va(e){return Math.max(0,Math.round(performance.now()-e))}function Ha(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 Ua(e){if(!v(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(!v(n))continue;let e=Ha(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 Wa(e){return{kind:e.kind,route:e.route,entries:e.entries.map(Ga)}}function Ga(e){return{name:e.name,durationMs:e.durationMs}}function Ka(e,t){let n={};for(let r of e)n[r]=t[r];return n}function qa(e){let t={};for(let n of e)t[n]=0;return t}function Ja(e){switch(e.authMethod){case`passkey`:return{kind:`passkey`,authProofMs:e.buckets.authProofMs,...Ka(Ma,e.buckets),emailOtpEnrollmentMaterialMs:0,emailOtpRecoveryCodeBackupMs:0};case`email_otp`:return{kind:`email_otp`,authProofMs:e.buckets.authProofMs,...qa(Ma),emailOtpEnrollmentMaterialMs:e.buckets.emailOtpEnrollmentMaterialMs,emailOtpRecoveryCodeBackupMs:e.buckets.emailOtpRecoveryCodeBackupMs};default:return J(e.authMethod)}}function Ya(e){return Ba(e.signerSet,`near_ed25519`)?{kind:`ed25519_yao_enabled`,...Ka(Na,e.buckets)}:{kind:`ed25519_disabled`,...qa(Na)}}function Xa(e){return Ba(e.signerSet,`evm_family_ecdsa`)?{kind:`ecdsa_enabled`,...Ka(Ia,e.buckets)}:{kind:`ecdsa_disabled`,...qa(Ia)}}const Za=[`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 $a(e){return{name:e.name,kind:e.kind,startOffsetMs:e.startOffsetMs,endOffsetMs:e.endOffsetMs}}function eo(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 to(e){let t=Za.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=eo(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($a)}}function no(e){let t=Ka(La,e.buckets);return{...t,auth:Ja({authMethod:e.authMethod,buckets:t}),ed25519:Ya({signerSet:e.signerSet,buckets:t}),ecdsa:Xa({signerSet:e.signerSet,buckets:t}),emailOtpYaoPrewarm:{...e.emailOtpYaoPrewarm}}}var ro=class{startedAt;nearStageStartedAt;buckets;relayDiagnostics;spans;emailOtpYaoPrewarm;constructor(e){this.startedAt=e,this.nearStageStartedAt=e,this.buckets=qa(La),this.relayDiagnostics=[],this.spans=[],this.emailOtpYaoPrewarm=io()}markNearStage(e,t){let n=performance.now();ja({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]=Va(n),this.recordSpan(e,n,performance.now())}}record(e,t){let n=Math.max(0,Math.round(t));this.buckets[e]+=n}snapshot(){return Ka(La,this.buckets)}spansSnapshot(){return this.spans.map($a)}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=Ua(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(Wa)}totalMs(){return Va(this.startedAt)}};function io(){return{kind:`not_requested`,elapsedMs:0,workerPrewarmMs:0,yaoWasmInitMs:0}}function ao(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:to({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:no({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function oo(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:to({totalElapsedMs:t,buckets:n,spans:e.recorder.spansSnapshot()}),errorCode:e.errorCode,relayDiagnostics:e.recorder.routeDiagnosticsSnapshot(),timings:no({authMethod:e.authMethod,signerSet:e.signerSet,buckets:n,emailOtpYaoPrewarm:e.recorder.emailOtpYaoPrewarmSnapshot()})}}function so(e){wa()&&(console.info(Ta,e),console.info(`${Ta} ${JSON.stringify(e)}`))}function co(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 Y(e){return{kind:`unavailable`,reason:e}}function lo(e){let t=e.selected;if(t.kind!==`resolved`)switch(t.kind){case`missing_selection`:return Y(`selected_authority_missing`);case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return Y(`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?Y(`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}:Y(`auth_method_mismatch`):Y(`authority_inactive`):Y(`auth_method_inactive`):Y(`wallet_locked`)}function uo(e){let t=e.authority.signerActivations;return e.keyFamily===`ed25519`?t.ed25519?.materialActivation??null:t.ecdsa?.materialActivation??null}function fo(e){return e.session.capabilitySubjects.filter(t=>t.kind===`sign`&&t.keyFamily===e.keyFamily&&f(t.materialActivation,e.materialActivation)).length===1}function po(e){return nr(e)?{keyFamily:`ecdsa_secp256k1`,materialActivation:e.signer.materialActivation}:{keyFamily:`ed25519`}}async function mo(e){let{input:t,ports:n}=e,r;try{r=await n.resolveSelectedWalletAuthority(String(t.walletId))}catch{return Y(`persistence_unavailable`)}let i=lo({selected:r,walletId:t.walletId,authMethod:t.authMethod});if(`kind`in i)return i;let a=uo({authority:i.authority,keyFamily:t.requiredSigningSubject.keyFamily});if(!a)return Y(`signer_material_missing`);if(t.requiredSigningSubject.keyFamily===`ecdsa_secp256k1`&&!f(t.requiredSigningSubject.materialActivation,a))return Y(`signer_material_mismatch`);let o;try{o=await n.readExactWithOperationCredential({walletId:t.walletId,authorityId:i.authority.authorityId,authMethodId:i.authMethod.walletAuthMethodId})}catch{return Y(`persistence_unavailable`)}switch(o.kind){case`found`:break;case`missing`:return Y(`wallet_session_missing`);case`upgrade_required`:return Y(`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?Y(`wallet_session_identity_mismatch`):t.expiry.kind===`unexpired`&&s.expiresAtMs<=t.expiry.nowMs?Y(`wallet_session_expired`):t.expiry.kind===`expired`&&s.expiresAtMs>t.expiry.nowMs?Y(`wallet_session_not_expired`):fo({session:s,keyFamily:t.requiredSigningSubject.keyFamily,materialActivation:a})?{kind:`resolved`,resolved:{authMethod:i.authMethod,session:s,operationCredential:c,walletSessionId:c.walletSessionId,materialActivation:a}}:Y(`wallet_session_capability_mismatch`)}function ho(e){return String(e||``).trim()}function go(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:0}function _o(e){let t=Math.floor(Number(e));return Number.isSafeInteger(t)&&t>=0?t:null}function vo(e){return e.expiresAtMs<=e.nowMs?{kind:`expired`}:e.remainingUses<=0?{kind:`exhausted`}:null}function yo(e,t){let n=ho(e);return n?{kind:`wallet_session_opaque`,walletSessionToken:n,credential:{kind:`wallet_session_opaque`,walletSessionToken:n,home:t}}:null}function bo(e){let n=yo(ho(e.walletSessionToken),e.home);if(!n)return{ok:!1,reason:`missing_wallet_session_token`};let r=ho(e.walletId),i=ho(e.nearAccountId),a=ho(e.nearEd25519SigningKeyId);if(!r||!i||!a)return{ok:!1,reason:`wallet_binding_mismatch`};let o=fe(e.walletSessionId),s=pe(e.authorizationId),c=ue(e.quotaId),l=t(e.thresholdSessionId);if(!o.ok||!s.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=_o(e.nowMs),d=go(e.remainingUses),f=go(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=vo({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=F(e.runtimePolicyScope)}catch{return{ok:!1,reason:`missing_signing_root`}}return m.signingRootId!==ho(e.signingRootId)||m.signingRootVersion!==ho(e.signingRootVersion)?{ok:!1,reason:`signing_root_mismatch`}:{ok:!0,value:{curve:`ed25519`,auth:n,walletSessionId:o.value,authorizationId:s.value,quotaId:c.value,thresholdSessionId:l.value,remainingUses:d,expiresAtMs:f,runtimePolicyScope:e.runtimePolicyScope,signingRootId:m.signingRootId,signingRootVersion:ho(m.signingRootVersion),routerAbNormalSigning:e.routerAbNormalSigning}}}const xo=Ve.signingSessionSeals,So=Ve.signingSessionRestoreLeases,Co=[He.ed25519ThresholdSessionId,He.ecdsaThresholdSessionId];function wo(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error||Error(`IndexedDB request failed`))})}function To(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 Eo(){if(Ue.isDisabled())return null;try{return We(await Ue.getDB())}catch{return null}}function Do(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 Oo(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 ko(e,t){let n=new Map;for(let r of Co)try{let i=await Do(e.index(r),t);for(let e of i)n.set(String(e.primaryKey),e)}catch{}return n.size?[...n.values()]:await Oo(e).catch(()=>[])}const X=new class{async collectAllRawSealedRecordEntries(){let e=await Eo();if(!e)return[];let t=e.transaction(xo,`readonly`),n=await Oo(t.objectStore(xo));return await To(t).catch(()=>void 0),n}async collectRawSealedRecordEntriesByThresholdSessionId(e){let t=await Eo();if(!t)return[];let n=t.transaction(xo,`readonly`),r=await ko(n.objectStore(xo),e);return await To(n).catch(()=>void 0),r}async replaceSealedRecord(e){let t=await Eo();if(!t)return;let n=t.transaction(xo,`readwrite`),r=n.objectStore(xo);for(let t of e.staleStoreKeys)r.delete(t);r.put(e.row),await To(n)}async replaceSealedRecordAndDeleteRestoreLease(e){let t=await Eo();if(!t)return!1;let n=t.transaction([xo,So],`readwrite`),r=n.objectStore(xo);for(let t of e.staleStoreKeys)r.delete(t);return r.put(e.row),n.objectStore(So).delete(e.restoreLeaseKey),await To(n),!0}async deleteSealedRecords(e){if(!e.length)return;let t=await Eo();if(!t)return;let n=t.transaction(xo,`readwrite`),r=n.objectStore(xo);for(let t of e)r.delete(t);await To(n).catch(()=>void 0)}async deleteRestoreLease(e){let t=await Eo();if(!t)return;let n=t.transaction(So,`readwrite`);n.objectStore(So).delete(e),await To(n).catch(()=>void 0)}async deleteRestoreLeaseIf(e){let t=await Eo();if(!t)return;let n=t.transaction(So,`readwrite`),r=n.objectStore(So),i=await wo(r.get(e.leaseKey));e.shouldDelete(i)&&r.delete(e.leaseKey),await To(n).catch(()=>void 0)}async withRestoreLeaseTransaction(e,t){let n=await Eo();if(!n)return null;try{let r=n.transaction([xo,So],`readwrite`),i=r.objectStore(xo),a=r.objectStore(So),o=await ko(i,e),s=!1,c=await t({entries:o,getRawRestoreLease:async e=>await wo(a.get(e)),putRestoreLease:e=>a.put(e),abort:()=>{s=!0}});return s?(r.abort(),c):(await To(r),c)}catch{return null}}};function Ao(e){throw Error(`Unhandled durable sealed-session identity: ${String(e)}`)}function jo(e){return{kind:`delete_durable_sealed_session`,durableRecord:e.durableRecord,deleteReason:e.deleteReason,preserveResolvedIdentity:e.preserveResolvedIdentity}}function Mo(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 Ao(e)}}function No(e){return[`ecdsa-material-v2`,e.walletId,e.authMethod,Je(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 Po=`ecdsa_inactive_sealed_material_v1`,Fo=`sealed_record`;function Io(e){let t=_(e)??{},n=m(t.ed25519),r=m(t.ecdsa);return{...n?{ed25519:n}:{},...r?{ecdsa:r}:{}}}function Lo(e){return Io((_(e)??{}).thresholdSessionIds)}function Ro(e){let t=_(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 zo(e){let t=String(e||``).trim();return t===`ed25519`||t===`ecdsa`?t:void 0}function Bo(e){let t=_(e);return t&&Fo in t?t[Fo]:e}function Vo(e){let t=e.ecdsaRestore?.chainTarget,n=m(e.thresholdSessionIds.ecdsa),r=m(e.thresholdSessionIds.ed25519);return{store_key:e.storeKey,wallet_id:e.walletId,auth_method:e.authMethod,curve:e.curve,signing_root_id:m(`signingRootId`in e?e.signingRootId:void 0),signing_root_version:m(`signingRootVersion`in e?e.signingRootVersion:void 0),ed25519_threshold_session_id:r,ecdsa_threshold_session_id:n,threshold_session_id:n||r,key_handle:m(e.ecdsaRestore?.keyHandle),chain_target_key:t?Je(t):void 0,expires_at_ms:e.expiresAtMs,updated_at:e.updatedAtMs,[Fo]:e}}function Ho(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:Je(e.ecdsaRestore.chainTarget),updated_at:e.updatedAtMs,[Fo]:e}}function Uo(e){return Vo(e)}function Wo(e){let t=String(e||``).trim().toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:void 0}function Go(e){return e.curve?e.curve:e.thresholdSessionIds.ecdsa?`ecdsa`:e.thresholdSessionIds.ed25519?`ed25519`:null}function Ko(e){try{return Rt(e)}catch{return null}}function qo(e){switch(e){case`login`:case`registration`:case`manual-bootstrap`:case`email_otp`:return e;default:return null}}function Jo(e){try{let t=F(I(e)),n=m(t.signingRootId),r=m(t.signingRootVersion);return n&&r?{signingRootId:n,signingRootVersion:r}:null}catch{return null}}function Yo(e){let t=_(e);if(!t)return;let n=null;try{n=Ge(_(t.chainTarget)??{})}catch{n=null}let r=qo(t.source),i=At(t.authority),a=m(t.rpId),o=t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?t.runtimePolicyScope:void 0,s=Jo(o),c=m(t.signingRootId),l=m(t.signingRootVersion);if(c&&s?.signingRootId&&c!==s.signingRootId||l&&s?.signingRootVersion&&l!==s.signingRootVersion)return;let u=c||s?.signingRootId||``,d=l||s?.signingRootVersion||``,f=m(t.credentialIdB64u),p=null;try{p=Yt(t.roleLocalMaterialRef)}catch{p=null}let h=kt(t.emailOtpAuthority),g=t.provider===`google`||t.provider===`email`?t.provider:null,v=m(t.providerSubjectId),y=m(t.emailHashHex),b=m(t.keyHandle),x=m(t.ecdsaThresholdKeyId),S=Wo(t.ethereumAddress),C=m(t.relayerKeyId),w=m(t.thresholdEcdsaPublicKeyB64u),T=Ko(t.routerAbEcdsaDerivationNormalSigning),E=null;try{E=Ct(t.publicCapability)}catch{E=null}let D=rs(t.participantIds);if(!n||!r||!u||!d||!b||!S||!C||!T||!E||!D.length)return;let O=f&&a&&p&&i&&r!==`email_otp`?{source:r,authority:i,roleLocalMaterialRef:p,rpId:a,credentialIdB64u:f}:v&&g&&y&&p&&i&&h&&r===`email_otp`?{source:r,provider:g,providerSubjectId:v,emailHashHex:y,authority:i,emailOtpAuthority:h,roleLocalMaterialRef:p}:null;if(!O)return;let k=m(t.clientVerifyingShareB64u);return{chainTarget:n,signingRootId:u,signingRootVersion:d,...O,keyHandle:b,...x?{ecdsaThresholdKeyId:x}:{},ethereumAddress:S,relayerKeyId:C,...k?{clientVerifyingShareB64u:k}:{},...w?{thresholdEcdsaPublicKeyB64u:w}:{},participantIds:D,routerAbEcdsaDerivationNormalSigning:T,publicCapability:E,...o?{runtimePolicyScope:o}:{}}}function Xo(e){let t=_(e);if(!t)return;let n=m(t.nearAccountId),i=m(t.nearEd25519SigningKeyId),a=m(t.rpId),o=m(t.credentialIdB64u),s=m(t.providerSubjectId),c=t.provider===`google`||t.provider===`email`?t.provider:null,l=m(t.emailHashHex),u=m(t.authSubjectId),f=m(t.relayerKeyId),p=rs(t.participantIds),h=r(t.signerSlot),g=ae(t.routerAbNormalSigning),v=d(t.materialActivation),y=o&&!s&&v.ok?{credentialIdB64u:o,materialActivation:v.value}:c&&s&&l&&!o&&v.ok?{provider:c,providerSubjectId:s,emailHashHex:l,materialActivation:v.value}:null;if(!(!n||!i||!a||!f||!p.length||h==null||h<=0||!g||!y||u))return{nearAccountId:n,nearEd25519SigningKeyId:i,rpId:a,...y,relayerKeyId:f,participantIds:p,...t.runtimePolicyScope&&typeof t.runtimePolicyScope==`object`?{runtimePolicyScope:t.runtimePolicyScope}:{},signerSlot:h,routerAbNormalSigning:g}}function Zo(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($o).join(`:`)}function Qo(e){let t=e.restore.roleLocalMaterialRef;return[`inactive-material`,e.walletId,e.authMethod,`ecdsa`,Je(e.restore.chainTarget),t.materialActivation.activationId].map($o).join(`:`)}function $o(e){return encodeURIComponent(String(e||``).trim())}function es(e){let t=String(e||``).trim();return t===`passkey`||t===`email_otp`?t:void 0}function ts(e){let t=_(e);return!!(m(t?.subjectId)||m(t?.userId))}function ns(e){let t=_(e);return!!(m(t?.signingRootId)||m(t?.signingRootVersion))}function rs(e){return Array.isArray(e)?e.map(e=>Math.floor(Number(e))).filter(e=>Number.isFinite(e)&&e>0):[]}function is(e){return{authMethod:m(e?.authMethod)||null,curve:m(e?.curve)||null,storeKey:m(e?.storeKey)||null,walletId:m(e?.walletId)||null,thresholdSessionIds:Lo(e),hasEcdsaRestore:!!_(e?.ecdsaRestore),hasEd25519Restore:!!_(e?.ed25519Restore),issuedAtMs:r(e?.issuedAtMs),expiresAtMs:r(e?.expiresAtMs),remainingUses:r(e?.remainingUses),updatedAtMs:r(e?.updatedAtMs)}}function Z(e,t,n){return{kind:e,storeKey:m(t?.storeKey)||null,walletId:m(t?.walletId)||null,reason:n,safeSummary:is(t)}}function as(e){return{v:2,alg:ce,storageScope:se,authMethod:e,secretKind:le}}function os(e){e=Bo(e);let t=_(e);if(!t)return Z(`malformed`,null,`invalid_payload`);if(Ro(t))return Z(`delete_required`,t,`invalid_identity`);if(t.recordKind===`ecdsa_reauth_anchor_v1`)return Z(`delete_required`,t,`invalid_header`);if(t.recordKind===Po){let e=ls(t);return e?{kind:`ecdsa_inactive_material`,record:e}:Z(`malformed`,t,`invalid_identity`)}if(Number(t.v)===1)return Z(`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 Z(`malformed`,t,`invalid_header`);let n=String(t.authMethod||``).trim(),i=Lo(t),a=m(t.sealedSecretB64u),o=zo(t.curve),s=m(t.subjectId),c=m(t.userId),l=m(t.walletId),u=m(t.signingRootId),d=m(t.signingRootVersion),f=d||(u?`default`:null),p=m(t.relayerUrl),h=m(t.keyVersion),g=m(t.groupId),v=r(t.issuedAtMs),y=r(t.expiresAtMs),b=r(t.remainingUses),x=r(t.updatedAtMs);if(!a||!h||g!==`rfc2409-group2`||n!==`passkey`&&n!==`email_otp`||!i.ed25519&&!i.ecdsa||!l)return Z(`malformed`,t,`invalid_identity`);let S=Go({curve:o,thresholdSessionIds:i});if(!S||v==null||v<=0||y==null||y<=0||b==null||b<0||x==null||x<=0)return Z(`malformed`,t,`invalid_identity`);let C=_(t.ecdsaRestore),w=_(t.ed25519Restore),T=Yo(t.ecdsaRestore),E=Xo(t.ed25519Restore);if(S===`ecdsa`){if(!i.ecdsa)return Z(`malformed`,t,`invalid_identity`);if(s||c||u||d)return Z(`delete_required`,t,`invalid_identity`);if(!C||!p)return Z(`rebuild_required`,t,`missing_restore_metadata`);if(!rs(C.participantIds).length)return Z(`delete_required`,t,`missing_participant_ids`);if(!T)return Z(`rebuild_required`,t,`missing_restore_metadata`);let e=No({walletId:l,authMethod:n,chainTarget:T.chainTarget,materialActivation:T.roleLocalMaterialRef.materialActivation}),r=m(t.storeKey);return r&&r!==e?Z(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...as(n),storeKey:e,thresholdSessionIds:{...i.ed25519?{ed25519:i.ed25519}:{},ecdsa:i.ecdsa},sealedSecretB64u:a,curve:`ecdsa`,walletId:l,relayerUrl:p,keyVersion:h,groupId:z,ecdsaRestore:T,...E?{ed25519Restore:E}:{},issuedAtMs:v,expiresAtMs:y,remainingUses:b,updatedAtMs:x}}}if(!i.ed25519)return Z(`malformed`,t,`invalid_identity`);if(s||c)return Z(`delete_required`,t,`invalid_identity`);if(!w||!p)return Z(`rebuild_required`,t,`missing_restore_metadata`);if(!rs(w.participantIds).length)return Z(`delete_required`,t,`missing_participant_ids`);if(!E)return Z(`rebuild_required`,t,`missing_restore_metadata`);let D=Zo({walletId:l,authMethod:n,restore:E}),O=m(t.storeKey);return O&&O!==D?Z(`malformed`,t,`invalid_identity`):{kind:`current`,record:{...as(n),storeKey:D,thresholdSessionIds:{ed25519:i.ed25519,...i.ecdsa?{ecdsa:i.ecdsa}:{}},sealedSecretB64u:a,curve:`ed25519`,walletId:l,...u?{signingRootId:u}:{},...f?{signingRootVersion:f}:{},relayerUrl:p,keyVersion:h,groupId:z,...T?{ecdsaRestore:T}:{},ed25519Restore:E,issuedAtMs:v,expiresAtMs:y,remainingUses:b,updatedAtMs:x}}}function ss(e){let t=os(Bo(e));return t.kind===`current`?t.record:null}function cs(e){let t=_(e);if(!t||t.clientVerifyingShareB64u!=null)return null;let n,r,i,a;try{n=Ge(t.chainTarget&&typeof t.chainTarget==`object`?t.chainTarget:{}),r=I(t.runtimePolicyScope);let e=Rt(t.routerAbEcdsaDerivationNormalSigning);if(!e)return null;i=e,a=Ct(t.publicCapability)}catch{return null}let o=m(t.signingRootId),s=m(t.signingRootVersion),c=null;try{c=Yt(t.roleLocalMaterialRef)}catch{c=null}let l=At(t.authority),u=kt(t.emailOtpAuthority),d=m(t.keyHandle),f=m(t.ecdsaThresholdKeyId),p=m(t.ethereumAddress),h=m(t.relayerKeyId),g=m(t.thresholdEcdsaPublicKeyB64u),v=rs(t.participantIds);if(!o||!s||!d||!f||!p||!h||!g||!v.length)return null;let y={chainTarget:n,signingRootId:o,signingRootVersion:s,keyHandle:d,ecdsaThresholdKeyId:f,ethereumAddress:p,relayerKeyId:h,thresholdEcdsaPublicKeyB64u:g,participantIds:v,runtimePolicyScope:r,routerAbEcdsaDerivationNormalSigning:i,publicCapability:a};switch(t.source){case`email_otp`:{let e=t.provider===`google`||t.provider===`email`?t.provider:null,n=m(t.providerSubjectId),r=m(t.emailHashHex);return!e||!n||!r||!c||!l||!u||t.rpId!=null||t.credentialIdB64u!=null?null:{...y,source:`email_otp`,provider:e,providerSubjectId:n,emailHashHex:r,authority:l,emailOtpAuthority:u,roleLocalMaterialRef:c}}case`login`:case`registration`:case`manual-bootstrap`:{let e=m(t.rpId),n=m(t.credentialIdB64u);return!e||!n||!c||!l||t.providerSubjectId!=null||t.emailHashHex!=null?null:{...y,source:t.source,authority:l,roleLocalMaterialRef:c,rpId:e,credentialIdB64u:n}}default:return null}}function ls(e){let t=_(Bo(e));if(!t||t.recordKind!==Po||Ro(t)||t.thresholdSessionIds!=null||t.ed25519Restore!=null||t.curve!==`ecdsa`)return null;let n=es(t.authMethod),i=m(t.walletId),a=m(t.relayerUrl),o=cs(t.ecdsaRestore),s=m(t.sealedSecretB64u),c=m(t.keyVersion),l=m(t.groupId),u=r(t.updatedAtMs),d=t.authorizationRetirementReason;if(!n||!i||!a||!o||t.alg!==`shamir3pass-v2`||t.storageScope!==`iframe_origin_indexeddb`||t.secretKind!==`signing_session_secret32`||!s||!c||l!==`rfc2409-group2`||t.issuedAtMs!=null||t.expiresAtMs!=null||t.remainingUses!=null||u==null||u<=0||d!==`expired`&&d!==`exhausted`)return null;let f=Qo({walletId:i,authMethod:n,restore:o});return m(t.storeKey)===f?us({storeKey:f,walletId:i,relayerUrl:a,sealedSecretB64u:s,keyVersion:c,updatedAtMs:u,authorizationRetirementReason:d,authMethod:n,ecdsaRestore:o}):null}function us(e){let{authMethod:t,ecdsaRestore:n}=e,r={recordKind:Po,storeKey:e.storeKey,curve:`ecdsa`,walletId:e.walletId,relayerUrl:e.relayerUrl,alg:ce,storageScope:se,secretKind:le,sealedSecretB64u:e.sealedSecretB64u,keyVersion:e.keyVersion,groupId:z,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 ds(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 fs(e){let t=String(e.thresholdSessionId||``).trim(),n=zo(e.curve),i=e.authMethod===`passkey`||e.authMethod===`email_otp`?e.authMethod:void 0;if(!n||!i)return null;let a=ps({thresholdSessionId:t,curve:n,thresholdSessionIds:e.thresholdSessionIds}),o=m(e.walletId),s=m(e.sealedSecretB64u),c=r(e.expiresAtMs),l=r(e.remainingUses),u=r(e.issuedAtMs),d=r(e.updatedAtMs),f=m(e.keyVersion);if(!t||!s||!f||e.groupId!==`rfc2409-group2`||!a.ed25519&&!a.ecdsa||u==null||u<=0||c==null||c<=0||l==null||l<0||d==null||d<=0)return null;let p=Yo(e.ecdsaRestore),h=Xo(e.ed25519Restore);if(ts(e)||n===`ecdsa`&&(!p?.chainTarget||!o||ns(e)))return null;let g,_;e.curve===`ed25519`&&(g=m(e.signingRootId),_=m(e.signingRootVersion));let v=os({...as(i),thresholdSessionIds:a,sealedSecretB64u:s,curve:n,...o?{walletId:o}:{},...g?{signingRootId:g}:{},..._?{signingRootVersion:_}:{},...m(e.relayerUrl)?{relayerUrl:m(e.relayerUrl)}:{},keyVersion:f,groupId:z,...p?{ecdsaRestore:p}:{},...h?{ed25519Restore:h}:{},issuedAtMs:u,expiresAtMs:c,remainingUses:l,updatedAtMs:d});return v.kind===`current`?v.record:(ds({operation:`build current sealed session record`,classification:v}),null)}function ps(e){let t=Io(e.thresholdSessionIds),n=String(e.thresholdSessionId||``).trim();return n&&(e.curve===`ed25519`&&t.ed25519===n||e.curve===`ecdsa`&&t.ecdsa===n)?t:{}}function ms(e,t){let n=m(t),r=m(e.ecdsaThresholdKeyId),i=m(e.thresholdEcdsaPublicKeyB64u);if(!n||!r||!i)return null;let a;try{a=I(e.runtimePolicyScope)}catch{return null}let o={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{...o,source:`email_otp`,provider:e.provider,providerSubjectId:e.providerSubjectId,emailHashHex:e.emailHashHex,authority:e.authority,emailOtpAuthority:e.emailOtpAuthority,roleLocalMaterialRef:Yt(e.roleLocalMaterialRef)};case`login`:case`registration`:case`manual-bootstrap`:return{...o,source:e.source,authority:e.authority,roleLocalMaterialRef:Yt(e.roleLocalMaterialRef),rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}}}function hs(e){let t=e.record,n=ms(t.ecdsaRestore,t.relayerUrl);return n?us({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 gs(e){let t=hs(e);if(!t)throw Error(`[SigningSessionSealedStore] inactive ECDSA material requires exact public restore facts`);return t}const _s=15e3;function vs(e){return M(e,32,`sealed signing session restore IDs`)}function ys(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 bs(e){let t=new Set,n=m(e.walletId);return n&&t.add(n),t}function xs(e,t){let n=bs(e);if(!n.size)return!1;for(let e of bs(t))if(n.has(e))return!0;return!1}function Ss(e,t){if(!xs(e,t)||e.authMethod!==t.authMethod||e.curve!==t.curve)return!1;if(e.curve===`ed25519`&&t.curve===`ed25519`)return f(e.ed25519Restore.materialActivation,t.ed25519Restore.materialActivation);if(e.curve===`ecdsa`){let n=m(e.ecdsaRestore?.keyHandle),r=m(t.ecdsaRestore?.keyHandle);if(!n||!r||n!==r)return!1;let i=e.ecdsaRestore?.chainTarget,a=t.ecdsaRestore?.chainTarget;if(!i||!a||!Xe(i,a))return!1}return!0}function Cs(e){return C({storeKey:e.storeKey,walletId:e.walletId,authMethod:e.authMethod,signingRootId:e.signingRootId??null,signingRootVersion:e.signingRootVersion??null,restore:e.ed25519Restore})}function ws(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 Ts(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 Es(e,t={writeCanonical:!1}){let n=e[0];if(!n)return null;let r=Cs(n.record);for(let t of e.slice(1))if(Cs(t.record)!==r)throw Error(`[SigningSessionSealedStore] exact Ed25519 material has conflicting public identity facts`);let i=e.reduce(Ts),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 X.replaceSealedRecord({row:Uo(i.record),staleStoreKeys:o}),i.record}async function Ds(e){let t=Bo(e.value),n=os(t);if(n.kind!==`current`)return n;let r=_(t);return Ro(_(e.value))||Ro(r)?Z(`delete_required`,r,`invalid_identity`):n}function Os(e){return Lo(Bo(e))}function ks(e,t,n,r){ds({operation:e,classification:t}),(t.kind===`delete_required`||t.kind===`malformed`)&&r.push(n)}function As(e){let t=_(e);if(!t)return null;if(_(t.lease))return As(t.lease);if(Number(t.v)!==1||Ro(t))return null;let n=m(t.leaseKey),i=m(t.ownerId),a=m(t.attemptId),o=r(t.startedAtMs),s=r(t.expiresAtMs);return!n||!i||!a||o==null||o<=0||s==null||s<=o?null:{v:1,leaseKey:n,ownerId:i,attemptId:a,startedAtMs:o,expiresAtMs:s}}function js(e){return{v:1,leaseKey:e.leaseKey,ownerId:e.ownerId,attemptId:vs(`restore-attempt`),startedAtMs:e.nowMs,expiresAtMs:e.nowMs+e.ttlMs}}function Ms(e,t,n){return!(e.authMethod!==n.authMethod||e.thresholdSessionIds[n.curve]!==t||n.curve===`ecdsa`&&(!e.ecdsaRestore?.chainTarget||!Xe(e.ecdsaRestore.chainTarget,n.chainTarget)))}function Ns(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 Ps(e){let t=await X.collectRawSealedRecordEntriesByThresholdSessionId(e);return t.length?t:(await X.collectAllRawSealedRecordEntries()).filter(t=>{let n=Os(t.value);return n.ed25519===e||n.ecdsa===e})}async function Fs(e,t,n){let r=await Ps(e),i=null,a=[],o=[];for(let s of r){let r=await Ds(s);if(r.kind===`current`){Ms(r.record,e,t)&&(i=r.record,r.record.curve===`ed25519`&&a.push(ws(s,r.record)));continue}ks(n,r,s.primaryKey,o)}return await X.deleteSealedRecords(o),a.length>0?await Es(a):i}async function Is(e,t){try{let n=await Ps(e),r=[];for(let i of n){let n=await Ds(i),a=n.kind===`current`?n.record:null;a?.storeKey&&Ms(a,e,t)&&r.push(i.primaryKey)}await X.deleteSealedRecords(r)}catch{}}async function Ls(e){if(!bs(e).size||!e.authMethod)return[];try{let t=await X.collectAllRawSealedRecordEntries(),n=[];for(let r of t){let t=await Ds(r),i=t.kind===`current`?t.record:null;i&&i.storeKey!==e.storeKey&&Ss(i,e)&&n.push(i)}return n}catch{return[]}}function Rs(e){if(e.curve!==`ecdsa`)return null;let t=ms(e.ecdsaRestore,e.relayerUrl);return t?Qo({walletId:e.walletId,authMethod:e.authMethod,restore:t}):null}async function zs(e,t){let n=Ns(t,`read`),r=String(e||``).trim();return r?await Fs(r,n,`read`):null}function Bs(e,t){return e.curve===`ed25519`&&e.authMethod===t.authMethod&&f(e.ed25519Restore.materialActivation,t.materialActivation)}async function Vs(e){let t=await X.collectAllRawSealedRecordEntries(),n=[],r=[];for(let i of t){let t=await Ds(i);if(t.kind===`current`){let n=t.record;Bs(n,e)&&r.push(ws(i,n));continue}ks(`read exact Ed25519 material`,t,i.primaryKey,n)}return await X.deleteSealedRecords(n),await Es(r)}async function Hs(e){let t=m(e.walletId);if(!t)return[];let n=Ns(e.filter,`list exact account records`),r=e.filter.curve===`ecdsa`?e.filter.chainTarget:void 0,i=await X.collectAllRawSealedRecordEntries(),a=[];try{let e=[],o=new Set,s=new Map;for(let c of i){let i=await Ds(c);if(i.kind!==`current`){ks(`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||!Xe(l.ecdsaRestore.chainTarget,r)))){if(l.curve===`ed25519`){let e=s.get(l.storeKey)??[];e.push(ws(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 Es(t);n&&e.push(n)}return await X.deleteSealedRecords(a),e}finally{await X.deleteSealedRecords(a)}}async function Us(e){let t=m(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 X.collectAllRawSealedRecordEntries(),r=[];try{let i=[],a=new Set;for(let o of n){let n=await Ds(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`){ks(`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 X.deleteSealedRecords(r),i}finally{await X.deleteSealedRecords(r)}}async function Ws(e){let t=os(e);if(t.kind!==`current`){ds({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 X.collectAllRawSealedRecordEntries();for(let r of t){let t=await Ds(r);t.kind===`current`&&t.record.curve===`ed25519`&&t.record.storeKey===n.storeKey&&e.push(ws(r,t.record))}await Es(e,{writeCanonical:!0});return}let r=await Ls(n),i=Rs(n);await X.replaceSealedRecord({row:Uo(n),staleStoreKeys:[...r.map(e=>e.storeKey),...i?[i]:[]]})}function Gs(e,t,n){return Ks({current:e,inactive:gs({record:e,retirement:t,updatedAtMs:n})})}async function Ks(e){await X.replaceSealedRecordAndDeleteRestoreLease({row:Ho(e.inactive),staleStoreKeys:[e.current.storeKey],restoreLeaseKey:e.current.storeKey})}async function qs(e){let t=Ns(e.filter,`update policy`),n=String(e.thresholdSessionId||``).trim();if(!n)return;let r=await zs(n,t);r&&await Ys(r,e)}async function Js(e){let t=await Vs(e.locator);t&&await Ys(t,e)}async function Ys(e,t){let n=r(t.expiresAtMs??e.expiresAtMs),i=r(t.remainingUses??e.remainingUses),a=r(t.updatedAtMs);if(n==null||n<=0||i==null||i<0||a==null||a<=0)return;let o={...e,expiresAtMs:n,remainingUses:i,updatedAtMs:a};if(o.curve===`ecdsa`){let e=n<=Date.now()?`expired`:i===0?`exhausted`:null;if(e){await Gs(o,e,a);return}}await Ws(o)}async function Xs(e,t,n){let r=Ns(t,`delete`),i=String(e||``).trim();if(!i)return;let a=await Fs(i,r,`delete`);await Is(i,r),a&&n.deleteResolvedIdentity&&await X.deleteRestoreLease(a.storeKey)}async function Zs(e,t){let n=await X.collectAllRawSealedRecordEntries(),r=[],i=[];for(let a of n){let n=await Ds(a);if(n.kind!==`current`){ds({operation:`delete exact Ed25519 material`,classification:n});continue}let o=n.record;Bs(o,e)&&(r.push(a.primaryKey),t.deleteResolvedIdentity&&i.push(o.storeKey))}if(await X.deleteSealedRecords(r),t.deleteResolvedIdentity)for(let e of i)await X.deleteRestoreLease(e)}async function Qs(e){let t=e.preserveResolvedIdentity?{deleteResolvedIdentity:!1}:{deleteResolvedIdentity:!0,resolvedIdentityDeleteReason:`durable_record_deleted`};if(e.durableRecord.curve===`ed25519`){await Zs({kind:`ed25519_durable_material`,authMethod:e.durableRecord.authMethod,materialActivation:e.durableRecord.materialActivation},t);return}let n=Mo(e.durableRecord),r=await $s(e.durableRecord.thresholdSessionId,n);if(e.preserveResolvedIdentity&&e.durableRecord.curve===`ecdsa`&&r?.curve===`ecdsa`&&(e.deleteReason===`expired`||e.deleteReason===`exhausted`)){await Gs(r,e.deleteReason,Date.now());return}await Xs(e.durableRecord.thresholdSessionId,n,t)}async function $s(e,t){try{return await zs(e,t)}catch{return null}}async function ec(e){let t=Ns(e,`acquire restore lease`),n=String(e.thresholdSessionId||``).trim();if(!n)return null;let i=r(e.nowMs??Date.now())??Date.now(),a=Math.max(1,r(e.ttlMs??_s)??_s),o=m(e.ownerId)||vs(`restore-owner`);return await Fs(n,t,`acquire restore lease`)?await X.withRestoreLeaseTransaction(n,async e=>{let r=[];for(let t of e.entries){let e=ss(t.value);e?.storeKey&&!r.some(t=>t.storeKey===e.storeKey)&&r.push(e)}let s=r.find(e=>Ms(e,n,t))||null;if(!s)return e.abort(),null;let c=As(await e.getRawRestoreLease(s.storeKey));if(c&&c.expiresAtMs>i&&c.ownerId!==o)return e.abort(),null;let l=js({leaseKey:s.storeKey,ownerId:o,nowMs:i,ttlMs:a});return e.putRestoreLease(ys(l)),{...l,thresholdSessionId:n}}):null}async function tc(e){!e?.leaseKey||!e.ownerId||!e.attemptId||await X.deleteRestoreLeaseIf({leaseKey:e.leaseKey,shouldDelete:t=>{let n=As(t);return n?.ownerId===e.ownerId&&n.attemptId===e.attemptId}})}function nc(e){return String(e??``).trim()||null}function rc(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function ic(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:null}function ac(e){let t=D(e);return t?.length===2?[t[0],t[1]]:null}function oc(e){let t=e.ed25519Restore;switch(e.authMethod){case Te.passkey:{let e=nc(t.credentialIdB64u);return e?{kind:`passkey`,rpId:Sn(t.rpId),credentialIdB64u:e}:null}case Te.emailOtp:{if(!(`provider`in t))return null;let e=nc(t.providerSubjectId),n=nc(t.emailHashHex);return!e||!n?null:{kind:`email_otp`,provider:t.provider,providerSubjectId:e,emailHashHex:n}}}}function sc(e){switch(e.kind){case`passkey`:return{kind:Te.passkey,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u};case`email_otp`:return{kind:Te.emailOtp,providerSubjectId:e.providerSubjectId}}}function cc(e){let t=e.ed25519Restore,n=nc(e.thresholdSessionIds.ed25519),r=nc(e.relayerUrl),i=nc(t.relayerKeyId),a=rc(e.expiresAtMs),o=ic(e.remainingUses),s=Wt(t.signerSlot),c=ac(t.participantIds),l=N(t.runtimePolicyScope),u=l?F(l):null,d=nc(u?.signingRootVersion),f=ae(t.routerAbNormalSigning),p=oc(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:Ke(e.walletId),nearAccountId:je(t.nearAccountId),nearEd25519SigningKeyId:Vt(t.nearEd25519SigningKeyId),signerSlot:s,factor:p,auth:sc(p),thresholdSessionId:De.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 lc(e){let t;switch(e.runtime.factor.kind){case`passkey`:t=Ft({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=kt({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 uc(e.runtime.factor)}if(!t)throw Error(`[SigningEngine][near] sealed Ed25519 authority is invalid`);return await Lt({authority:t})}function uc(e){throw Error(`Unsupported Ed25519 factor: ${String(e)}`)}async function dc(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||!rr({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 lc({runtime:n,walletAuthMethodId:t.selectedAuthMethod.walletAuthMethodId}),r=await Lt({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 fc(e,t){switch(e.kind){case`voiceid`:return t.kind===`voiceid`&&e.walletAuthMethodId===t.walletAuthMethodId&&e.deviceKeyId===t.deviceKeyId;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 pc(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 mc(e,t){return fc(e.auth,t.auth)}async function hc(e,t){if(e.laneIdentity.auth.kind===`voiceid`)return{kind:`missing`};let n=(await t.listExactSealedSessionsForWallet({walletId:e.walletId,filter:{authMethod:e.laneIdentity.auth.kind,curve:`ed25519`}})).filter(t=>t.curve===`ed25519`&&pc({record:t,laneIdentity:e.laneIdentity}));if(n.length===0)return{kind:`missing`};if(n.length>1)return{kind:`conflict`};let r=cc(n[0]);return!r||!mc(r,e.laneIdentity)?{kind:`corrupt`}:{kind:`resolved`,runtime:r}}async function gc(e){return await hc(e,{listExactSealedSessionsForWallet:Hs})}async function _c(e,t){return yc(await vc(e,t))}async function vc(e,t){let n=await Promise.all([t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Te.passkey,curve:`ed25519`}}),t.listExactSealedSessionsForWallet({walletId:e,filter:{authMethod:Te.emailOtp,curve:`ed25519`}})]),r=[];for(let e of n)for(let t of e)t.curve===`ed25519`&&r.push(t);return r}function yc(e){if(e.length===0)return{kind:`missing`};if(e.length>1)return{kind:`conflict`};let t=cc(e[0]);return t?{kind:`resolved`,runtime:t}:{kind:`corrupt`}}async function bc(e){return await _c(e,{listExactSealedSessionsForWallet:Hs})}async function xc(e,t){let n=await vc(e.walletId,t),r=[];for(let t of n)t.ed25519Restore.nearAccountId===e.nearAccountId&&t.ed25519Restore.nearEd25519SigningKeyId===e.nearEd25519SigningKeyId&&r.push(t);return yc(r)}async function Sc(e){return await xc(e,{listExactSealedSessionsForWallet:Hs})}function Cc(e,t){let n=String(e).trim();if(!n)throw Error(`${t} is required for Ed25519 Wallet Session state`);return n}function wc(e,t){if(!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be positive for Ed25519 Wallet Session state`);return e}function Tc(e){let t=De.thresholdEd25519Session(Cc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=Cc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=Cc(e.relayerUrl,`relayerUrl`),i=Cc(e.providerSubjectId,`providerSubjectId`),a=wc(e.signerSlot,`signerSlot`),o=wc(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:lr({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 Ec(e){return Dc({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,relayerUrl:e.relayerUrl,authority:e.authority,signingWalletSession:e.signingWalletSession,auth:{kind:`passkey`,rpId:e.rpId,credentialIdB64u:Cc(e.credentialIdB64u,`credentialIdB64u`)}})}function Dc(e){let t=De.thresholdEd25519Session(Cc(e.signingWalletSession.thresholdSessionId,`thresholdSessionId`)),n=Cc(e.signingWalletSession.auth.walletSessionToken,`walletSessionToken`),r=Cc(e.relayerUrl,`relayerUrl`),i=wc(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:lr({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:i,auth:e.auth,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 Oc(e){let t=e.authorization.operationCredential.token,n=e.authorization.session.authorizationId,r=await lc({runtime:e.runtime,walletAuthMethodId:e.authorization.selectedAuthMethod.walletAuthMethodId}),i=await Lt({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=bo({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 Ec({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 Tc({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 kc(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 Ac(e){return e.authorization.capabilitySubjects.some(t=>t.kind===`sign`&&t.keyFamily===`ed25519`&&f(t.materialActivation,e.materialActivation))}function jc(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||!Ac({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=bo({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`voiceid`:return{...Dc({walletId:a.account.wallet.walletId,nearAccountId:a.account.nearAccountId,nearEd25519SigningKeyId:a.nearEd25519SigningKeyId,signerSlot:a.signerSlot,auth:t.signingLane.auth,relayerUrl:t.relayerUrl,authority:t.authority,signingWalletSession:s.value}),walletSessionAuthorization:n,walletSessionOperationCredential:e.operationCredential};case`passkey`:return{...Ec({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{...Tc({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 Mc(t.signingLane.auth)}}function Mc(e){throw Error(`Unknown Ed25519 signing lane auth: ${String(e)}`)}async function Nc(e){let t=e.state.signingLane.identity.signer.account.wallet.walletId,n=await mo({ports:e.ports,input:{walletId:t,authMethod:Ee(e.state.signingLane.auth),walletSessionId:e.state.walletSessionId,quotaId:e.state.quotaId,requiredSigningSubject:po(e.state.signingLane.identity),expiry:{kind:`unexpired`,nowMs:e.nowMs}}});return n.kind!==`resolved`||n.resolved.authMethod.walletAuthMethodId!==e.state.authority.walletAuthMethodId?null:jc({state:e.state,authorization:n.resolved.session,operationCredential:n.resolved.operationCredential,materialActivation:n.resolved.materialActivation,nowMs:e.nowMs})}function Pc(e){return jt(C({operation:`wallet_add_signer_activate_v2`,addSignerCeremonyId:e.addSignerCeremonyId,activationCorrelationId:e.activationCorrelationId,publicFacts:e.publicFacts}))}async function Fc(e){return A(await S(String(Pc(e))))}function Ic(e){let t;try{t=ze(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:Be(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 Lc(e){let t={};return wa()&&(t[`X-Seams-Benchmark-Diagnostics`]=`registration-flow`),e&&(t[un]=e.value),Object.keys(t).length>0?t:void 0}function Rc(e){let t=j(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 zc=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 Bc(e){switch(e.kind){case`owner_operations`:throw Error(`Owner registration has no reusable session`);case`issued`:return e.session;case`already_committed`:throw new zc(e.session);default:return J(e)}}function Vc(e){let t=e[0];if(t)for(let n of e.slice(1)){let e=Uc(t,n);if(e)throw Error(`ECDSA registration returned partitioned EVM-family wallet key material: ${e}`)}}function Hc(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 Uc(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 Wc(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||Je(r)!==Je(i))return!1}return!0}async function Gc(e){try{await e.context.signingEngine.closeRouterAbEcdsaRegistrationCeremony({kind:`close_router_ab_ecdsa_registration_ceremony_v1`,ceremonyId:e.ceremonyId})}catch{return}}function Kc(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 qc(e){return{canonicalRequest:Pc(e),requestDigest:ge(await Fc(e))}}async function Jc(e){try{return await Rn(e)}catch{return await Rn(e)}}async function Yc(e){return e.registrationTiming?await e.registrationTiming.measure(e.bucket,e.operation):await e.operation()}async function Xc(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=he(r);try{let a=await Yc({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 Yc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Un.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 Yc({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=Ic(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=xt({registrationRequestDigestB64u:s.registrationRequestDigestB64u,proofTranscriptDigestB64u:s.proofTranscriptDigestB64u,contextBinding32B64u:a.contextBinding32B64u,derivationClientSharePublicKey33B64u:a.clientSharePublicKey33B64u,clientShareRetryCounter:a.clientShareRetryCounter,participantId:1}),c=await qc({addSignerCeremonyId:r,activationCorrelationId:i,publicFacts:o}),u={bytes:Array.from(j(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:Nt(e.started.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:qt(e.started.prepare.ecdsaThresholdKeyId),signingRootId:wt(e.started.prepare.signingRootId),signingRootVersion:gt(e.started.prepare.signingRootVersion),runtimePolicyScope:e.started.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:Gt(a.clientSharePublicKey33B64u),participantIds:[Cn(e.started.prepare.participantIds[0]),Cn(e.started.prepare.participantIds[1])],relayerKeyId:Kt(e.started.prepare.relayerKeyId),bindingDigest:Zt(a.contextBinding32B64u),journalId:i,requestDigest:c.requestDigest,canonicalRequest:c.canonicalRequest,createdAt:me(new Date().toISOString())}});if(!d.ok)throw Error(`Canonical ECDSA activation persistence failed (${d.code}): ${d.message}`);l.journalId=d.journalId,l.response=await Yc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Jc.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:Rc(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=Kc({prepare:e.started.prepare,verified:u.clientBootstrap}),h=Ln({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 Gc({context:e.context,ceremonyId:r}),t}}async function Zc(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 Qc(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 J(e.tokens)}}function $c(e){let[t]=e.walletKeys;if(!t)throw Error(`ECDSA registration did not return wallet key material`);let n=Qc(e.session.registrationEstablishedSession);if(String(e.session.registrationEstablishedSession.walletId)!==t.walletId||n.thresholdSessionId!==e.session.activatedThresholdSessionId||n.keyHandle!==t.keyHandle||!el(n.runtimePolicyScope,e.session.clientBootstrap.runtimePolicyScope)||!Tt(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 el(e,t){return e.orgId===t.orgId&&e.projectId===t.projectId&&e.envId===t.envId&&e.signingRootVersion===t.signingRootVersion}async function tl(e,t){e.kind===`passkey`&&await Promise.allSettled([Promise.resolve().then(t),ji.initializeBundled()])}function nl(e){return Dt({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:String(e.credential.rawId||e.credential.id||``).trim()})}async function rl(e){if(!e.material)throw Error(`Email OTP registration ${e.operation} is missing enrollment material`);return await e.material}function il(e){let n=e.admissionRequest,r=t(n.scope.threshold_session_id);if(!r.ok)throw Error(`Ed25519 registration threshold-session identity is invalid`);let i=n.participant_ids,a=I(e.finalized.runtimePolicyScope);if(n.application_binding.wallet_id!==e.walletId||n.application_binding.near_ed25519_signing_key_id!==e.finalized.nearEd25519SigningKeyId||n.application_binding.key_creation_signer_slot!==e.finalized.signerSlot||i[0]!==e.finalized.participantIds[0]||i[1]!==e.finalized.participantIds[1]||!el(a,e.expectedRuntimePolicyScope)||n.application_binding.signing_root_id!==`${a.projectId}:${a.envId}`||n.scope.root_share_epoch!==a.signingRootVersion||n.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:r.value,signerSlot:e.finalized.signerSlot,signingRootId:n.application_binding.signing_root_id,signingRootVersion:n.scope.root_share_epoch,signingWorkerId:n.scope.signing_worker_id},stableServerScope:{relayerKeyId:e.finalized.relayerKeyId,participantIds:e.finalized.participantIds,runtimePolicyScope:a,routerAbNormalSigning:e.finalized.routerAbNormalSigning}}}function al(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 J(e.tokens)}}async function ol(e){let t=al(e.registrationEstablishedSession);if(t.nearAccountId!==String(e.nearAccountId)||t.nearEd25519SigningKeyId!==String(e.nearEd25519SigningKeyId)||t.thresholdSessionId!==String(e.thresholdSessionId)||!el(t.runtimePolicyScope,e.runtimePolicyScope))throw Error(`Registration-established Email OTP Ed25519 session changed signer identity`);let n=F(t.runtimePolicyScope),r=n.signingRootVersion;if(!r)throw Error(`Registration-established Ed25519 session is missing a signing-root version`);let i=bo({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 Lt({authority:e.emailOtpAuthContext.authority});return Tc({walletId:e.walletId,nearAccountId:je(e.nearAccountId),nearEd25519SigningKeyId:Bt(e.nearEd25519SigningKeyId),providerSubjectId:ar(e.emailOtpAuthContext),signerSlot:e.signerSlot,relayerUrl:e.relayerUrl,authority:a,signingWalletSession:i.value})}function sl(e){if(e.authMethod.kind!==`passkey`)throw Error(`Ed25519 Yao registration requires a passkey registration intent`);return{version:e.version,completion:e.completion,walletId:e.walletId,authMethod:e.authMethod,signerSelection:e.signerSelection,foundingWalletAuthMethodId:e.foundingWalletAuthMethodId,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},nonceB64u:e.nonceB64u}}function cl(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 ll(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 ul(e,t){let n=await new wi(t).send({kind:`admit`,path:ct,body:e.admissionRequest});if(!n.ok)throw Error(n.message);let r=dt(n.value);if(!r.ok)throw Error(r.message);return r.value}function dl(e){let t=al(e.session);return{thresholdSessionId:String(t.thresholdSessionId),prfFirstB64u:e.prfFirstB64u,expiresAtMs:e.session.expiresAtMs,remainingUses:e.session.remainingUses,diagnostics:{recordDuration:Aa.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:Sa({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 fl(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 pl(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 ml(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 hl(e,t,n){let r=t.registrationEstablishedSession.session,i=ml(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 gl(e,t,n){let r=e.ecdsa_activation.public_identity;return yt({registrationRequestDigestB64u:t.publicCapability.registration_request_digest_b64u,proofTranscriptDigestB64u:A(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 _l(e,t){return e.derivationClientSharePublicKey33B64u===t.derivationClientSharePublicKey33B64u&&e.relayerPublicKey33B64u===t.relayerVerifyingShareB64u&&e.groupPublicKey33B64u===t.thresholdEcdsaPublicKeyB64u&&e.ethereumAddress===t.thresholdOwnerAddress.toLowerCase()}function vl(e,t){return e.server_public_key33_b64u===t.relayerVerifyingShareB64u&&e.threshold_public_key33_b64u===t.thresholdEcdsaPublicKeyB64u&&Sl(e.ethereum_address20_b64u)===t.thresholdOwnerAddress&&e.server_share_retry_counter===t.relayerShareRetryCounter}function yl(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 bl(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 xl(e){let t=e.ecdsa.walletKeys[0];if(!t)throw Error(`pending ECDSA activation returned no wallet keys`);return Vc(e.ecdsa.walletKeys),[t,...e.ecdsa.walletKeys.slice(1)]}function Sl(e){let t=j(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 Cl(e,t,n){if(!hl(e,t,n))throw Error(`pending ECDSA activation projection mismatch`);on(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function wl(e){return e.ok===!0&&e.kind===`evm_family_ecdsa`&&e.registrationEstablishedSession.kind===`already_committed`}async function Tl(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=kt(t.authority),r=await y(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 El(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||A(Uint8Array.from(r.activation_request_digest.bytes))!==e.localMaterial.ecdsa.activationRequestDigestB64u||!gl(r,n,o)||!_l(t.ecdsa.bootstrap.publicIdentity,n)||i.context.application_binding_digest_b64u!==t.ecdsa.bootstrap.applicationBindingDigestB64u||!vl(a,n))throw Error(`pending ECDSA activation facts mismatch`);if(!yl(t.ecdsa.bootstrap,n))throw Error(`pending ECDSA bootstrap changed committed key identity`)}function Dl(e){let t=ml(e).ecdsa,n=e.ecdsa.activation.ecdsa_activation;if(!f(t.materialActivation,bt(n.material_activation))||!Tt(t.routerAbEcdsaDerivationNormalSigning,e.ecdsa.bootstrap.routerAbEcdsaDerivationNormalSigning))throw Error(`pending ECDSA activation facts do not match the committed projection`)}async function Ol(e){let t=e.response;if(!wl(t))throw Error(t.ok?`pending ECDSA activation replay did not return a committed projection`:`pending ECDSA activation replay failed`);let n=xl(t)[0];if(Cl(e.pending,t,n),await Tl(e.pending,t),El(e.pending,t,n),Dl(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}async function kl(e){let t=new cn,n=bt(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 Jn(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(!It(i.activation.serverActivation.serverActivationReceipt.protocolReceipt,e.activationReceipt)||!vt(a.roleLocalPublicFacts.publicCapability,e.publicCapability)||!xn(i.signer.scope,Xt({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||!bn(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 Al(e){let t=e[0];if(!t)throw Error(`ECDSA registration finalization returned no wallet keys`);return[t,...e.slice(1)]}function jl(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 Ml(e){let t=Al(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 tr({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=kt(e.response.authority);if(!n)throw Error(`ECDSA Email OTP registration authority is invalid`);return await tr({kind:`email_otp`,walletId:e.pending.walletId,email:e.pending.auth.email,registrationAuthorityId:e.pending.auth.registrationAuthorityId,authority:n,walletKeys:t})}function Nl(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 Pl(e){let t=await e.ports.activateWalletRegistration(bl(e.relayerUrl,e.pending)),n=await Ol({pending:e.pending,response:t}),r=xl(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 Lt({authority:n.authority}),c=await kl({authority:s,chainTargets:jl(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:ml(n).ecdsa.runtimePolicyScope,readyStateBlobB64u:a.readyStateBlobB64u,publicFacts:a.publicFacts}),l={kind:`ecdsa_role_local_worker_handle_v1`,materialHandle:Jt(c.roleLocalMaterialRef.durableMaterialRef),bindingDigest:c.roleLocalMaterialRef.bindingDigest,durableMaterialRef:c.roleLocalMaterialRef.durableMaterialRef},u=await e.signingSurface.finalizeWalletRegistrationEcdsaSessions({walletId:String(e.pending.walletId),session:{chainTargets:jl(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 Ml({pending:e.pending,response:n,walletKeys:u});if(await e.ports.publishPendingWalletRegistrationCommit(Nl({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=fr(a.credential,`Pending NEAR registration continuation`),n=eh({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:ur(a.credential),prfFirstB64u:t},ownedFactorSecret:j(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 Fl(e,t,n){e?.(Qt({flowId:`unlock:${t}`,accountId:t,...n}))}async function Il(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}),Fl(a,r,{phase:en.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 Ll(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?.(ve(r)),Fl(i,n,{phase:l?en.CANCELLED:en.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}}function Rl(){}function zl(e){if(e.keySet!==`near_ed25519_v1`)throw Error(`The custody worker began an EVM run for a NEAR request`);return e}function Bl(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker began a NEAR run for an EVM request`);return e}function Vl(e){if(e.keySet!==`evm_family_ecdsa_v1`)throw Error(`The custody worker completed a NEAR run for an EVM request`);return e}function Hl(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 Wl(e)}}async function Ul(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 Wl(e)}}function Wl(e){throw Error(`Unsupported wallet custody origin: ${String(e)}`)}function Gl(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 Kl(e,t,n){if(wa())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 ql(e){let t=e.ceremonyId||M(`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=zl(await e.runStep(`beginWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`near_ed25519_v1`,custody:Hl(n),protocolInputsJson:r.protocolInputsJson})).yaoExecuteRequestJson;if(Kl(t,`begin`,a),i=!0,r.beforeRouterRound){a=performance.now();let n=await e.runStep(`checkpointNearRegistration`,{ceremonyId:t});Kl(t,`checkpoint`,a),await r.beforeRouterRound(n.checkpointJson)}a=performance.now();let s=await r.runRouterRound(o);Kl(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}),Kl(t,`complete`,a),await r.afterRouterRoundCompleted?.(s),a=performance.now();let c=await e.runStep(`finishWalletCustodyKeySetRun`,{ceremonyId:t,finish:await Ul(n)});return Kl(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=Bl(a);await r.beforeRelayerRound();let s=await r.runRelayerRound({contextBinding32B64u:o.ecdsaContextBinding32B64u,clientSharePublicKey33B64u:o.ecdsaClientSharePublicKey33B64u,clientShareRetryCounter:o.ecdsaClientShareRetryCounter,preActivationCommitPayload:o.preActivationCommitPayload}),c=Vl(await e.runStep(`completeWalletCustodyKeySetRun`,{ceremonyId:t,keySet:`evm_family_ecdsa_v1`,protocolResultJson:s}));return Gl(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(Rl),n}}async function Jl(e){let t=gr(),n=null;try{let r=JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:A(e)}))),i=await ql({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=cu(r),r}}});if(!n)throw Error(`the NEAR custody ceremony produced no activation session id`);let a=await su(i,t);return{recoveryCodes:t.codes,activationReference:{kind:`router_ab_ed25519_yao_activation_reference_v1`,lifecycle_id:e.registrationCeremonyId,session_id:n},commitPayload:ou(a),localMaterial:i.ed25519LocalMaterialB64u&&i.ed25519LocalMaterialNonceB64u&&i.ed25519ApplicationBindingDigestB64u?{b64u:i.ed25519LocalMaterialB64u,nonceB64u:i.ed25519LocalMaterialNonceB64u,applicationBindingDigestB64u:i.ed25519ApplicationBindingDigestB64u}:null}}finally{t&&mr(t),t=null}}function Yl(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 Xl(e){let t=gr(),n=null,r=null;try{let i=t;if(!i)throw Error(`recovery codes were not issued`);let a=await ql({runStep:e.runStep,custody:{origin:`establish`,walletId:e.walletId,factorJson:e.factorJson,factorSecret:e.factorSecret,recoveryCodesJson:JSON.stringify(t.codeBytes.map(e=>({codeBytesB64u:A(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=Le(await su(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&&mr(t),t=null}}async function Zl(e){let t=null,n=null,r=await ql({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 Ql(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 $l(e.factorReplacement)}}function $l(e){throw Error(`unsupported recovery factor replacement: ${String(e)}`)}async function eu(e){if(await iu({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 ql({runStep:e.runStep,custody:Ql(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 tu(e){let t=await iu({walletId:e.walletId,evmFamilySigningKeySlotId:e.evmFamilySigningKeySlotId,clientRootPublicKey33B64u:e.registeredClientRootPublicKey33B64u}),n=await ql({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 nu(e,t){e.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255)}function ru(e,t,n){let r=new TextEncoder().encode(t);nu(e,r.length),e.push(...r),nu(e,n.length),e.push(...n)}async function iu(e){let t=String(e.walletId||``).trim(),n=String(e.evmFamilySigningKeySlotId||``).trim(),r=j(e.clientRootPublicKey33B64u);if(!t||!n||r.length!==33)throw Error(`EVM custody continuity identity is invalid`);let i=[];return ru(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/evm-family-ecdsa/v1`)),ru(i,`walletId`,new TextEncoder().encode(t)),ru(i,`evmFamilySigningKeySlotId`,new TextEncoder().encode(n)),ru(i,`clientRootPublicKey33`,r),A(await x(Uint8Array.from(i)))}async function au(e){let t=String(e.walletId||``).trim(),n=String(e.nearEd25519SigningKeyId||``).trim(),r=j(e.registeredPublicKeyB64u);if(!t||!n||r.length!==32)throw Error(`NEAR custody continuity identity is invalid`);let i=[];return ru(i,`context`,new TextEncoder().encode(`seams/wallet-custody/key-set-manifest/near-ed25519/v1`)),ru(i,`walletId`,new TextEncoder().encode(t)),ru(i,`nearEd25519SigningKeyId`,new TextEncoder().encode(n)),ru(i,`registeredPublicKey`,r),A(await x(Uint8Array.from(i)))}function ou(e){let{ed25519LocalMaterialB64u:t,ed25519LocalMaterialNonceB64u:n,ed25519ApplicationBindingDigestB64u:r,ecdsaReadyStateBlobB64u:i,recoveryReplacementEnvelope:a,...o}=e;return o}async function su(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 hr(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 cu(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 lu(e){if(await au({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 ql({runStep:e.runStep,custody:Ql(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 uu(e){return await fu(e,e.registrationCeremonyId,void 0,`registration join`)}async function du(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 fu({...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 fu(e,t,n,r,i){let a=null,o=await ql({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=cu(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:ou(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 pu(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(!Se(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 mu=class e extends Error{kind=`email_otp_signing_session_auth_state_error`;failure;constructor(t){super(hu(t)),this.name=`EmailOtpSigningSessionAuthStateError`,this.failure=t,Object.setPrototypeOf(this,e.prototype)}};function hu(e){return`Email OTP ${e.expectedCurve} signing-session auth lane is unavailable at ${e.source}; unlock wallet again`}function gu(e){throw new mu(e)}function _u(e){return e.freshRouteFamily===`registration`?pu({routeFamily:`registration`,operation:xe}):pu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function vu(e){return e?.kind!==`signing_session`&&gu({kind:`auth_lane_missing`,source:`route_plan`,expectedCurve:`unknown`}),e}function yu(e){return pu({routeFamily:`signing_session`,authLane:e.authLane,operation:e.operation})}function bu(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 xu(e){if(e.routeFamily===`signing_session`)return bu(e.authLane)}async function Su(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 Cu(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:be,material:e.material},onEvent:e.base.onProgress}})}async function wu(e){let t=await Cu({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 Tu(e){let t=await Cu({base:e,material:{kind:`ed25519_yao_recovery`,providerSubject:e.providerSubject,nearAccountId:e.nearAccountId,expectedOperationalPublicKey:e.expectedOperationalPublicKey,expectedThresholdSessionId:e.expectedThresholdSessionId,walletCustodyEd25519Material:e.walletCustodyEd25519Material,ed25519YaoRecovery:{kind:ft,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 Eu(e){let t=await Cu({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:ft,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 Du(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 Ou(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function ku(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 Au(e){return e.kind===`sign`&&e.keyFamily===`ed25519`}function ju(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(w(e.walletId,`session.walletId`)!==n.walletId||w(e.nearAccountId,`session.nearAccountId`)!==n.nearAccountId||w(e.nearEd25519SigningKeyId,`session.nearEd25519SigningKeyId`)!==n.nearEd25519SigningKeyId)throw Error(`Yao recovery session identity does not match the verified passkey`);let o=I(h(e.runtimePolicyScope,`session.runtimePolicyScope`)),s=ae(e.routerAbNormalSigning);if(!s)throw Error(`Yao recovery session signing state is invalid`);let c=fe(e.walletSessionId),l=ue(e.quotaId);if(!c.ok||!l.ok)throw Error(`Yao recovery Wallet Session identity is invalid`);let u=Ou(e.expiresAtMs,`session.expiresAtMs`),d=Ou(e.remainingUses,`session.remainingUses`),p=r.capabilitySubjects.find(Au);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||!p||!f(p.materialActivation,a.materialActivation))throw Error(`Yao recovery session does not match the exact Wallet Session`);return{thresholdSessionId:w(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 Mu(e){let t=e.capability,n=e.session,r=F(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]||!te(n.runtimePolicyScope,t.runtimePolicyScope)||n.runtimePolicyScope.signingRootVersion!==t.lifecycle.rootShareEpoch||t.applicationBinding.signing_root_id!==r.signingRootId||e.operationalPublicKey!==`ed25519:${ke(Uint8Array.from(t.registeredPublicKey))}`)throw Error(`Yao recovery response does not preserve the registered wallet identity`)}function Nu(e){if(Mu(e),e.capability.lifecycle.thresholdSessionId!==e.session.thresholdSessionId)throw Error(`Yao recovery response does not preserve the threshold material lifecycle`)}function Pu(e,t){if(Mu(e),!f(e.capability.materialActivation,t))throw Error(`Yao warm recovery response does not preserve exact material activation`)}function Fu(e){return`operationCredential`in e?e.operationCredential.token:e.walletSessionToken}function Iu(e){let t=h(e,`sync-account response`);if(t.ok!==!0||t.verified!==!0)throw Error(`sync-account response is not verified`);let r=Ut(w(t.walletId,`walletId`)),i=je(w(t.nearAccountId,`nearAccountId`)),a=w(t.nearEd25519SigningKeyId,`nearEd25519SigningKeyId`),s=h(t.thresholdEd25519,`thresholdEd25519`),c=ku(s.participantIds),l=h(t.ed25519YaoRecovery,`ed25519YaoRecovery`);if(l.kind!==`router_ab_ed25519_yao_sync_recovery_v1`)throw Error(`sync-account recovery kind is invalid`);let u=At(l.authorityRef);if(!u||String(u.walletId)!==String(r))throw Error(`sync-account recovery authority is invalid`);let d=n(t.walletAuthMethodId),f=o(t.walletAuthorityId),p=ot(t.foundingAuthority),m=zt(t.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 g=h(t.walletCustody,`walletCustody`);if(g.kind!==`wallet_custody_sync_bootstrap_v1`)throw Error(`walletCustody kind is invalid`);let _=On(l.capability),v=re(t.walletSession),y=ne(t.operationCredential),b={authority:u,walletAuthMethodId:d.value,walletAuthorityId:f.value,foundingAuthority:p.value,foundingAuthMethod:m,walletId:r,nearAccountId:i,nearEd25519SigningKeyId:a,signerSlot:Ou(t.signerSlot,`signerSlot`),operationalPublicKey:w(t.publicKey,`publicKey`),relayerKeyId:w(s.relayerKeyId,`thresholdEd25519.relayerKeyId`),keyVersion:w(s.keyVersion,`thresholdEd25519.keyVersion`),credentialIdB64u:w(t.credentialIdB64u,`credentialIdB64u`),credentialPublicKeyB64u:w(t.credentialPublicKeyB64u,`credentialPublicKeyB64u`),session:ju(h(s.session,`thresholdEd25519.session`),c,{walletId:String(r),nearAccountId:String(i),nearEd25519SigningKeyId:a},v,y,{walletAuthorityId:f.value,walletAuthMethodId:d.value,authorityDigestB64u:p.value.authorityDigestB64u,authorityRevocationEpoch:p.value.revocationEpoch,materialActivation:_.materialActivation}),capability:_,walletSession:v,operationCredential:y,walletCustody:{envelope:ze(g.envelope),storeVersion:w(g.storeVersion,`walletCustody.storeVersion`)}};return Nu(b),b}function Lu(e){let t=e.parsed,n=t.session,r=F(n.runtimePolicyScope),i=bo({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:Fu(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 Ec({walletId:Ke(t.walletId),nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:Vt(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,rpId:Sn(e.rpId),credentialIdB64u:t.credentialIdB64u,relayerUrl:e.relayerUrl,authority:t.authority,signingWalletSession:i.value})}function Ru(e){if(!v(e)||e.kind!==`wallet_custody_passkey_login_v1`)throw Error(`Passkey wallet unlock returned invalid custody data`);if(!v(e.ed25519))throw Error(`Passkey wallet unlock omitted Ed25519 custody continuity`);if(e.ed25519.kind===`absent`)return{kind:`wallet_custody_passkey_login_v1`,envelope:ze(e.envelope),storeVersion:w(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:ze(e.envelope),storeVersion:w(e.storeVersion,`walletCustody.storeVersion`),ed25519:{kind:`active`,nearAccountId:w(e.ed25519.nearAccountId,`walletCustody.ed25519.nearAccountId`),nearEd25519SigningKeyId:w(e.ed25519.nearEd25519SigningKeyId,`walletCustody.ed25519.nearEd25519SigningKeyId`),signerSlot:t,publicKey:w(e.ed25519.publicKey,`walletCustody.ed25519.publicKey`),relayerKeyId:w(e.ed25519.relayerKeyId,`walletCustody.ed25519.relayerKeyId`),participantIds:[Number(n[0]),Number(n[1])],capability:On(e.ed25519.capability)}}}function zu(e){if(!v(e))throw Error(`ECDSA custody chain target is invalid`);let t=w(e.kind,`ecdsaCustody.chainTarget.kind`),n=Number(e.chainId),r=w(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 Bu(e){if(!v(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(!v(n)||!v(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:zu(n.chainTarget),walletKey:{walletId:w(e.walletId,`ecdsaCustody.walletKey.walletId`),keyHandle:w(e.keyHandle,`ecdsaCustody.walletKey.keyHandle`),ecdsaThresholdKeyId:w(e.ecdsaThresholdKeyId,`ecdsaCustody.walletKey.ecdsaThresholdKeyId`),signingRootId:w(e.signingRootId,`ecdsaCustody.walletKey.signingRootId`),signingRootVersion:w(e.signingRootVersion,`ecdsaCustody.walletKey.signingRootVersion`),relayerKeyId:w(e.relayerKeyId,`ecdsaCustody.walletKey.relayerKeyId`),contextBinding32B64u:w(e.contextBinding32B64u,`ecdsaCustody.walletKey.contextBinding32B64u`),derivationClientSharePublicKey33B64u:w(e.derivationClientSharePublicKey33B64u,`ecdsaCustody.walletKey.derivationClientSharePublicKey33B64u`),participantIds:[1,2],publicCapability:Ct(e.publicCapability)},activationReceipt:mt(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 Vu(e){let t=e.raw.sessionKind;if(t===`issued_exact_wallet_session`){let n=ne(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(ne(e.unlockCredential).walletSessionId!==e.walletSessionId)throw Error(`Wallet unlock Ed25519 session reuses another Wallet Session`);return{sessionKind:t}}function Hu(e,n){if(e===null)return null;if(!v(e))throw Error(`Wallet unlock returned invalid Ed25519 session data`);let r=t(e.thresholdSessionId),i=pe(e.authorizationId),a=fe(e.walletSessionId),o=ue(e.quotaId),s=Number(e.expiresAtMs),c=Number(e.remainingUses),l=I(e.runtimePolicyScope),u=oe(e.routerAbNormalSigning),d=e.participantIds;if(!r.ok||!i.ok||!a.ok||!o.ok||!Number.isSafeInteger(s)||s<=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=Vu({raw:e,walletSessionId:a.value,unlockCredential:n});return{walletId:w(e.walletId,`ed25519Session.walletId`),nearAccountId:w(e.nearAccountId,`ed25519Session.nearAccountId`),nearEd25519SigningKeyId:w(e.nearEd25519SigningKeyId,`ed25519Session.nearEd25519SigningKeyId`),relayerKeyId:w(e.relayerKeyId,`ed25519Session.relayerKeyId`),participantIds:[Number(d[0]),Number(d[1])],thresholdSessionId:r.value,authorizationId:i.value,walletSessionId:a.value,quotaId:o.value,expiresAtMs:s,remainingUses:c,runtimePolicyScope:l,routerAbNormalSigning:u,...f}}function Uu(e){let t=e.authorization.record,n=bt(e.ecdsaSession.public_capability.material_activation),r=0;for(let e of t.capabilitySubjects)e.kind===`sign`&&e.keyFamily===`ecdsa_secp256k1`&&f(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 Wu(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 Gu(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:re(e.data.walletSession),operationCredential:ne(e.data.operationCredential)};return Wu({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 Wu({ed25519Session:e.ed25519Session,authorization:i}),i}async function Ku(e,t){let n=await Gu(e,t);return Uu({ed25519Session:e.ed25519Session,ecdsaSession:e.ecdsaSession,authorization:n}),n}function qu(e){let t=Bn(e)??Hn(e);return t?{success:!1,kind:`already_committed`,code:t.code,message:t.message,next:t.next,committed:t.committed}:null}async function Ju(e,t,n){try{if(t.type!==`passkey_assertion`)throw Error(`Passkey wallet unlock requires a passkey assertion`);let r=w(t.challengeId,`challengeId`),i=t.webauthn_authentication,a=String(t.expected_origin||``).trim(),o={unlockBackend:`passkey`,challengeId:r,...`walletId`in t&&t.walletId?{walletId:t.walletId}:{},webauthn_authentication:Xn(i),ed25519SessionRequest:t.ed25519SessionRequest,...a?{expected_origin:a}:{},...t.ecdsaSessionPolicy?{ecdsaSessionPolicy:ht(t.ecdsaSessionPolicy)}:{}},c=s(e,`/wallet/unlock/verify`),l=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(o)}),u=await l.json().catch(()=>({})),d=v(u)?u:{};if(!l.ok)return qu(d)||{success:!1,error:typeof d.message==`string`?d.message:`HTTP ${l.status}`};if(d.ok!==!0)return qu(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=Hu(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=Ru(d.walletCustody),h,g,_,y;if(f){if(d.ecdsaSession===void 0)throw Error(`Wallet unlock omitted the requested ECDSA Wallet Session activation`);if(h=v(d.ecdsaSession)&&d.ecdsaSession.kind===`router_ab_ecdsa_credential_free_session_activated_v1`?Ot(d.ecdsaSession):Mt(d.ecdsaSession),d.ecdsaActivationReceipt===void 0||d.ecdsaCustody===void 0)throw Error(`Wallet unlock omitted ECDSA custody continuity`);if(_=mt(d.ecdsaActivationReceipt),y=Bu(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 Ku({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 Gu({relayServerUrl:e,data:d,ed25519Session:p},n));if(h&&_&&y&&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:y,ed25519Session:p,walletCustody:m,walletSessionAuthorization:g}}return{success:!0,ecdsaSession:h,ecdsaActivationReceipt:_,ecdsaCustody:y,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:ye(e)||`Failed to verify wallet unlock`}}}async function Yu(e,t){try{let n=w(t.challengeId,`challengeId`),r=String(t.expected_origin||``).trim(),i={unlockBackend:`passkey`,challengeId:n,webauthn_authentication:Xn(t.webauthn_authentication),ed25519SessionRequest:t.ed25519SessionRequest,...r?{expected_origin:r}:{}},a=await fetch(s(e,`/wallet/unlock/verify`),{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`omit`,body:JSON.stringify(i)}),o=await a.json().catch(()=>({})),c=v(o)?o:{};if(!a.ok||c.ok!==!0)return qu(c)||{success:!1,error:typeof c.message==`string`?c.message:`Wallet Session unlock failed (HTTP ${a.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=Hu(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:re(c.walletSession),operationCredential:ne(c.operationCredential),ed25519Session:l}}catch(e){return{success:!1,error:ye(e)||`Failed to verify linked passkey Wallet Session`}}}function Xu(e){let t=c(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a session id`);return t.value}function Zu(e){let t=de(e);if(!t.ok)throw Error(`ECDSA registration recovery could not create a Wallet Session mint id`);return t.value}function Qu(e){return ht({kind:`router_ab_ecdsa_post_registration_session_activation_policy_v1`,key_handle:e.keyHandle,session_policy:{threshold_session_id:Xu(_r(`threshold-ecdsa-registration-recovery`)),wallet_session_mint_id:Zu(_r(`wallet-session-mint`)),ttl_ms:e.sessionPolicy.ttlMs,remaining_uses:e.sessionPolicy.unlockRemainingUses,runtime_policy_scope:e.runtimePolicyScope}})}async function $u(e){let t=await fetch(s(e.relayerUrl,`/wallet/unlock/challenge`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unlockBackend:`passkey`,userId:e.walletId,rpId:e.rpId})}),n=h(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:T(n.challengeId,`Passkey unlock challenge ID`),challengeB64u:T(n.challengeB64u,`Passkey unlock challenge`)}}function ed(e){return e===`ble`||e===`hybrid`||e===`internal`||e===`nfc`||e===`usb`}function td(e,t){return{id:e,type:`public-key`,transports:t.filter(ed)}}function nd(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 rd(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=Je(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=Je(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)||!It(n.activationReceipt,e.response.ecdsa.activation))throw Error(`ECDSA registration unlock returned different custody continuity`)}}function id(e){new Uint8Array(e).fill(0)}async function ad(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`);Fl(e.onEvent,String(e.pending.walletId),{phase:en.STEP_03_PASSKEY_CHALLENGE_STARTED,status:`running`,authMethod:`passkey`});let r=await $u({relayerUrl:e.relayerUrl,walletId:String(e.pending.walletId),rpId:e.pending.auth.rpId});Fl(e.onEvent,String(e.pending.walletId),{phase:en.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:[td(e.pending.auth.credentialIdB64u,e.pending.auth.transports)],includeSecondPrfOutput:!0});if(ur(i)!==e.pending.auth.credentialIdB64u)throw Error(`ECDSA registration unlock returned a different Passkey credential`);Fl(e.onEvent,String(e.pending.walletId),{phase:en.STEP_03_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let a=fr(i,`ECDSA registration recovery`),o=await Ju(e.relayerUrl,{type:`passkey_assertion`,challengeId:r.challengeId,walletId:String(e.pending.walletId),webauthn_authentication:i,ed25519SessionRequest:{kind:`not_requested`},expected_origin:n,ecdsaSessionPolicy:Qu({keyHandle:t.keyHandle,sessionPolicy:e.sessionPolicy,runtimePolicyScope:ml(e.response).ecdsa.runtimePolicyScope})},new Tn);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`);nd({pending:e.pending,response:e.response,session:o.ecdsaSession,walletKey:t}),rd({pending:e.pending,response:e.response,walletKeys:e.walletKeys,signers:o.ecdsaCustody.signers});let s=Uint8Array.from(j(a)).buffer;try{let n=await e.signingSurface.rejoinWalletCustodyEvmFamilyKeySet({walletId:String(e.pending.walletId),custodyJson:Yl(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{id(s)}}async function od(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=ml(e.response).ecdsa.runtimePolicyScope,r=await wu({walletSession:{walletId:Ke(e.pending.walletId),walletSessionUserId:String(e.pending.walletId)},authoritySelector:{kind:`wallet_auth_method`,walletAuthMethodId:e.pending.walletAuthMethodId},relayUrl:e.relayerUrl,groupId:z,routePlan:_u({freshRouteFamily:`login`,operation:Ce}),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:Qu({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 nd({pending:e.pending,response:e.response,session:r.ecdsaSession,walletKey:t}),rd({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 sd(e){switch(e.exactMethod.kind){case`passkey`:return await ad({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 od({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 cd={listPendingWalletRegistrationCommits:ld,completeWalletRegistrationNearProvisioning:Vn,publishPendingWalletRegistrationCommit:ud};async function ld(){return await V.initialize(),await V.listPendingWalletRegistrationCommits()}async function ud(e){return await V.publishPendingWalletRegistrationCommit(e)}function dd(e){return e instanceof Error?e:Error(String(e||`pending registration replay failed`))}function fd(e){return e.operation===`near_provisioning`&&e.phase===`joined`}function pd(e,t){let n=e.localMaterial.ed25519.metadata,r=e.localMaterial.ed25519.localMaterial;return{binding:{kind:Zn,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 md(e){let t=j(e.localMaterial.ed25519.metadata.registeredPublicKeyB64u);if(t.length!==32)throw Error(`pending registration has an invalid Ed25519 registered public key`);return`ed25519:${ke(t)}`}function hd(e,t,n){let r=e.localMaterial.ed25519.metadata,i=e.localMaterial.custodyCommit;if(e.auth.kind===`passkey`){if(cl({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 ll({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`);on(e,{operation:e.operation,walletId:t.walletId,walletAuthMethodId:t.foundingAuthMethod.walletAuthMethodId,authority:t.authority})}function gd(e,t){let n=t.registrationEstablishedSession;if(n.kind===`owner_operations`){if(n.walletId!==e.walletId||e.signerPlanKind!==`near_ed25519`)throw Error(`Owner registration replay identity mismatch`);return}let r=n.session,i=r.tokens.kind===`near_ed25519`||r.tokens.kind===`near_ed25519_and_evm_family_ecdsa`?r.tokens.ed25519:null,a=e.localMaterial.ed25519.metadata;if(r.walletId!==e.walletId||!i||i.nearAccountId!==t.ed25519.nearAccountId||i.nearEd25519SigningKeyId!==t.ed25519.nearEd25519SigningKeyId||i.routerAbNormalSigning.signingWorkerId!==a.signingWorkerId||!f(i.materialActivation,a.materialActivation))throw Error(`pending registration does not match the committed Wallet Session projection`)}function _d(e,t){gd(e,t);let n=t.registrationEstablishedSession;if(n.kind!==`owner_operations`){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 vd(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 hd(e,t,md(e)),t}function yd(e,t){let n=vd(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 _d(e,n),n}async function bd(e,t){let n=md(e),r={walletId:e.walletId,nearAccountId:je(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:pd(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 Qn({...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=kt(t.authority);if(!i)throw Error(`pending Email OTP registration replay returned an invalid authority`);return await er({...r,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:i})}function xd(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===`owner_operations`?{kind:`owner_operations`}: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 Sd(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 Cd(e,t){return{relayerUrl:e,registrationCeremonyId:t.registrationCeremonyId,signedSetup:t.signedSetup,idempotencyKey:t.idempotencyKey,ed25519:{activationReference:t.localMaterial.ed25519.activationReference},auth:Sd(t),walletCustodyCommit:t.localMaterial.custodyCommit}}async function wd(e){let t=Cd(e.relayerUrl,e.pending),n=await e.ports.completeWalletRegistrationNearProvisioning(t);return yd(e.pending,n)}async function Td(e){let t=await Vn({...Cd(e.relayerUrl,e.pending),headers:E(e.operationCredential)}),n=yd(e.pending,t);if(n.registrationEstablishedSession.kind===`owner_operations`)throw Error(`Owner registration has no reusable session to restore`);let 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=at({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(/\/$/,``)}${et}`,{method:`POST`,headers:{...E(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=On(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||A(Uint8Array.from(c.registeredPublicKey))!==l.registeredPublicKeyB64u||!f(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:ha({material:pd(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:A(Uint8Array.from(u.activationTranscript)),activationCapabilityBindingB64u:A(Uint8Array.from(c.activeCapabilityBinding))}})},admissionRequest:u.admissionRequest,admissionReceipt:u.admissionReceipt}}async function Ed(e){let t=await wd(e),n=await bd(e.pending,t);return await e.ports.publishPendingWalletRegistrationCommit(xd(e.pending,t,n)),{kind:`published`,registrationCeremonyId:e.pending.registrationCeremonyId}}async function Dd(e){let t=e.ports||cd,n=await t.listPendingWalletRegistrationCommits(),r=[];for(let i of n){if(fl(i)||pl(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(fd(i))try{r.push(await Ed({relayerUrl:e.relayerUrl,pending:i,ports:t}))}catch(e){r.push({kind:`failed`,registrationCeremonyId:i.registrationCeremonyId,error:dd(e)})}}return r}const Od={activateWalletRegistration:Nn,publishPendingWalletRegistrationCommit:ud,unlockPendingEcdsaRegistration:sd};async function kd(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(!fl(t)&&!pl(t))throw Error(`pending registration commit is not ECDSA-enabled`);return t}async function Ad(e){if(e.pending.auth.kind!==e.exactMethod.kind)throw Error(`pending registration requires its exact authentication method`);return await Pl({relayerUrl:e.relayerUrl,sessionPolicy:e.sessionPolicy,pending:e.pending,exactMethod:e.exactMethod,signingSurface:e.signingSurface,ports:Od,nearContext:e.nearContext,nearCompletion:e.nearCompletion,onEvent:e.onEvent})}const jd=[1,2];function Md(e){let t=[],n=new Set;for(let r of e){let e=R(r.network);if(e!==`evm`&&e!==`tempo`)continue;let i=qe(r),a=Je(i);n.has(a)||(n.add(a),t.push({chainTarget:i}))}return t}function Nd(e){let t=[],n=new Set;for(let r of e.chains){let i=R(r.network);if(i!==`evm`&&i!==`tempo`||!(i===`tempo`?e.signerOptions.tempo:e.signerOptions.evm).enabled)continue;let a=qe(r),o=Je(a);n.has(o)||(n.add(o),t.push({chainTarget:a}))}return t}function Pd(e){for(let t of e.signers)if(t.kind===`near_ed25519`)return!0;return!1}function Fd(e){let t=e.ecdsaChainTargets??Ld(e.configs,e.options);return Rd(e.accountProvisioning??mn(),t)}function Id(e){let t=null;for(let n of e.configs.network.chains)if(ie(n.network)){t=Vd(e);break}return Rd(t,Ld(e.configs,e.options))}function Ld(e,t){let n=Nd({signerOptions:t.signerOptions??e.signing.thresholdEcdsa.provisioningDefaults,chains:e.network.chains}),r=[];for(let e of n)r.push(e.chainTarget);return r}function Rd(e,t){let n=[];if(e&&n.push({kind:`near_ed25519`,accountProvisioning:e,signerSlot:1,participantIds:[...k],derivationVersion:1}),t.length&&n.push({kind:`evm_family_ecdsa`,chainTargets:[...t],participantIds:[...jd]}),!n.length)throw Error(`Wallet registration requires at least one configured, enabled signer`);return{kind:`signer_set`,signers:n}}function zd(e){let t=Oe(e);if(!t.ok)throw Error(t.message);return pn(t.value)}function Bd(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 zd(`${t}.${n}`)}function Vd(e){let t=e.preference??e.configs.registration.nearAccountProvisioning;switch(t.kind){case`implicit_account`:return mn();case`relayer_named_subaccount`:if(e.wallet.kind!==`provided`)throw Error(`Relayer named NEAR registration requires a provided walletId`);return Bd({walletId:e.wallet.walletId,relayerAccountId:e.configs.network.relayer.accountId});default:return t}}async function Hd(e){let t=performance.now();vr(`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);vr(`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{vr(`evm-family`,{event:`ecdsa_session_prefill`,trigger:e.trigger,chainTarget:e.chainTarget,status:`failed`,reason:`unexpected_error`,durationMs:performance.now()-t})}}const Ud=new Map,Wd=new Set;function Gd(e,t){for(let n of Wd)try{n(e,t)}catch{}}function Kd(e,t){let n=String(e),r=Ud.get(n);if(r)return r;let i={state:{status:`near_pending`,updatedAtMs:t},inFlight:null};return Ud.set(n,i),i}function qd(e){return Ud.get(String(e))?.state??null}async function Jd(e){let t=Ud.get(String(e));return t?t.inFlight?await t.inFlight:t.state:null}function Yd(e,t){let n=Kd(e,t.updatedAtMs);n.state.status===`near_ready`&&t.status!==`near_ready`||(n.state=t,Gd(e,t))}function Xd(e){return Wd.add(e),()=>{Wd.delete(e)}}function Zd(e){let t=Kd(e.walletId,e.nowMs());if(t.inFlight)return t.inFlight;if(t.state.status===`near_ready`)return Promise.resolve(t.state);Yd(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,Yd(e.walletId,n),n));return t.inFlight=n,n}function Qd(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 $d(e){let{session:t,previous:n}=e;if(n.walletId!==t.walletId||n.authorityId!==t.authorityId||n.revocationEpoch!==t.authorityRevocationEpoch||n.authorityDigestB64u===t.authorityDigestB64u||!n.signerActivations.ed25519)return;let r=t.capabilitySubjects.find(ef);if(!r||r.kind!==`sign`)return;let i=await ut({authority:n,materialActivation:r.materialActivation,updatedAtMs:Date.now()});i.authorityDigestB64u===t.authorityDigestB64u&&await Ue.runTransaction([Ve.walletAuthorities,Ve.signingSessionSeals],`readwrite`,tf.bind(null,n,i))}function ef(e){return e.kind===`sign`&&e.keyFamily===`ed25519`}async function tf(e,t,n){let r=n.store(Ve.walletAuthorities),i=ln(await r.get(e.authorityId));if(!i||i.record.state!==`active`||i.record.walletId!==e.walletId||i.record.revocationEpoch!==e.revocationEpoch||i.record.authorityDigestB64u!==e.authorityDigestB64u&&i.record.authorityDigestB64u!==t.authorityDigestB64u)throw Error(`Recovered Ed25519 authority changed before local adoption`);i.record.authorityDigestB64u!==t.authorityDigestB64u&&await r.put(sn(t));let a=e.signerActivations.ed25519;if(!a)return;let o=await n.store(Ve.signingSessionSeals).index(`wallet_id`).openCursor(e.walletId);for(;o;){let t=os(Bo(o.value));t.kind===`current`&&t.record.curve===`ed25519`&&t.record.walletId===e.walletId&&f(t.record.ed25519Restore.materialActivation,a.materialActivation)&&await o.delete(),o=await o.continue()}}async function nf(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 rf(e){return await af(await nf(e))}async function af(e){return await Lt({authority:{walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.walletAuthMethodId}})}async function of(e){let{record:t,operationCredential:n}=e.authorization;e.statusReads.invalidateCredential(n.token);let r=await e.statusReads.read({relayerUrl:e.relayerUrl,operationCredential:n},{walletSessionId:n.walletSessionId,quotaId:t.quotaId});if(r.status!==`active`||!br(r.authorization,t)||r.authorization.authorityRevocationEpoch!==t.authorityRevocationEpoch||!r.authorization.capabilitySubjects.some(sf.bind(null,e.materialActivation)))throw Error(`Recovered Ed25519 material does not match the active Wallet Session`);if(await $d({session:r.authorization,previous:e.previousAuthority}),await cf({walletId:t.walletId,authorization:{record:r.authorization,operationCredential:n}}),(await V.replaceExactActiveWalletSessionFromStatus({active:r.authorization,operationCredential:n})).kind===`superseded`)throw Error(`Wallet Session changed before recovered authority adoption`)}function sf(e,t){return t.kind===`sign`&&t.keyFamily===`ed25519`&&f(e,t.materialActivation)}async function cf(e){let t=await V.getWalletAuthMethodV2(e.authorization.record.authMethodId);if(!t||t.kind!==`passkey`||t.status!==`active`||t.walletId!==e.walletId||t.walletAuthorityId!==e.authorization.record.authorityId)throw Error(`Passkey Wallet Session authorization changed auth-method identity`);let n=await V.getWalletAuthority(t.walletAuthorityId);if(!n||n.state!==`active`||n.walletId!==e.walletId||n.authorityId!==e.authorization.record.authorityId||n.authorityDigestB64u!==e.authorization.record.authorityDigestB64u||n.revocationEpoch!==e.authorization.record.authorityRevocationEpoch)throw Error(`Passkey Wallet Session authorization changed authority identity`);return{reference:await af(t),identity:xr({authority:n,walletAuthMethodId:t.walletAuthMethodId})}}async function lf(e){let t=await V.getWalletAuthMethodV2(e.authMethodId);if(!t||t.kind!==`passkey`||t.status!==`active`||t.walletId!==e.walletId)throw Error(`Passkey recovery requires its active authentication method`);let n=await V.getWalletAuthority(t.walletAuthorityId);if(!n||n.state!==`active`||n.walletId!==e.walletId)throw Error(`Passkey recovery requires its active wallet authority`);return n}const uf=[`walletId`,`envelopeId`,`factor`,`envelopeRevision`,`binding`,`ownership`];function df(e){let t=ff(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=ze({kind:Pe,envelopeId:t.envelopeId,walletId:t.walletId,binding:t.binding,factor:t.factor,ownership:Ne(t.ownership,`recoveryReplacementEnvelope.binding.ownership`),envelopeVersion:Pe,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 ff(e){let t;try{t=JSON.parse(e)}catch{throw Error(`recovery replacement envelope binding is not JSON`)}let n=h(t,`recoveryReplacementEnvelope.binding`);return P(n,uf,`recoveryReplacementEnvelope.binding`),n}const pf=`passkeyCustodyEnvelopeCacheV1`,mf=`passkey_custody_envelope_cache_v1`;let hf={kind:`unconfigured`};const gf=new Map;function _f(e){throw Error(`unknown passkey custody session cache persistence state: ${String(e)}`)}function vf(){switch(hf.kind){case`configured`:return hf.persistence;case`unconfigured`:throw Error(`passkey custody session cache persistence is not configured`);default:return _f(hf)}}function yf(e){hf={kind:`configured`,persistence:e}}function bf(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 xf(){return{kind:mf,envelopes:[]}}function Sf(e){if(e==null)return xf();if(typeof e!=`object`||Array.isArray(e))throw Error(`passkey custody envelope cache is invalid`);let t=e;if(t.kind!==mf||!Array.isArray(t.envelopes))throw Error(`passkey custody envelope cache has an invalid shape`);return{kind:mf,envelopes:t.envelopes.map(e=>{let t=ze(e);if(!Me(t.binding))throw Error(`generic passkey custody cache cannot contain an Ed25519 export root`);return t})}}async function Cf(){return Sf(await vf().readCacheEntry(pf))}async function wf(e){await vf().writeCacheEntry(pf,e)}async function Tf(e){if(e.envelope.lifecycle.state!==`active`)throw Error(`passkey custody session envelope is not active`);if(!Me(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=bf(String(e.walletId),String(e.credentialIdB64u));gf.set(t,e.envelope);let n=(await Cf()).envelopes.filter(e=>e.factor.kind!==`passkey`||bf(String(e.walletId),String(e.factor.credentialIdB64u))!==t);n.push(e.envelope),await wf({kind:mf,envelopes:n.slice(-32)})}async function Ef(e){let t=bf(String(e.walletId),String(e.credentialIdB64u)),n=gf.get(t);if(n)return n;let r=(await Cf()).envelopes.find(e=>e.lifecycle.state===`active`&&e.factor.kind===`passkey`&&bf(String(e.walletId),String(e.factor.credentialIdB64u))===t);return r?(gf.set(t,r),r):null}function Df(e){return Math.max(0,Math.round(performance.now()-e))}function Of(){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 kf(e){let t=performance.now(),n=fr(e.credential,`Passkey registration authority`),r=Df(t),i=performance.now(),a=Yn(e.credential),o=Df(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 Af(e){let t=performance.now();return kf({credential:await e,diagnostics:Of(),requestConfirmationMs:Df(t)})}async function jf(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=Df(t),i=n.registrationDiagnostics??Of();return kf({credential:n.credential,diagnostics:i,requestConfirmationMs:r})}function Mf(e){let t=e.trim();if(!t)throw Error(`Registration finalize idempotency key is required`);return t}function Nf(e){let t=d(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=N(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 Pf(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`,...Nf(t)}}function Ff(e){let t=Rf(e,`wallet/email-otp/challenge signerSelection`);if(t.kind===`ed25519_only`)return{kind:`ed25519_only`,...Nf(t)};if(t.kind!==`ecdsa`)throw Error(`wallet/email-otp/challenge signerSelection kind is invalid`);return{kind:`ecdsa`,keyHandle:Q(t.keyHandle,`wallet/email-otp/challenge keyHandle`),runtimePolicyScope:I(t.runtimePolicyScope),ed25519:Pf(t.ed25519)}}var If=class extends Error{code;status;retryAfterMs;resetAtMs;constructor(e){super(e.message),this.name=`EmailOtpRouteError`;let t=zf(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 Lf(e){let t=e||globalThis.fetch;if(typeof t!=`function`)throw Error(`fetch is unavailable in this runtime`);return t}function Rf(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} returned invalid JSON`);return e}function Q(e,t){return w(e,t)}function zf(e){return g(e)}function Bf(e){let t={"Content-Type":`application/json`},n=String(e.publishableKey||``).trim();return n&&(t.Authorization=`Bearer ${n}`),t}function Vf(e){return e.routeFamily===`registration`?pu({routeFamily:`registration`,operation:xe}):pu({routeFamily:`login`,operation:e.operation??`wallet_unlock`})}function Hf(e){let t=zf(e.challenge.action);if(t&&t!==e.expectedAction)throw Error(`${e.context} returned ${t}; expected ${e.expectedAction}`)}async function Uf(e){let t=await Lf(e.fetchImpl)(e.url,{method:`POST`,headers:Bf({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=Rf(r,e.url);if(!t.ok||i.ok===!1)throw new If({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 Wf(e){if(e.restartRegistrationOffer===!0&&e.accountMode!==`register`)throw Error(`restartRegistrationOffer is only valid with register account mode`);let t=await Uf({url:s(e.relayUrl,`/auth/google/verify`),fetchImpl:e.fetchImpl,publishableKey:Q(e.publishableKey,`publishableKey`),body:{id_token:Q(e.idToken,`idToken`),account_mode:e.accountMode,project_environment_id:Q(e.projectEnvironmentId,`projectEnvironmentId`),...e.loginWalletId?{wallet_id:Q(e.loginWalletId,`loginWalletId`)}:{},...e.restartRegistrationOffer===!0?{restart_registration_offer:!0}:{}}}),n=Q(t.mode,`auth/google/verify mode`),r=Q(t.walletId,`auth/google/verify walletId`),i=Q(t.providerSubject,`auth/google/verify providerSubject`),a=zf(t.email);if(n===`existing_wallet`){if(t.hasEmailOtpEnrollment!==!0)throw Error(`auth/google/verify existing wallet is missing Email OTP enrollment`);if(!a)throw Error(`auth/google/verify existing wallet is missing email`);return{mode:n,walletId:r,providerSubject:i,email:a,hasEmailOtpEnrollment:!0}}if(n!==`register_started`)throw Error(`auth/google/verify returned unsupported mode: ${n}`);if(!a)throw Error(`auth/google/verify registration is missing email`);let o=Rf(t.offer,`auth/google/verify offer`),c=(Array.isArray(o.candidates)?o.candidates:[]).map(Gf),l=c[0];if(!l)throw Error(`auth/google/verify offer has no wallet candidates`);return{mode:n,walletId:r,providerSubject:i,email:a,registrationAttemptId:Q(t.registrationAttemptId,`auth/google/verify registrationAttemptId`),expiresAtMs:Kf(t.expiresAtMs,`auth/google/verify expiresAtMs`),offer:{offerId:Q(o.offerId,`auth/google/verify offer.offerId`),selectedCandidateId:Q(o.selectedCandidateId,`auth/google/verify offer.selectedCandidateId`),candidates:[l,...c.slice(1)]}}}function Gf(e){let t=Rf(e,`auth/google/verify offer candidate`);return{candidateId:Q(t.candidateId,`offer candidate candidateId`),walletId:Q(t.walletId,`offer candidate walletId`)}}function Kf(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 qf(e){let t=e.operation??`wallet_unlock`;if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpChallenge`,payload:{relayUrl:Q(e.relayUrl,`relayUrl`),walletId:Q(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Q(e.walletAuthMethodId,`walletAuthMethodId`)}:{},routePlan:Vf({routeFamily:`login`,operation:t}),otpChannel:be,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}});let n=await Uf({url:s(e.relayUrl,`/wallet/email-otp/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Q(e.walletId,`walletId`),...e.walletAuthMethodId?{walletAuthMethodId:Q(e.walletAuthMethodId,`walletAuthMethodId`)}:{},otpChannel:e.otpChannel||`email_otp`,operation:t,...e.operationFingerprintDigest?{operationFingerprintDigest:e.operationFingerprintDigest}:{}}}),r=Rf(n.challenge,`wallet/email-otp/challenge`);Hf({challenge:r,expectedAction:we.login,context:`wallet/email-otp/challenge`});let i=wr(n.delivery,`wallet/email-otp/challenge delivery`),a=Number(r.expiresAtMs),o={challengeId:Q(r.challengeId,`wallet/email-otp/challenge challengeId`),otpChannel:be,delivery:i,emailHint:i.emailHint,ownerProofBindingDigest:Q(r.ownerProofBindingDigest,`wallet/email-otp/challenge ownerProofBindingDigest`),walletAuthMethodId:Q(n.walletAuthMethodId,`wallet/email-otp/challenge walletAuthMethodId`),signerSelection:Ff(n.signerSelection)};return Number.isFinite(a)&&(o.expiresAtMs=a),o}async function Jf(e){if(!e.fetchImpl&&e.workerCtx)return await e.workerCtx.requestWorkerOperation({kind:`emailOtp`,request:{type:`requestEmailOtpEnrollmentChallenge`,payload:{relayUrl:Q(e.relayUrl,`relayUrl`),walletId:Q(e.walletId,`walletId`),routePlan:Vf({routeFamily:`registration`}),otpChannel:be}}});let t=await Uf({url:s(e.relayUrl,`/wallet/email-otp/registration/challenge`),fetchImpl:e.fetchImpl,body:{walletId:Q(e.walletId,`walletId`),otpChannel:e.otpChannel||`email_otp`}}),n=Rf(t.challenge,`wallet/email-otp/registration/challenge`);Hf({challenge:n,expectedAction:we.registration,context:`wallet/email-otp/registration/challenge`});let r=wr(t.delivery,`wallet/email-otp/registration/challenge delivery`),i=Number(n.expiresAtMs),a={challengeId:Q(n.challengeId,`wallet/email-otp/registration/challenge challengeId`),otpChannel:be,delivery:r,emailHint:r.emailHint};return Number.isFinite(i)&&(a.expiresAtMs=i),a}function Yf(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 Xf(e){let t=Yf(e.authMethod.email,`email`).toLowerCase(),n=Yf(e.authMethod.providerSubject,`providerSubject`),r=Yf(e.relayUrl,`relayUrl`),i=Yf(e.walletId,`walletId`),a=Yf(e.registrationIntentDigestB64u,`registrationIntentDigestB64u`);if(e.authMethod.proofKind===`google_sso_registration`){let r=Yf(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:Yf(e.authMethod.googleEmailOtpRegistrationOfferId,`googleEmailOtpRegistrationOfferId`),googleEmailOtpRegistrationCandidateId:Yf(e.authMethod.googleEmailOtpRegistrationCandidateId,`googleEmailOtpRegistrationCandidateId`),registrationIntentDigestB64u:a},registrationAuthorityId:r,providerSubject:n,email:t}}let o=Yf(e.authMethod.otpCode,`otpCode`),s=typeof e.authMethod.challengeId==`string`?e.authMethod.challengeId.trim():``,c=s?null:await Jf({relayUrl:r,walletId:i,fetchImpl:e.fetchImpl}),l=s||Yf(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:be,registrationIntentDigestB64u:a},registrationAuthorityId:l,providerSubject:n,email:t}}function Zf(e,t,n){if(e!==t)throw Error(`${n} does not match the verified add-signer intent`)}function Qf(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 $f(e){let t=b(e.verifiedIntent.addSignerIntentGrant,`add-signer intent grant`);return{routerOrigin:b(e.httpTransport.routerOrigin,`Yao Router origin`),routing:{kind:`discovery`},authorization:{kind:`bearer`,value:`Bearer ${t}`},fetch:e.httpTransport.fetch}}async function ep(e){let t=e.verifiedIntent.intent,n=t.signerSelection.ed25519;Zf(String(t.walletId),String(e.verifiedAuthority.walletId),`Passkey authority wallet ID`),Zf(e.verifiedIntent.addSignerIntentDigestB64u,e.verifiedAuthority.addSignerIntentDigestB64u,`Passkey authority intent digest`),b(e.verifiedAuthority.credentialIdB64u,`passkey credential ID`);let r=I(t.runtimePolicyScope),i=ee(r),a=it(e.admissionRequest);if(!a.ok)throw Error(a.message);let o=a.value,s=b(e.verifiedIntent.addSignerCeremonyId,`add-signer ceremony ID`);if(Zf(o.scope.lifecycle_id,s,`Yao lifecycle ID`),Zf(o.scope.threshold_session_id,s,`Yao Threshold Session ID`),Zf(o.scope.account_id,String(t.walletId),`Yao account ID`),Zf(o.scope.signer_set_id,String(fn(n.signerSlot)),`Yao signer-set ID`),Zf(o.scope.root_share_epoch,r.signingRootVersion,`Yao root-share epoch`),Zf(o.application_binding.wallet_id,String(t.walletId),`Yao application wallet ID`),Zf(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`);Qf(n.participantIds,o.participant_ids);let c=await Ht({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 Zf(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:$f(e)}}async function tp(e){let t=await ep(e),n=await new wi(t.transportConfig).send({kind:`admit`,path:ct,body:t.request});if(!n.ok)throw Error(n.message);let r=dt(n.value);if(!r.ok)throw Error(r.message);return{request:t.request,receipt:r.value}}function np(e){let t=a(e);if(!t.ok)throw Error(t.error.message);return t.value}function rp(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 ip(e){let t=e.configs.signing.emailOtp.authPolicy;return sr({policy:t,retention:`session`,reason:`login`,authority:e.authority})}async function ap(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:rp({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(!Pt(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=kt({...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 ip({configs:e.configs,authority:i}),authority:i}}default:return J(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||!Wc(e.session.chainTargets,e.expectedChainTargets))throw Error(`ECDSA registration family session target projection is incomplete`);return Vc(e.walletKeys),Hc({session:e.session,walletKeys:e.walletKeys}),$c({session:e.session,walletKeys:e.walletKeys}),{kind:`evm_family_ecdsa`,session:e.session,walletKeys:[t,...n],expectedChainTargets:[r,...i]}}function sp(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 cp(e){return{kind:`registration_persistence_plan_v1`,walletId:e.walletId,auth:e.auth,ecdsa:e.ecdsa,foundingAuthority:e.foundingAuthority,foundingAuthMethod:e.foundingAuthMethod}}function lp(e){let t=dn(e);if(!t)throw Error(`pending wallet registration commit is invalid`);return t}function up(e){let t=Ke(e.walletId),r=n(e.walletAuthMethodId);if(!r.ok)throw Error(r.error.message);let i=dp(e.auth),a={kind:`pending_wallet_registration_commit_v1`,registrationCeremonyId:fp(e.registrationCeremonyId,`registrationCeremonyId`),idempotencyKey:fp(e.idempotencyKey,`idempotencyKey`),walletId:t,walletAuthMethodId:r.value,signedSetup:fp(e.signedSetup,`signedSetup`),auth:i,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs};if(e.operation===`registration_activate`)return lp({...a,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 lp({...a,operation:e.operation,phase:`joined`,completion:e.completion,signerPlanKind:e.signerPlanKind,localMaterial:e.localMaterial})}function dp(e){if(e.kind===`passkey`){let t=np(e.rpId),n=i(e.credentialIdB64u);if(!n.ok)throw Error(n.error.message);return{kind:`passkey`,rpId:t,credentialIdB64u:n.value,transports:[...e.transports]}}let t=l(e.email);if(!t.ok)throw Error(t.error.message);let n=p(e.registrationAuthorityId);if(!n.ok)throw Error(n.error.message);let r=u(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:fp(e.enrollment.enrollmentSealKeyVersion,`enrollment.enrollmentSealKeyVersion`),serverSealedFactorCiphertextB64u:fp(e.enrollment.serverSealedFactorCiphertextB64u,`enrollment.serverSealedFactorCiphertextB64u`),clientUnlockPublicKeyB64u:fp(e.enrollment.clientUnlockPublicKeyB64u,`enrollment.clientUnlockPublicKeyB64u`),unlockKeyVersion:fp(e.enrollment.unlockKeyVersion,`enrollment.unlockKeyVersion`)}}}function fp(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 pp(e){e.registrationTiming.record(`ecdsaRegistrationTargetCount`,e.plan.ecdsa.walletKeys.length);let t=performance.now();try{return await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ke(e.plan.walletId),session:e.plan.ecdsa.session,walletKeys:[...e.plan.ecdsa.walletKeys]})}finally{e.registrationTiming.record(`ecdsaRegistrationSessionFinalizeMs`,Va(t))}}async function mp(e){if(e.plan.auth.kind===`passkey`){await e.context.signingEngine.finalizeWalletEcdsaRegistration({walletId:e.plan.walletId,rpId:np(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 hp(e){let t=await pp(e),n=performance.now();try{if(await mp({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=l(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`,Va(n))}await yr(wn,e.plan.ecdsa.session.registrationEstablishedSession)}function gp(e){return hp.bind(void 0,e)}async function _p(e){await e.registrationTiming.measure(`ecdsaRegistrationPersistenceMs`,gp(e))}var vp=e({REGISTRATION_TIMING_LABEL:()=>Ta,addSigner:()=>Fh,cancelHostedPasskeyRegistration:()=>am,prepareHostedPasskeyRegistration:()=>im,registerPreparedHostedPasskeyRegistration:()=>sm,registerWallet:()=>Sh,resumeNearRegistrationAfterUnlock:()=>eh,startHostedPasskeyRegistrationCredential:()=>om});async function yp(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 xp({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 null;case`wallet_recovery_code_backup_deferred_v1`:return await pr.write({walletId:t,recoveryCodes:r});default:throw Error(`Wallet recovery-code backup result is invalid`)}}async function bp(e,t,n,r,i){e.value=await yp(t,n,r,i)}async function xp(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 dr(e.request,e.context.signingEngine.getWalletIframeSurfaceMeasurementBinding());case`custom_handler`:return await e.backup.handler(e.request);default:return J(e.backup)}}function Sp(e){e.byteLength>0&&new Uint8Array(e).fill(0)}function Cp(e){let t=e.established.metadata;return{binding:{kind:Zn,applicationBindingDigestB64u:e.established.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:A(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:A(t.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:e.established.localMaterial.b64u,nonceB64u:e.established.localMaterial.nonceB64u}}}function wp(e){let t=e.metadata;return{materialActivation:Mn(t),registeredPublicKeyB64u:A(t.registeredPublicKey),signingWorkerVerifyingShareB64u:A(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 Tp(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 Ep(e){let t=e.commit.establishedCustody;if(!t)throw Error(`Passkey registration custody commit is missing its established envelope`);return df({expectedWalletId:e.walletId,replacement:t,activatedAtMs:e.activatedAtMs})}async function Dp(e){await e.signingEngine.establishUnlockedWalletEd25519ExportRootCapabilityV1({existingEnvelope:Ep({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 Op(e){try{await En(Dn(e.context.signingEngine.getSignerWorkerContext()),{existingEnvelope:Ep({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 kp(e){let t=Ep(e);if(t.factor.kind!==`passkey`)throw Error(`Passkey registration custody commit has a non-passkey factor`);await Tf({walletId:e.walletId,credentialIdB64u:t.factor.credentialIdB64u,envelope:t})}function Ap(e){let n=e.joined.metadata,r=t(n.scope.threshold_session_id);if(!r.ok)throw Error(`Registration Ed25519 capability has an invalid threshold session`);return{kind:ft,session:{walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,authorityScope:{kind:`email_otp`,provider:ir(e.authContext),providerUserId:ar(e.authContext)},thresholdSessionId:r.value,authorizationId:e.sessionState.signingWalletSession.authorizationId,walletSessionId:e.sessionState.walletSessionId,quotaId:e.sessionState.quotaId,expiresAtMs:e.sessionState.signingWalletSession.expiresAtMs,participantIds:n.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:n.materialActivation,activeCapabilityBinding:n.activeCapabilityBinding,registeredPublicKey:[...n.registeredPublicKey],nearAccountId:e.nearAccountId,applicationBinding:n.applicationBinding,runtimePolicyScope:e.sessionState.runtimePolicyScope,participantIds:n.participantIds,lifecycle:{lifecycleId:n.scope.lifecycle_id,rootShareEpoch:n.scope.root_share_epoch,accountId:n.scope.account_id,thresholdSessionId:r.value,signerSetId:n.scope.signer_set_id,signingWorkerId:n.scope.signing_worker_id},stateEpoch:Number(n.stateEpoch),registrationContinuity:{kind:`registration`,admissionRequest:e.deferredNear.admissionRequest,admissionReceipt:e.admissionReceipt,activationTranscript:[...n.transcript]}}}}const jp=Symbol(`hostedPasskeyRegistrationPrepared`),Mp=new WeakMap;function Np(e){let t=hn(e);if(!t.ok)throw Error(t.message);return t.value}function Pp(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 Fp(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 J(e)}}function Ip(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`near_ed25519`:return t.kind===`near_ed25519`&&Fp(e.accountProvisioning,t.accountProvisioning)&&e.signerSlot===t.signerSlot&&Pp(e.participantIds,t.participantIds)&&e.derivationVersion===t.derivationVersion;case`evm_family_ecdsa`:return t.kind===`evm_family_ecdsa`&&Pp(e.participantIds,t.participantIds)&&vn(e.chainTargets)===vn(t.chainTargets);default:return J(e)}}function Lp(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||!Ip(r,i))return!1}return!0}function Rp(e){return e.signingEngine.warmCriticalResources.bind(e.signingEngine,{kind:`none`})}function zp(){return Promise.resolve(io())}function Bp(e){return e.signers.some(e=>e.kind===`evm_family_ecdsa`)}function Vp(e){return e.authMethod.kind!==`email_otp`||!Pd(e.signerSelection)?zp:Up.bind(void 0,{prewarm:e.context.signingEngine.prewarmEmailOtpYao.bind(e.context.signingEngine)})}function Hp(e,t){let n=Va(t);return{kind:`failed`,elapsedMs:n,workerPrewarmMs:n,yaoWasmInitMs:0,failureStage:`worker_ready`}}function Up(e){let t=performance.now();return e.prewarm().catch(e=>Hp(e,t))}function Wp(e){let[t,n]=e;return{kind:`completed`,diagnostics:{...t,emailOtpWorkerPrewarmMs:n.workerPrewarmMs,emailOtpYaoWasmInitMs:n.yaoWasmInitMs,emailOtpYaoPrewarm:n}}}function Gp(e){return{kind:`failed`,error:e}}function Kp(e){In({relayerUrl:e.relayerUrl,nearEd25519:e.signerSelection.signers.some(e=>e.kind===`near_ed25519`),evmFamilyEcdsa:Bp(e.signerSelection)}),Pd(e.signerSelection)&&tl(e.authMethod,e.context.signingEngine.prewarmNearSigner.bind(e.context.signingEngine));let t=e.recorder.measure(`registrationWarmupMs`,Rp(e.context)),n=e.recorder.measure(`registrationWarmupEmailOtpYaoWasmInitMs`,Vp({context:e.context,authMethod:e.authMethod,signerSelection:e.signerSelection}));return Bp(e.signerSelection)&&e.context.signingEngine.prewarmEcdsaRegistrationCrypto?.().catch(()=>{}),Promise.all([t,n]).then(Wp,Gp)}function qp(e){e.warmup.then(t=>{t.kind===`completed`&&e.recorder.captureWarmupDiagnostics(t.diagnostics)})}function Jp(e){return _n(Np(e))?.signerSlot??1}async function Yp(e){return e.passkeyExecution?.kind===`use_hosted_preparation`?await e.passkeyExecution.authority:await jf({context:e.context,walletId:e.walletId,signerSlot:e.signerSlot,registrationIntentDigestB64u:e.registrationIntentDigestB64u,options:e.options,confirmationConfigOverride:e.confirmationConfigOverride})}function Xp(e){if(e[jp]!==!0)throw Error(`Invalid hosted passkey registration preparation`);let t=Mp.get(e);if(!t)throw Error(`Hosted passkey registration preparation is unknown`);return t}function Zp(e){if(e.lifecycle!==`ready`)throw Error(`Hosted passkey registration preparation is no longer usable`);if(Date.now()>=e.prepared.expiresAtMs)throw am(e.prepared),Error(`Hosted passkey registration preparation expired`);if(e.controller.signal.aborted)throw Error(`Hosted passkey registration preparation was cancelled`);if(!Sr.isLiveReservation({reservation:e.prepared.reservation,owner:e.prepared.owner}))throw am(e.prepared),Error(`Hosted passkey registration prompt reservation is no longer active`)}function Qp(e){return C({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:e.walletId,signerSlot:e.signerSlot,rpId:e.rpId,challengeB64u:e.challengeB64u})}function $p(){return Error(`Hosted passkey registration preparation was cancelled`)}function em(e){if(e.aborted)throw $p()}function tm(e){let t=e.cancellation.signal;return em(t),new Promise((n,r)=>{let i=!1,a=()=>{c($p())},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 nm(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=Fm(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 J(e.setup)}}function rm(e){e.ceremony.kind!==`not_required`&&Gc({context:e.context,ceremonyId:e.ceremony.ceremonyId})}async function im(e){let t=e.authMethod,n=np(String(t.rpId));if(np(String(e.context.signingEngine.getRpId()||``))!==n)throw Error(`Hosted passkey registration rpId does not match the wallet runtime`);let r=Jp(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&&am(c)},f=()=>{e.cancellation.signal.removeEventListener(`abort`,d)};em(e.cancellation.signal),e.cancellation.signal.addEventListener(`abort`,d,{once:!0});let p=new ro(performance.now());try{let i=await tm({operation:Om({completion:`wallet_session`,context:e.context,authMethod:t,wallet:e.wallet,signerSelection:e.signerSelection,recorder:p}),cancellation:e.cancellation}),d=sl(i.setup.intent);if(String(d.authMethod.rpId)!==String(n)||!Lp(d.signerSelection,e.signerSelection))throw Error(`Hosted passkey registration setup changed its authority binding`);let m=Ut(String(d.walletId)),h=String(i.setup.registrationIntentDigestB64u||``).trim();if(!h)throw Error(`Hosted passkey registration setup returned no challenge`);if(r!==Jp(e.signerSelection))throw Error(`Hosted passkey registration signer slot changed during preparation`);if(u=nm({context:e.context,setup:i.setup}),qp({recorder:p,warmup:i.registrationWarmup}),Date.now()>=a)throw Error(`Hosted passkey registration preparation expired before reservation`);let g=await Sr.reserveRegistrationPrompt({owner:o,expiresAtMs:a,cancellation:e.cancellation});l=g;let _=Qp({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},[jp]:!0});return Mp.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(),rm({context:e.context,ceremony:u}),c?am(c):l&&Sr.releaseReservation(l),t}}function am(e){let t=Xp(e);t.lifecycle===`finished`||t.lifecycle===`cancelled`||(t.lifecycle=`cancelled`,t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,rm({context:t.context,ceremony:t.ecdsaClientCeremony}),Sr.releaseReservation(e.reservation))}function om(e){let t=Xp(e);Zp(t),t.lifecycle=`consuming`;let n=Af(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`)},()=>{am(e)}),n}async function sm(e){let t=Xp(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 bh({completion:`wallet_session`,context:t.context,authMethod:t.authMethod,wallet:t.wallet,signerSelection:t.signerSelection,options:t.options,authenticatorOptions:yn(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`,rm({context:t.context,ceremony:t.ecdsaClientCeremony}),t.controller.abort(),t.removeExternalCancellationListener?.(),t.removeExternalCancellationListener=null,Sr.releaseReservation(e.prepared.reservation)}}async function cm(e){return Mf(`wallet-registration-near-provisioning:${await y([`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 lm(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return Mf(`${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),Mf(`${e}:${[...n].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`)}function um(e){return e.recorder.measure(`emailOtpEnrollmentMaterialMs`,()=>fm({context:e.context,authMethod:e.authMethod,relayerUrl:e.relayerUrl,walletId:e.walletId,providerSubject:e.providerSubject,clientSecret32:e.clientSecret32}))}function dm(e){if(e.emailOtpSessionHandle.kind!==`not_requested`)throw Error(`Strict ECDSA registration received obsolete Email OTP root-share material`)}async function fm(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:Ke(e.walletId),userId:e.providerSubject,clientSecret32:e.clientSecret32});return dm(t),t}finally{e.clientSecret32.fill(0)}}function pm(e){let t=e.event.authMethod,n=mm(e.accountId);return $t({...e.event,flowId:`registration:${t}:${n}`,accountId:n,authMethod:t})}function mm(e){let t=String(e||``).trim();if(!t)throw Error(`Registration event account id is required`);return t}function hm(e){return v(e)&&`code`in e?String(e.code||``).trim():``}function gm(e,t){return Object.assign(Error(e),t?{code:t}:{})}function _m(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 vm(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 ym(e){let t=String(e||``).trim().toLowerCase();if(!t)throw Error(`Email OTP registration auth context requires email`);return y(t)}function bm(e){switch(e.proofKind){case`otp_challenge`:return`email`;case`google_sso_registration`:return`google`;default:return J(e)}}function xm(e){switch(e.kind){case`passkey`:return{kind:`passkey`,webauthnRegistration:e.webauthnRegistration};case`email_otp`:return{kind:`email_otp`,emailOtpRegistrationProof:e.emailOtpRegistrationProof};default:return J(e)}}async function Sm(e){let t=performance.now();try{let n=await ul(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 q({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`success`}),{deferredNear:e.deferredNear,admissionReceipt:n}}catch(n){throw q({ceremonyId:e.registrationCeremonyId,stage:`early_admission`,startedAt:t,outcome:`failure`}),n}}function Cm(e){if(!e)throw Error(`Mixed registration did not start NEAR admission`);return e}function wm(e,t,n){switch(e.kind){case`passkey`:return{auth:{kind:`passkey`,rpId:Sn(e.rpId),credentialIdB64u:t}};case`email_otp`:return{auth:{kind:`email_otp`,providerSubjectId:ar(e.emailOtpAuthContext)},remainingUses:n.remainingUses,expiresAtMs:n.expiresAtMs};default:return J(e)}}async function Tm(e){let t=jt(C({operation:`wallet_registration_activate_v2`,registrationCeremonyId:e.registrationCeremonyId,activationCorrelationId:e.activationCorrelationId,idempotencyKey:e.idempotencyKey,publicFacts:e.publicFacts}));return{canonicalRequest:t,requestDigest:ge(A(await S(String(t))))}}async function Em(e){let t={authority:e.materialAuthority,targetMemberships:e.chainTargets,evmFamilySigningKeySlotId:Nt(e.ecdsaPrepare.prepare.evmFamilySigningKeySlotId,`registration ECDSA signing key slot`),ecdsaThresholdKeyId:qt(e.ecdsaPrepare.prepare.ecdsaThresholdKeyId),signingRootId:wt(e.ecdsaPrepare.prepare.signingRootId),signingRootVersion:gt(e.ecdsaPrepare.prepare.signingRootVersion),runtimePolicyScope:e.ecdsaPrepare.prepare.runtimePolicyScope,clientVerifyingPublicKey33B64u:Gt(e.clientActivation.derivationClientSharePublicKey33B64u),participantIds:[Cn(e.ecdsaPrepare.prepare.participantIds[0]),Cn(e.ecdsaPrepare.prepare.participantIds[1])],relayerKeyId:Kt(e.ecdsaPrepare.prepare.relayerKeyId),bindingDigest:Zt(e.clientActivation.contextBinding32B64u),journalId:e.activationCorrelationId,requestDigest:e.activationCommand.requestDigest,canonicalRequest:e.activationCommand.canonicalRequest,createdAt:me(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 Dm(e){let t=j(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 Om(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=Kp({recorder:e.recorder,context:e.context,relayerUrl:t,authMethod:e.authMethod,signerSelection:e.signerSelection}),o=await e.recorder.measure(`registrationIntentMs`,()=>Wn({relayerUrl:t,request:{completion:e.completion,...e.wallet.kind===`provided`?{wallet:e.wallet}:{},signerSelection:e.signerSelection,authMethod:e.authMethod},auth:{publishableKey:r,environmentId:i}}));if(!o.ok)throw gm(o.message,o.code);return{relayerUrl:t,setup:o,registrationWarmup:a}}async function km(e){if(e.passkeyExecution.kind===`collect_during_registration`)return await Om({completion:e.completion,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=Xp(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=sl(n.setup.intent),i=String(n.setup.registrationIntentDigestB64u||``).trim(),a=Jp(e.signerSelection);if(Qp({wallet:e.wallet,signerSelection:e.signerSelection,authMethod:e.authMethod,walletId:Ut(String(r.walletId)),signerSlot:a,rpId:np(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 Am(e){if(e.passkeyExecution.kind===`collect_during_registration`)return{kind:`create_after_authority`};let t=Xp(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 jm(e){return await e}function Mm(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 jm.bind(void 0,e.clientCeremony.operation);default:return J(e.clientCeremony)}}async function Nm(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=he(r),a=null;try{let o=await Yc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationClientCreateMs`,operation:Mm({context:e.context,ceremonyId:r,registration:e.ecdsaPrepare.strictRegistration,clientCeremony:e.clientCeremony})}),s=await Yc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayRespondMs`,operation:Gn.bind(void 0,{relayerUrl:e.relayerUrl,headers:Lc(e.traceContext),registrationCeremonyId:r,signerPlanKind:e.signerPlanKind,signedSetup:e.signedSetup,ecdsa:{kind:`router_ab_ecdsa_registration_v1`,strictRegistration:o.registrationRequest,requestDigestB64u:o.registrationRequestDigestB64u},...xm(e.authority),onServerTiming:t=>Da(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?Sm({home:e.home,relayerUrl:e.relayerUrl,registrationCeremonyId:r,signedSetup:e.signedSetup,deferredNear:c,traceContext:e.traceContext}):null;l?.catch(qm);let u=await Yc({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=xt({registrationRequestDigestB64u:u.registrationRequestDigestB64u,proofTranscriptDigestB64u:u.proofTranscriptDigestB64u,contextBinding32B64u:t.contextBinding32B64u,derivationClientSharePublicKey33B64u:t.clientSharePublicKey33B64u,clientShareRetryCounter:t.clientShareRetryCounter,participantId:1}),o=await Tm({registrationCeremonyId:r,activationCorrelationId:i,idempotencyKey:e.idempotencyKey,publicFacts:n}),s=ou(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:Cm(l),establishedEvmCustodyCommit:t.preActivationCommitPayload}),a.catch(qm)}else await e.persistPendingCommit({signerPlanKind:e.signerPlanKind,localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:s,ecdsa:p},emailOtpEnrollment:d.enrollment});let m=await Em({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 Yc({registrationTiming:e.registrationTiming,bucket:`ecdsaRegistrationGatewayActivateMs`,operation:Nn.bind(void 0,{relayerUrl:e.relayerUrl,headers:Lc(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=>Da(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:Dm(_.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=Kc({prepare:e.ecdsaPrepare.prepare,verified:g.clientBootstrap}),y=Ln({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 Lt({authority:_.authority}),materialActivation:b.materialActivation,clientPublicFacts:b.publicFacts,publicCapability:b.publicCapability,registrationEstablishedSession:Bc(_.registrationEstablishedSession)},activated:_,deferredNear:c,activateEmailOtp:{enrollment:d.enrollment},walletCustody:g,deferredNearCustodyWork:a}}catch(t){throw Wm(a),await Gc({context:e.context,ceremonyId:r}),t}}function Pm(e){switch(e.kind){case`evm`:return Ye({chain:`evm`,chainId:e.chainId,networkSlug:e.networkSlug});case`tempo`:return Ye({chain:`tempo`,chainId:e.chainId,networkSlug:e.networkSlug});default:return J(e)}}function Fm(e){let[t,...n]=e.chainTargets;if(!t)throw Error(`Registration setup ECDSA chain targets are required`);return{kind:e.kind,chainTargets:[Pm(t),...n.map(Pm)],prepare:e.prepare,strictRegistration:e.strictRegistration}}function Im(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 J(e)}}function Lm(e){switch(e.kind){case`evm_family_ecdsa`:return 1;case`near_ed25519_and_evm_family_ecdsa`:return e.ed25519Selection.signerSlot;default:return J(e)}}function Rm(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:zm(e.emailOtpEnrollment)}}function zm(e){if(!e)throw Error(`Email OTP registration has no enrollment material for pending recovery`);return e}async function Bm(e){let t=Date.now(),n=up({...e,createdAtMs:t,updatedAtMs:t});return await V.putPendingWalletRegistrationCommit(n),n}function Vm(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 Hm(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 tr({kind:`passkey`,walletId:e.walletId,rpId:np(e.auth.rpId),credentialIdB64u:n,credentialPublicKeyB64u:e.auth.credentialPublicKeyB64u,transports:e.auth.credential.response?.transports??[],walletKeys:t})}return await tr({kind:`email_otp`,walletId:e.walletId,email:e.auth.email,registrationAuthorityId:e.auth.registrationAuthorityId,authority:e.auth.authority,walletKeys:t})}async function Um(e){let t=await pp({context:e.context,relayerUrl:e.relayerUrl,registrationTiming:e.registrationTiming,plan:e.plan}),n=await Hm({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 Wm(e){if(e)try{Sp((await e).factorSecret32)}catch{}}function Gm(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 J(e.auth)}}async function Km(e,t,n){let r=performance.now();await V.advancePendingNearRegistration({expected:e,next:tn(e,t,n)}),Kl(e.registrationCeremonyId,`journal_prepared`,r)}function qm(){}async function Jm(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(!st(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 Xm({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:Ep({commit:t.establishedEvmCustodyCommit,walletId:r.walletId,activatedAtMs:Date.now()}),factorSecret32:n}}catch(e){throw Sp(n),e}finally{q({ceremonyId:e.registrationCeremonyId,stage:`custody_join`,startedAt:r,outcome:i})}}async function Ym(e){return e.pending.phase===`execution_prepared`?e.pending.admissionReceipt:e.admitted?e.admitted:await ul({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 Xm(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 Ym({home:e.home,pending:n,relayerUrl:e.relayerUrl,credential:e.credential,traceContext:e.traceContext,...e.admitted?{admitted:e.admitted}:{}});Kl(n.registrationCeremonyId,`admission`,i);let o=await e.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:e.home,...n.phase===`planned`?{preparation:{kind:`fresh`},beforeRouterRound:Km.bind(void 0,n,a)}:{preparation:{kind:`checkpoint`,checkpointJson:n.checkpointJson}},custodyJson:Yl(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(A(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=up({operation:`near_provisioning`,signerPlanKind:`near_ed25519_and_evm_family_ecdsa`,completion:{kind:`encrypted_checkpoint`,prepared:c},registrationCeremonyId:c.registrationCeremonyId,idempotencyKey:await cm({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:wp(o)}}});if(l.operation!==`near_provisioning`||l.phase!==`joined`)throw Error(`Invalid joined NEAR continuation`);return await V.advancePendingNearRegistration({expected:c,next:l}),Kl(n.registrationCeremonyId,`journal_joined`,s),{joined:o,admissionReceipt:a}}function Zm(e){return e.chainTarget}function Qm(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=kt({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:sr({policy:`session`,retention:`session`,reason:`login`,authority:n})}}throw Error(`NEAR continuation requires its founding authentication method`)}async function $m(e){if(await rh(e.sessionAuthority),e.pending.phase===`joined`&&e.pending.completion.kind===`sealed_material`){let t=await Td({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 Xm({home:e.sessionAuthority.operationCredential.home,pending:e.pending,signingEngine:e.context.signingEngine,relayerUrl:e.relayerUrl,credential:e.sessionAuthority.operationCredential.token,traceContext:an(),factorSecret:e.factorSecret});return{joined:n.joined,admissionReceipt:n.admissionReceipt,admissionRequest:t.admissionRequest,envelope:e.envelope,factorSecret32:e.factorSecret}}async function eh(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=Qm(r,e.factor),a=$m.bind(void 0,{context:e.context,pending:r,envelope:e.custodyEnvelope,relayerUrl:n,sessionAuthority:e.sessionAuthority,factorSecret:e.ownedFactorSecret});await fh({context:e.context,walletId:r.walletId,commit:{context:e.context,registrationTiming:null,registrationStartedAt:t,relayerUrl:n,registrationCeremonyId:r.registrationCeremonyId,signedSetup:r.signedSetup,headers:Lc(),nearCustodyWork:a,sessionAuthority:e.sessionAuthority,expectedChainTargets:Md(e.context.configs.network.chains).map(Zm),walletId:r.walletId,authMaterial:i}})}}catch(e){console.warn(`[registration] NEAR continuation remains pending`,e instanceof Error?e.message:`continuation failed`)}finally{Sp(e.ownedFactorSecret)}}function th(e){if(!e)throw Error(`Mixed registration did not start its NEAR custody join`);return e}function nh(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()||!L(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 rh(e){let t=await wn.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 ih(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 ah(e){let{materialFacts:t}=e,n=null;try{n=await va(e),await ta({store:V,activeClient:n,identity:ya(t,e.rpId,e.credentialIdB64u),stableServerScope:t.stableServerScope,passkeyPrfFirstB64u:e.passkeyPrfFirstB64u}),await rh(e.sessionAuthority),await e.signingEngine.activateVerifiedNearEd25519YaoMaterial({activeClient:n,facts:{thresholdSessionId:t.identity.thresholdSessionId,signer:or({walletId:Ke(t.identity.walletId),nearAccountId:je(t.identity.nearAccountId),nearEd25519SigningKeyId:Bt(t.identity.nearEd25519SigningKeyId),signerSlot:t.identity.signerSlot}),signingRootId:t.identity.signingRootId,signingRootVersion:t.identity.signingRootVersion,routerAbNormalSigning:t.stableServerScope.routerAbNormalSigning,runtimePolicyScope:t.stableServerScope.runtimePolicyScope,relayerUrl:e.relayerUrl}}),await rh(e.sessionAuthority),n=null}catch(e){throw n?.dispose(),e}finally{e.ownedFactorSecret.fill(0)}}async function oh(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{q({ceremonyId:e.ceremonyId,stage:`session_hydration`,startedAt:t,outcome:n})}}async function sh(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{q({ceremonyId:e.ceremonyId,stage:`session_seal_preparation`,startedAt:t,outcome:n})}}function ch(e){let n=t(e.thresholdSessionId);if(!n.ok)throw Error(`Invalid admitted NEAR session identity`);let r=lm(`near-session-client-seal`);return{kind:`preparing`,thresholdSessionId:String(n.value),preparationId:r,result:sh({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,input:{preparationId:r,thresholdSessionId:String(n.value),prfFirstB64u:e.prfFirstB64u}})}}async function lh(e){try{await rh(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`}:ch({signingEngine:e.signingEngine,ceremonyId:e.ceremonyId,thresholdSessionId:t.admissionRequest.scope.threshold_session_id,prfFirstB64u:e.prfFirstB64u})}catch{return{kind:`none`}}}function uh(){return null}async function dh(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 lh({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:${ke(s.metadata.registeredPublicKey)}`,l=s.activationReference,u=await cm({registrationCeremonyId:e.registrationCeremonyId,activationReference:l}),d=await ih({registrationCeremonyId:e.registrationCeremonyId,walletId:e.walletId,walletAuthMethodId:String(e.sessionAuthority.record.authMethodId)});await rh(e.sessionAuthority),t.kind===`passkey`&&o.kind===`none`&&(o=ch({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(q({ceremonyId:e.registrationCeremonyId,stage:`session_seal_preparation_wait`,startedAt:t,outcome:n.kind===`completed`?`success`:`failure`}),n.kind===`failed`)throw n.error;await rh(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,...E(e.sessionAuthority.operationCredential)},idempotencyKey:u,ed25519:{activationReference:l},walletCustodyCommit:s.commitPayload,onServerTiming:Oa.bind(void 0,e.registrationTiming)},h;if(f){if(e.authMaterial.kind!==`passkey`)throw Error(`Prepared session sealing requires a passkey authority`);h=await Vn({...m,auth:{kind:`passkey`},sessionSeal:{thresholdSessionId:f.thresholdSessionId,ciphertext:f.ciphertext}})}else h=await Vn({...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`);q({ceremonyId:e.registrationCeremonyId,stage:`server_finalize`,startedAt:p,outcome:`success`});let _=nh(e.sessionAuthority,g.registrationEstablishedSession,g.foundingAuthority,g.foundingAuthMethod),v=je(g.ed25519.nearAccountId),y=e.authMaterial.kind===`passkey`?e.authMaterial.credentialIdB64u:``;t.kind===`passkey`?cl({clientPublicKey:c,finalized:g,expectedRpId:t.rpId,expectedWalletId:e.walletId}):ll({clientPublicKey:c,finalized:g,expectedRegistrationAuthorityId:d.auth.kind===`email_otp`?d.auth.registrationAuthorityId:``,expectedWalletId:e.walletId});let b=il({admissionRequest:n.admissionRequest,finalized:g.ed25519,walletId:e.walletId,expectedRuntimePolicyScope:I(g.ed25519.runtimePolicyScope)}),x=s.metadata,S=Mn(x),C=Cp({established:s,walletId:String(e.walletId),nearAccountId:String(v),nearEd25519SigningKeyId:g.ed25519.nearEd25519SigningKeyId,signerSlot:g.ed25519.signerSlot}),w=performance.now(),T=await bd(d,g);await rh(e.sessionAuthority);let D=(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(!D||D.signerSlot!==g.ed25519.signerSlot)throw Error(`Deferred Ed25519 registration persisted a different signer slot`);let O=new Tn;for(let t of e.expectedChainTargets)Hd({signingEngine:e.context.signingEngine,walletId:e.walletId,chainTarget:t,trigger:`registration`,statusReads:O});q({ceremonyId:e.registrationCeremonyId,stage:`local_publication`,startedAt:w,outcome:`success`}),await rh(e.sessionAuthority),e.authMaterial.kind===`passkey`&&_.remainingUses>0&&(a=oh({signingEngine:e.context.signingEngine,ceremonyId:e.registrationCeremonyId,input:dl({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 k=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,...wm(t,y,_),nearEd25519SigningKeyId:Bt(g.ed25519.nearEd25519SigningKeyId),signerSlot:g.ed25519.signerSlot}),q({ceremonyId:e.registrationCeremonyId,stage:`session_install`,startedAt:k,outcome:`success`});let A=performance.now();if(t.kind===`email_otp`&&_.remainingUses>0){let r=await ol({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=Ap({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:ar(t.emailOtpAuthContext),emailHashHex:cr(t.emailOtpAuthContext),signerSlot:g.ed25519.signerSlot,expectedOperationalPublicKey:c,expectedThresholdSessionId:b.identity.thresholdSessionId,bootstrap:a,material:C,envelope:ma(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 ah({signingEngine:e.context.signingEngine,sessionAuthority:e.sessionAuthority,metadata:x,material:C,materialFacts:b,envelope:ma(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 Tf({walletId:String(e.walletId),credentialIdB64u:e.authMaterial.credentialIdB64u,envelope:n.envelope}),q({ceremonyId:e.registrationCeremonyId,stage:`signer_activation`,startedAt:A,outcome:`success`}),await rh(e.sessionAuthority);let j=performance.now(),M=await a;if(q({ceremonyId:e.registrationCeremonyId,stage:`session_hydration_wait`,startedAt:j,outcome:M.kind===`completed`?`success`:`failure`}),M.kind===`failed`)throw M.error;await rh(e.sessionAuthority);let N=performance.now();return await V.completePendingNearRegistration({pending:d,walletSession:_.walletSession,operationCredential:_.operationCredential,nearAccountId:String(v)}),q({ceremonyId:e.registrationCeremonyId,stage:`durable_ready`,startedAt:N,outcome:`success`}),r=`success`,{status:`near_ready`,updatedAtMs:Date.now(),nearAccountId:String(v)}}catch(t){let n=await V.getProfile(String(e.walletId)).catch(uh);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:_e(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(qm)),i&&Sp(i),q({ceremonyId:e.registrationCeremonyId,stage:`provisioning_total`,startedAt:n,outcome:r}),q({ceremonyId:e.registrationCeremonyId,stage:`registration_total`,startedAt:e.registrationStartedAt,outcome:r})}}async function fh(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:_e(t,`registration`,String(e.walletId)),errorCode:n};try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:n})}catch{}Yd(e.walletId,r);return}await Zd({walletId:e.walletId,nowMs:Date.now,attempt:dh.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 mh(e){let t=ph(e.error),n=_e(e.error,`registration`,String(e.walletId));try{await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_failed_retryable`,errorCode:t})}catch{}return Yd(e.walletId,{status:`near_failed_retryable`,updatedAtMs:Date.now(),error:n,errorCode:t}),{status:`retryable`,error:n,errorCode:t}}async function hh(e){try{return await e.context.signingEngine.setWalletNearProvisioningState({walletId:String(e.walletId),status:`near_pending`}),Yd(e.walletId,{status:`near_pending`,updatedAtMs:Date.now()}),{status:`pending`}}catch(t){return await mh({context:e.context,walletId:e.walletId,error:t})}}async function gh(e){let{context:t,wallet:r,signerSelection:a}=e,o=e.options||{},{onEvent:s,onError:c,afterCall:l}=o,u=performance.now(),d=new ro(u),f=an(),p=null,m=null,h=mm(r.kind===`provided`?String(r.walletId):`wallet-registration`);$(s,h,{authMethod:e.authMethod.kind,phase:B.STEP_01_STARTED,status:`started`});try{let c=lm(`wallet-registration-finalize`),h=await km({completion:`wallet_session`,context:t,authMethod:e.authMethod,wallet:r,signerSelection:a,recorder:d,passkeyExecution:e.passkeyExecution});e.authMethod.kind===`email_otp`&&qp({recorder:d,warmup:h.registrationWarmup});let{relayerUrl:g,setup:_}=h,v=Fm(Im(_,e.kind).ecdsa),y=Am({passkeyExecution:e.passkeyExecution,ceremonyId:_.registrationCeremonyId}),b={intent:_.intent,registrationIntentDigestB64u:_.registrationIntentDigestB64u},x=b.intent.walletId,S=mm(String(x)),C=null,w=``,T=``,E=``,D=null,O=null,k=null,A;if(e.authMethod.kind===`passkey`){$(s,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??o?.confirmationConfig??{}};k=await d.measure(`authProofMs`,()=>Yp({context:t,walletId:x,signerSlot:Lm(e),registrationIntentDigestB64u:b.registrationIntentDigestB64u,options:o,confirmationConfigOverride:n,passkeyExecution:e.passkeyExecution})),d.capturePasskeyAuthDiagnostics(k.diagnostics),p=performance.now();let r=i(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:Fe({rpId:np(e.authMethod.rpId),credentialIdB64u:r.value}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId}),walletCustodyFactorSecret:j(k.prfFirstB64u).buffer},$(s,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 d.measure(`authProofMs`,()=>Xf({authMethod:n,relayUrl:g,walletId:String(x),registrationIntentDigestB64u:b.registrationIntentDigestB64u}));C=um({recorder:d,context:t,authMethod:n,relayerUrl:g,walletId:String(x),providerSubject:i.providerSubject,clientSecret32:r}),w=i.registrationAuthorityId,T=i.email,E=i.providerSubject,D=bm(i.proof),A={kind:`email_otp`,emailOtpRegistrationProof:i.proof,walletCustodyFactorSecret:O}}let M=n(_.walletAuthMethodId);if(!M.ok)throw Error(`Registration setup auth-method identity is invalid: ${M.error.message}`);let N;if(e.authMethod.kind===`passkey`){if(!k)throw Error(`ECDSA registration is missing its verified passkey authority`);N=await Lt({authority:{...nl({walletId:x,rpId:e.authMethod.rpId,credential:k.credential}),bindingId:M.value}})}else{if(!D)throw Error(`Email OTP registration is missing its verified provider`);N=await Lt({authority:{...Et({walletId:x,provider:D,providerUserId:E,emailHashHex:await ym(T)}),bindingId:M.value}})}$(s,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_STARTED,status:`running`});let P={value:e.kind===`near_ed25519_and_evm_family_ecdsa`?A.walletCustodyFactorSecret.slice(0):null},F=null,I={value:null},ee;try{ee=await d.measure(`ecdsaRegistrationTotalMs`,()=>Nm({home:_.home,context:t,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signerPlanKind:e.kind,signedSetup:_.signedSetup,ecdsaPrepare:v,clientCeremony:y,authority:A,materialAuthority:N,idempotencyKey:c,resolveActivateEmailOtp:async()=>{let t=null,n=null;if(e.authMethod.kind===`email_otp`){let e=await rl({material:C,operation:`activate`});t=e.emailOtpEnrollment??null,n=JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Ie({enrollmentId:e.enrollmentId,enrollmentSealKeyVersion:e.enrollmentSealKeyVersion}),walletAuthMethodId:b.intent.foundingWalletAuthMethodId})}return{enrollment:t,walletCustodyFactorJson:n}},traceContext:f,registrationTiming:d,confirmRecoveryCodesBackedUp:bp.bind(void 0,I,t,String(x),o.recoveryCodeBackup),persistPendingCommit:async t=>{let n={operation:`registration_activate`,registrationCeremonyId:_.registrationCeremonyId,idempotencyKey:c,walletId:String(x),walletAuthMethodId:String(b.intent.foundingWalletAuthMethodId),signedSetup:String(_.signedSetup),auth:Rm({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=Vm(up({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial,createdAtMs:e,updatedAtMs:e})),i=rn(r,t.deferredNear.admissionRequest);await V.putPendingWalletRegistrationCommits([r,i]),F=r;return}F=await Bm({...n,signerPlanKind:t.signerPlanKind,localMaterial:t.localMaterial})},startDeferredNearCustody:Jm.bind(void 0,{home:_.home,context:t,factorSecretOwner:P,registrationCeremonyId:_.registrationCeremonyId,relayerUrl:g,signedSetup:String(_.signedSetup),traceContext:f})}))}finally{Sp(A.walletCustodyFactorSecret),P.value&&=(Sp(P.value),null)}if(I.value){let e=ee.activated.walletCustody;if(e?.status!==`committed`)throw Error(`Deferred recovery codes lack a committed server issuance`);await pr.bindIssuedAtMs(I.value,e.issuedAtMs)}let te=ee.session;if(ee.activated.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration activate returned a different signer branch`);let L=sp(ee.activated),ne=ee.activateEmailOtp.enrollment;if(L.kind!==`evm_family_ecdsa`)throw Error(`Wallet registration finalize returned a different signer branch`);if(e.authMethod.kind===`email_otp`&&!zn(L))throw Error(`Email OTP registration finalize returned a different auth method`);d.captureRouteDiagnostics(L.registrationDiagnostics);let re=L.ecdsa.walletKeys;if(re.length===0)throw Error(`Wallet registration finalize did not return ECDSA wallet keys`);let ie=await ap({authMethod:e.authMethod,configs:t.configs,walletId:Ke(L.walletId),finalized:L,passkeyAuthority:k,email:T,providerSubject:E,registrationAuthorityId:w}),R=cp({walletId:Ke(L.walletId),auth:ie,foundingAuthority:L.foundingAuthority,foundingAuthMethod:L.foundingAuthMethod,ecdsa:op({session:te,walletKeys:re,expectedChainTargets:te.chainTargets})});$(s,S,{authMethod:e.authMethod.kind,phase:B.STEP_05_ED25519_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`}),$(s,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let z=Ke(L.walletId),ae={status:`pending`};e.kind===`near_ed25519_and_evm_family_ecdsa`?(await Um({context:t,relayerUrl:g,registrationTiming:d,pending:Vm(F),plan:R,activated:ee.activated}),ae=await hh({context:t,walletId:z})):await _p({context:t,relayerUrl:g,registrationTiming:d,plan:R});let oe=Tn.fromRegistration(g,R.ecdsa.session.registrationEstablishedSession);for(let e of te.chainTargets)Hd({signingEngine:t.signingEngine,walletId:z,chainTarget:e,trigger:`registration`,statusReads:oe});let se=R.ecdsa.walletKeys[0];if(e.authMethod.kind===`passkey`){if(!k)throw Error(`Passkey registration authority was not collected`);let n=R.ecdsa.session.registrationEstablishedSession;try{await Dp({signingEngine:t.signingEngine,commit:ee.walletCustody.commitPayload,passkeyPrfFirstB64u:k.prfFirstB64u,walletId:String(x),walletAuthMethodId:String(R.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(n.walletSessionId),expiresAtMs:n.expiresAtMs})}catch(n){if(e.kind!==`near_ed25519_and_evm_family_ecdsa`)throw n;ae=await mh({context:t,walletId:z,error:n})}}else{if(ie.kind!==`email_otp`||!m)throw Error(`Email OTP registration has no custody capability material`);let e=R.ecdsa.session.registrationEstablishedSession;await Op({context:t,commit:ee.walletCustody.commitPayload,factorSecret32:m,emailOtpAuthContext:ie.emailOtpAuthContext,walletId:String(x),walletSessionId:String(e.walletSessionId),expiresAtMs:e.expiresAtMs})}if(e.kind===`near_ed25519_and_evm_family_ecdsa`){let e=Gm({auth:R.auth,emailOtpEnrollment:ne,passkeyAuthority:k});try{fh({context:t,walletId:z,commit:{context:t,registrationTiming:d,registrationStartedAt:u,relayerUrl:g,registrationCeremonyId:_.registrationCeremonyId,signedSetup:_.signedSetup,headers:Lc(f),nearCustodyWork:th.bind(void 0,ee.deferredNearCustodyWork),sessionAuthority:{record:R.ecdsa.session.registrationEstablishedSession.walletSession,operationCredential:R.ecdsa.session.registrationEstablishedSession.operationCredential},expectedChainTargets:R.ecdsa.expectedChainTargets,walletId:z,authMaterial:e}})}catch(e){let t=ph(e);ae={status:`retryable`,error:_e(e,`registration`,String(z)),errorCode:t},Yd(z,{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:L.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}],nearProvisioning:ae}:{success:!0,kind:`wallet_registered`,walletId:L.walletId,capabilities:[{kind:`evm_family_ecdsa`,thresholdEcdsaEthereumAddress:se.thresholdOwnerAddress,thresholdEcdsaPublicKeyB64u:se.thresholdEcdsaPublicKeyB64u}]};if($(s,S,{authMethod:e.authMethod.kind,phase:B.STEP_08_STORAGE_PERSIST_SUCCEEDED,status:`succeeded`}),$(s,S,{authMethod:e.authMethod.kind,phase:B.STEP_11_COMPLETED,status:`succeeded`}),p!==null){let e=performance.now();co({callback:o.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-p,traceContext:f}),co({callback:o.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:f})}return so(ao({recorder:d,authMethod:e.authMethod.kind,signerSet:za(e.signerPlan)})),xh(e.context,ce,e.authMethod.kind),l?.(!0,ce),ce}catch(t){let n=hm(t),r=_e(t,`registration`,h);p!==null&&co({callback:o.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-p,traceContext:f});let i=gm(r,n);c?.(i),$(s,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 a={success:!1,error:r,...n?{errorCode:n}:{}};return so(oo({recorder:d,authMethod:e.authMethod.kind,signerSet:za(e.signerPlan),errorCode:n||null})),l?.(!1),a}finally{m?.fill(0)}}async function _h(e){let{context:t,options:n}=e,r=mm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),i=new ro(performance.now()),a=null;$(n.onEvent,r,{authMethod:`email_otp`,phase:B.STEP_01_STARTED,status:`started`});try{let r=await Om({completion:`wallet_session`,context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:i});qp({recorder:i,warmup:r.registrationWarmup});let{relayerUrl:o,setup:s}=r,c=s.intent.walletId,l=mm(String(c)),u=await i.measure(`authProofMs`,Xf.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=um({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`,Gn.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:s.signedSetup,headers:{...Lc(),...O(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 rl({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:Ie({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{Sp(f)}let _=await yp(t,String(c),n.recoveryCodeBackup,g.recoveryCodes),v=Le(g.commitPayload);if(!g.localMaterial)throw Error(`Email OTP registration produced no sealed local custody material`);let y=await cm({registrationCeremonyId:s.registrationCeremonyId,activationReference:g.activationReference}),b=await Bm({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:y,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:v,ed25519:{activationReference:g.activationReference,localMaterial:g.localMaterial,metadata:wp(g)}}}),x=`ed25519:${ke(g.metadata.registeredPublicKey)}`,S=await i.measure(`walletRegisterFinalizeMs`,Vn.bind(void 0,{relayerUrl:o,registrationCeremonyId:s.registrationCeremonyId,signedSetup:s.signedSetup,headers:{...Lc(),...O(s.home)},idempotencyKey:y,ed25519:{activationReference:g.activationReference},auth:{kind:`email_otp`,enrollment:h.emailOtpEnrollment},walletCustodyCommit:v}));if(!S.ok)throw Error(`Deferred NEAR provisioning did not complete`);if(i.captureRouteDiagnostics(S.registrationDiagnostics),S.kind!==`near_ed25519`)throw Error(`Wallet registration finalize returned a different signer branch`);if(!zn(S))throw Error(`Email OTP registration finalize returned a different auth method`);if(S.walletCustody?.status!==`committed`){let e=S.walletCustody?.status??`not_reported`;throw Error(`Wallet custody did not commit (${e})`)}if(_&&await pr.bindIssuedAtMs(_,S.walletCustody.issuedAtMs),S.ed25519.signerSlot!==e.ed25519Selection.signerSlot)throw Error(`Ed25519 Yao finalize returned a different signer slot`);let C=Bc(S.registrationEstablishedSession);ll({clientPublicKey:x,finalized:S,expectedRegistrationAuthorityId:u.registrationAuthorityId,expectedWalletId:c});let w=await ap({authMethod:e.authMethod,configs:t.configs,walletId:Ke(S.walletId),finalized:S,passkeyAuthority:null,email:u.email,providerSubject:u.providerSubject,registrationAuthorityId:u.registrationAuthorityId});if(w.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 T=il({admissionRequest:m.ed25519.admissionRequest,finalized:S.ed25519,walletId:c,expectedRuntimePolicyScope:I(s.intent.runtimePolicyScope)}),E=g.metadata,D=je(S.ed25519.nearAccountId),k=Cp({established:g,walletId:String(S.walletId),nearAccountId:String(D),nearEd25519SigningKeyId:S.ed25519.nearEd25519SigningKeyId,signerSlot:S.ed25519.signerSlot}),A=await er({walletId:S.walletId,nearAccountId:D,nearEd25519SigningKeyId:S.ed25519.nearEd25519SigningKeyId,email:w.email,registrationAuthorityId:w.registrationAuthorityId,authority:w.authority,signerSlot:S.ed25519.signerSlot,operationalPublicKey:x,relayerKeyId:S.ed25519.relayerKeyId,keyVersion:S.ed25519.keyVersion,participantIds:[...S.ed25519.participantIds],custodyMaterial:k}),j=await V.publishPendingWalletRegistrationCommit({pending:b,ecdsaContinuity:[],authority:S.authority,foundingAuthority:{authority:S.foundingAuthority,authMethod:S.foundingAuthMethod},request:{operation:`near_provisioning`,registrationCeremonyId:s.registrationCeremonyId,idempotencyKey:y,walletId:S.walletId,walletAuthMethodId:S.foundingAuthMethod.walletAuthMethodId},walletSessionPublication:{kind:`issued`,walletSession:C.walletSession,operationCredential:C.operationCredential},registration:A});Tn.acceptRegistrationSession(o,C);let M=j.signerActivations[1];if(!M||M.signerSlot!==S.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);if(await t.signingEngine.activateAuthenticatedWalletState({walletId:S.walletId,nearAccountId:D,signerSlot:S.ed25519.signerSlot,nearClient:t.nearClient}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:S.walletId,nearAccountId:D,thresholdSessionId:T.identity.thresholdSessionId,runtimePolicyScope:T.stableServerScope.runtimePolicyScope,materialActivation:Mn(E),auth:{kind:`email_otp`,providerSubjectId:u.providerSubject},nearEd25519SigningKeyId:Bt(S.ed25519.nearEd25519SigningKeyId),signerSlot:S.ed25519.signerSlot,remainingUses:C.remainingUses,expiresAtMs:C.expiresAtMs}),!a)throw Error(`Email OTP registration has no custody capability material`);await Op({context:t,commit:v,factorSecret32:a,emailOtpAuthContext:w.emailOtpAuthContext,walletId:String(S.walletId),walletSessionId:String(C.walletSessionId),expiresAtMs:C.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 N={success:!0,kind:`wallet_registered`,walletId:S.walletId,capabilities:[{kind:`near_ed25519`,accountProvisioning:S.accountProvisioning,resolvedAccount:S.resolvedAccount,nearEd25519SigningKeyId:Bt(S.ed25519.nearEd25519SigningKeyId),operationalPublicKey:x,nearAccountId:je(S.ed25519.nearAccountId),transactionId:S.resolvedAccount.kind===`sponsored_named_account`?S.resolvedAccount.transactionHash:null}]};return so(ao({recorder:i,authMethod:`email_otp`,signerSet:za(e.signerPlan)})),xh(t,N,`email_otp`),n.afterCall?.(!0,N),N}catch(t){let a=hm(t),o=_e(t,`registration`,r);n.onError?.(gm(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 so(oo({recorder:i,authMethod:`email_otp`,signerSet:za(e.signerPlan),errorCode:a||null})),n.afterCall?.(!1),s}finally{a?.fill(0)}}function vh(){}async function yh(e){let{context:t,options:n}=e,r=mm(e.wallet.kind===`provided`?String(e.wallet.walletId):`wallet-registration`),a=an(),o=null,s={kind:`none`};$(n.onEvent,r,{authMethod:`passkey`,phase:B.STEP_01_STARTED,status:`started`});try{let r=new ro(performance.now()),{relayerUrl:c,setup:l}=await km({completion:e.completion,context:t,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,recorder:r,passkeyExecution:e.passkeyExecution});r.markNearStage(l.registrationCeremonyId,`near_only.setup`);let u=sl(l.intent),d=mm(String(u.walletId));$(n.onEvent,d,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_create`,overlay:`show`}});let f=l.kind===`near_ed25519`&&l.ed25519.status===`described`?l.ed25519:null,p=Yp({context:t,walletId:u.walletId,signerSlot:e.ed25519Selection.signerSlot,registrationIntentDigestB64u:l.registrationIntentDigestB64u,options:n,confirmationConfigOverride:{uiMode:`modal`,behavior:`requireClick`,...e.confirmationConfigOverride??n.confirmationConfig??{}},passkeyExecution:e.passkeyExecution}).then(e=>(o=performance.now(),r.capturePasskeyAuthDiagnostics(e.diagnostics),r.markNearStage(l.registrationCeremonyId,`near_only.authentication`),$(n.onEvent,d,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_create`,overlay:`hide`}}),e)),m=vm(n.onEvent,d,B.STEP_05_ED25519_SIGNER_PROVISION_DELAYED),h=async(e,t)=>{let n=await m(Gn({relayerUrl:c,registrationCeremonyId:l.registrationCeremonyId,signerPlanKind:`near_ed25519`,signedSetup:l.signedSetup,headers:{...Lc(a),...O(l.home)},kind:`passkey`,webauthnRegistration:e.webauthnRegistration,...t?{ed25519Execution:t}:{},onServerTiming:Oa.bind(void 0,r)}));if(r.markNearStage(l.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=i(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=>(_=j(t.prfFirstB64u).buffer,{factorJson:JSON.stringify({envelopeId:`wallet-custody-envelope:${crypto.randomUUID()}`,factor:Fe({rpId:np(e.authMethod.rpId),credentialIdB64u:g(t)}),walletAuthMethodId:l.intent.foundingWalletAuthMethodId}),factorSecret:_}),y=Ih.bind(null,t.signingEngine,l.registrationCeremonyId,e.completion),b=e=>({home:l.home,walletId:String(u.walletId),nearEd25519SigningKeyId:e.admissionRequest.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:l.registrationCeremonyId,admissionRequest:e.admissionRequest,admissionReceipt:e.admissionReceipt,participantIds:e.admissionRequest.participant_ids,routerOrigin:new URL(c).origin,authorization:`Bearer ${String(l.signedSetup)}`,traceContext:a}),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(!tt(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(vh),x=await p,s=y(x,f.admissionRequest.scope.threshold_session_id),C=await m(e)}else x=await p,S=await h(x),s=y(x,S.admissionRequest.scope.threshold_session_id),C=await m(t.signingEngine.establishWalletCustodyNearEd25519KeySet({...b(S),factor:v(x)}))}finally{_&&Sp(_)}let w={value:g(x)};r.markNearStage(l.registrationCeremonyId,`near_only.custody`);let T=await yp(t,String(u.walletId),n.recoveryCodeBackup,C.recoveryCodes),E=Le(C.commitPayload);if(!C.localMaterial)throw Error(`Passkey registration produced no sealed local custody material`);let D=await cm({registrationCeremonyId:l.registrationCeremonyId,activationReference:C.activationReference}),k=await Bm({operation:`near_provisioning`,completion:{kind:`sealed_material`},signerPlanKind:`near_ed25519`,registrationCeremonyId:l.registrationCeremonyId,idempotencyKey:D,walletId:String(u.walletId),walletAuthMethodId:String(l.intent.foundingWalletAuthMethodId),signedSetup:String(l.signedSetup),auth:{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:w.value,transports:[...x.webauthnRegistration.response.transports]},localMaterial:{keyFamilies:[`ed25519`],custodyCommit:E,ed25519:{activationReference:C.activationReference,localMaterial:C.localMaterial,metadata:wp(C)}}});if(k.operation!==`near_provisioning`||k.phase!==`joined`)throw Error(`Invalid pending owner registration branch`);let A=`ed25519:${ke(C.metadata.registeredPublicKey)}`;r.markNearStage(l.registrationCeremonyId,`near_only.provision_checkpoint`);let M=null;if(e.completion===`wallet_session`){if(s.kind!==`preparing`)throw Error(`NEAR registration session seal preparation is missing`);let e=await s.result;if(e.kind===`failed`)throw e.error;let n=await t.signingEngine.readPreparedSigningSessionHydration({thresholdSessionId:s.thresholdSessionId,preparationId:s.preparationId});M={thresholdSessionId:s.thresholdSessionId,ciphertext:n.ciphertext}}let N=await vm(n.onEvent,d,B.STEP_06_RELAY_BOOTSTRAP_DELAYED)(Vn({relayerUrl:c,registrationCeremonyId:l.registrationCeremonyId,signedSetup:l.signedSetup,headers:{...Lc(a),...O(l.home)},idempotencyKey:D,ed25519:{activationReference:C.activationReference},auth:{kind:`passkey`},...M?{sessionSeal:M}:{},walletCustodyCommit:E}));if(r.markNearStage(l.registrationCeremonyId,`near_only.finalize`),!N.ok||N.kind!==`near_ed25519`)throw Error(`Deferred NEAR provisioning returned a different signer branch`);if(e.completion===`wallet_session`&&!N.sessionSeal)throw Error(`NEAR finalization did not return the prepared session seal`);if(C.commitPayload&&N.walletCustody?.status!==`committed`){let e=N.walletCustody?.status??`not_reported`,t=N.walletCustody?.status===`rejected`?`: ${N.walletCustody.reason}`:``;throw Error(`Wallet custody did not commit (${e})${t}. The recovery codes shown are not usable.`)}if(T){if(N.walletCustody?.status!==`committed`)throw Error(`Deferred recovery codes lack a committed server issuance`);await pr.bindIssuedAtMs(T,N.walletCustody.issuedAtMs)}let P=cl({clientPublicKey:A,finalized:N,expectedRpId:e.authMethod.rpId,expectedWalletId:u.walletId}),F=je(N.ed25519.nearAccountId),ee=rp({finalized:N,credential:x.credential}),te=il({admissionRequest:S.admissionRequest,finalized:N.ed25519,walletId:u.walletId,expectedRuntimePolicyScope:I(u.runtimePolicyScope)}),L=C.metadata,ne=Cp({established:C,walletId:String(N.walletId),nearAccountId:String(F),nearEd25519SigningKeyId:N.ed25519.nearEd25519SigningKeyId,signerSlot:N.ed25519.signerSlot});await kp({commit:C.commitPayload,walletId:String(N.walletId),activatedAtMs:Date.now()}),await t.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:N.walletId,nearAccountId:je(N.ed25519.nearAccountId),thresholdSessionId:te.identity.thresholdSessionId,runtimePolicyScope:te.stableServerScope.runtimePolicyScope,materialActivation:Mn(L),auth:{kind:`passkey`,rpId:Sn(P.rpId),credentialIdB64u:P.credentialIdB64u},nearEd25519SigningKeyId:Bt(N.ed25519.nearEd25519SigningKeyId),signerSlot:N.ed25519.signerSlot});let re=$n({walletId:N.walletId,nearAccountId:F,nearEd25519SigningKeyId:N.ed25519.nearEd25519SigningKeyId,rpId:np(P.rpId),credential:x.credential,credentialPublicKeyB64u:ee,signerSlot:N.ed25519.signerSlot,operationalPublicKey:A,relayerKeyId:N.ed25519.relayerKeyId,keyVersion:N.ed25519.keyVersion,participantIds:[...N.ed25519.participantIds],custodyMaterial:ne});if(e.completion===`owner_operations`){if(N.registrationEstablishedSession.kind!==`owner_operations`)throw Error(`Owner onboarding unexpectedly issued a Wallet Session`);let e=await ba({registration:re,metadata:L,material:ne,materialFacts:te,envelope:Tp(C.commitPayload),ownedFactorSecret:j(x.prfFirstB64u),rpId:P.rpId,credentialIdB64u:P.credentialIdB64u,passkeyPrfFirstB64u:x.prfFirstB64u});await V.publishPendingWalletRegistrationCommit(xd(k,N,e));let t={success:!0,kind:`wallet_owner_registered`,walletId:N.walletId,capabilities:[Lh(N,A)]};return $(n.onEvent,d,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),n.afterCall?.(!0,t),t}let ie=Bc(N.registrationEstablishedSession),R=await V.publishPendingWalletRegistrationCommit(xd(k,N,re));Tn.acceptRegistrationSession(c,ie);let z=R.signerActivations[1];if(!z||z.signerSlot!==N.ed25519.signerSlot)throw Error(`Ed25519 Yao registration persisted a different signer slot`);if(r.markNearStage(l.registrationCeremonyId,`near_only.publication`),s.kind!==`preparing`||!N.sessionSeal)throw Error(`Registration session seal is unavailable`);let ae=await oh({signingEngine:t.signingEngine,ceremonyId:l.registrationCeremonyId,input:dl({session:ie,ceremonyId:l.registrationCeremonyId,walletId:String(N.walletId),relayerUrl:c,prfFirstB64u:x.prfFirstB64u,preparedServerSeal:{preparationId:s.preparationId,...N.sessionSeal},restore:{rpId:P.rpId,nearAccountId:String(F),nearEd25519SigningKeyId:N.ed25519.nearEd25519SigningKeyId,relayerKeyId:N.ed25519.relayerKeyId,participantIds:N.ed25519.participantIds,signerSlot:N.ed25519.signerSlot,credentialIdB64u:P.credentialIdB64u,materialActivation:Mn(L)}})});if(ae.kind===`failed`)throw ae.error;if(s={kind:`consumed`},r.markNearStage(l.registrationCeremonyId,`near_only.session_hydration`),await ah({signingEngine:t.signingEngine,sessionAuthority:{record:ie.walletSession,operationCredential:ie.operationCredential},metadata:L,material:ne,materialFacts:te,envelope:Tp(C.commitPayload),ownedFactorSecret:j(x.prfFirstB64u),rpId:P.rpId,credentialIdB64u:P.credentialIdB64u,passkeyPrfFirstB64u:x.prfFirstB64u,relayerUrl:c}),r.markNearStage(l.registrationCeremonyId,`near_only.material_activation`),await Dp({signingEngine:t.signingEngine,commit:C.commitPayload,passkeyPrfFirstB64u:x.prfFirstB64u,walletId:String(N.walletId),walletAuthMethodId:String(N.foundingAuthMethod.walletAuthMethodId),walletSessionId:String(ie.walletSessionId),expiresAtMs:ie.expiresAtMs}),r.markNearStage(l.registrationCeremonyId,`near_only.export_capability`),await t.signingEngine.activateAuthenticatedWalletState({walletId:N.walletId,nearAccountId:F,signerSlot:N.ed25519.signerSlot,nearClient:t.nearClient}),$(n.onEvent,d,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),o!==null){let e=performance.now();co({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`success`,durationMs:e-o,traceContext:a}),co({callback:n.onTimingSpan,span:`frontend.wallet_ready`,outcome:`success`,durationMs:0,traceContext:a})}r.markNearStage(l.registrationCeremonyId,`near_only.wallet_ready`),so(ao({recorder:r,authMethod:`passkey`,signerSet:za(e.signerPlan)}));let oe={success:!0,kind:`wallet_registered`,walletId:N.walletId,capabilities:[Lh(N,A)]};return xh(t,oe,`passkey`),n.afterCall?.(!0,oe),oe}catch(e){let t=hm(e),i=_e(e,`registration`,r);o!==null&&co({callback:n.onTimingSpan,span:`registration.post_touch_id`,outcome:`failure`,durationMs:performance.now()-o,traceContext:a}),n.onError?.(gm(i,t)),$(n.onEvent,r,{authMethod:`passkey`,phase:B.FAILED,status:`failed`,message:i,interaction:{kind:`passkey_create`,overlay:`hide`},error:{...t?{code:t}:{},message:i}});let s={success:!1,error:i,...t?{errorCode:t}:{}};return n.afterCall?.(!1),s}finally{s.kind===`preparing`&&(await s.result,await t.signingEngine.discardSigningSessionHydration({thresholdSessionId:s.thresholdSessionId,preparationId:s.preparationId}).catch(qm))}}async function bh(e){let t=Np(e.signerSelection),n=_n(t);if(e.completion===`owner_operations`&&(e.authMethod.kind!==`passkey`||!n||gn(t)))throw Error(`Owner-operation onboarding requires a NEAR-only wallet and a wallet-origin passkey.`);if(n){let r=gn(t);if(r)return await gh({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 _h({context:e.context,authMethod:e.authMethod,wallet:e.wallet,signerSelection:e.signerSelection,signerPlan:t,ed25519Selection:n,options:e.options,passkeyExecution:e.passkeyExecution})}return await yh({completion:e.completion,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=gn(t);if(!r)throw Error(`Wallet registration requires an ECDSA signer branch`);return await gh({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 xh(e,t,n){e.signingEngine.setWalletAuthenticated({kind:`authenticated`,walletId:t.walletId,authMethod:n})}async function Sh(e){try{return await bh({completion:e.completion,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 Ch(e,t,n){try{$(e,t,n)}catch{}}function wh(e,t){try{e?.(t)}catch{}}function Th(e,t,n){try{t&&n?e?.(!0,n):e?.(!1)}catch{}}function Eh(e){let t=[];for(let n of e){let e=String(n.credentialId||``).trim();e&&t.push({id:e,type:`public-key`,transports:_m(n.transports)})}if(t.length===0)throw Error(`Wallet add-signer requires an existing passkey credential`);return t}function Dh(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 Oh(e){if(e.started.intent.walletId!==e.walletId)throw Error(`Wallet add-signer start returned a different wallet`);if(await Cr(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 kh(e,t){return e.length===2&&t.length===2&&e[0]===t[0]&&e[1]===t[1]}function Ah(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=Ae(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||!kh(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 jh(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 Mh(e){if(e.started.intent.signerSelection.mode!==`ed25519`)throw Error(`Wallet add-signer start returned a different signer branch`);let n=null,r=null,i=null;try{if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody Ed25519 add-signer requires WebAuthn authorization`);let a=await tp({kind:`verified_passkey_ed25519_yao_add_signer_input_v1`,verifiedIntent:{kind:`verified_passkey_ed25519_add_signer_intent_v1`,intent:jh(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}}),o=Ic(e.started.ed25519.custodyEnvelope);if(!o.ok)throw Error(o.reason);i=Uint8Array.from(j(e.passkeyPrfFirstB64u)).buffer;let s=await e.context.signingEngine.joinWalletCustodyNearEd25519KeySet({routing:{kind:`discovery`},preparation:{kind:`fresh`},custodyJson:o.custodyJson,factorSecret:i,nearEd25519SigningKeyId:a.request.application_binding.near_ed25519_signing_key_id,registrationCeremonyId:e.started.addSignerCeremonyId,admissionRequest:a.request,admissionReceipt:a.receipt,participantIds:a.request.participant_ids,routerOrigin:new URL(e.relayerUrl).origin,authorization:`Bearer ${String(e.intentResponse.addSignerIntentGrant)}`}),c=`ed25519:${ke(s.metadata.registeredPublicKey)}`,l=await Fn({relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:lm(`wallet-ed25519-add-signer-finalize`),kind:`near_ed25519`,ed25519:{activationReference:s.activationReference},custodyKeySet:{kind:`near_ed25519_v1`,keyManifestDigestB64u:s.commitPayload.keyManifestDigestB64u,registeredPublicKeyB64u:A(s.metadata.registeredPublicKey)}});if(l.kind!==`near_ed25519`)throw Error(`Wallet add-signer finalize returned a different signer branch`);let u=Ah({finalized:l,started:e.started,walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u,clientPublicKey:c});Ch(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:je(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`);n=d.rollbackReceipt;let f=e.started.ed25519.admissionRequest,p=t(f.scope.threshold_session_id);if(!p.ok)throw Error(`Wallet add-signer threshold-session identity is invalid`);let m=s.metadata;return await e.context.signingEngine.persistWalletCustodyEd25519Material({binding:{kind:Zn,applicationBindingDigestB64u:s.localMaterial.applicationBindingDigestB64u,registeredPublicKeyB64u:A(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:A(m.signingWorkerVerifyingShare)},sealed:{ciphertextB64u:s.localMaterial.b64u,nonceB64u:s.localMaterial.nonceB64u}}),r={nearAccountId:u.ed25519.nearAccountId,signerSlot:u.ed25519.signerSlot},await e.context.signingEngine.upsertEd25519YaoPublicCapabilityLaneReference({walletId:u.walletId,nearAccountId:je(u.ed25519.nearAccountId),thresholdSessionId:p.value,runtimePolicyScope:I(e.started.intent.runtimePolicyScope),materialActivation:Mn(m),auth:{kind:`passkey`,rpId:Sn(e.rpId),credentialIdB64u:e.credentialIdB64u},nearEd25519SigningKeyId:Bt(u.ed25519.nearEd25519SigningKeyId),signerSlot:u.ed25519.signerSlot}),n=null,Ch(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:Bt(u.ed25519.nearEd25519SigningKeyId),operationalPublicKey:c,nearAccountId:je(u.ed25519.nearAccountId)}]}}catch(t){let i=[];if(r)try{await e.context.signingEngine.deleteWalletCustodyEd25519Material({nearAccountId:r.nearAccountId,signerSlot:r.signerSlot})}catch(e){i.push(e instanceof Error?e.message:String(e))}if(n)try{await e.context.signingEngine.rollbackWalletEd25519SignerRegistration(n)}catch(e){i.push(e instanceof Error?e.message:String(e))}if(i.length>0){let e=t instanceof Error?t.message:String(t);throw Error(`${e}; add-signer cleanup failed: ${i.join(`; `)}`)}throw t}finally{i&&Sp(i)}}async function Nh(e){if(e.started.authorizationKind!==`webauthn_assertion`)throw Error(`Wallet custody ECDSA add-signer requires WebAuthn authorization`);let t=await rf({walletId:e.walletId,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u}),n=Uint8Array.from(j(e.passkeyPrfFirstB64u)).buffer,r;try{r=await Xc({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{Sp(n)}let i={relayerUrl:e.relayerUrl,walletId:e.walletId,addSignerCeremonyId:e.started.addSignerCeremonyId,idempotencyKey:lm(`wallet-add-signer-finalize`),kind:`evm_family_ecdsa`,ecdsa:{expectedKeyHandles:[r.bootstrap.keyHandle]},custodyKeySet:r.custodyKeySet},a;try{a=await Fn(i)}catch(e){if(!(e instanceof TypeError))throw e;a=await Fn(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 Zc({context:e.context,pending:r});Ch(e.onEvent,e.eventAccountId,{authMethod:`passkey`,phase:B.STEP_08_STORAGE_PERSIST_STARTED,status:`running`});let l=await e.context.signingEngine.finalizeWalletRegistrationEcdsaSessions({walletId:Ke(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}),Ch(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 Ph(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 Mh({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 Nh({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 J(e.signerSelection)}}async function Fh(e){let{context:t,signerSelection:n}=e,r=e.options||{},i=Ut(String(e.walletId||``).trim()),a=mm(String(i)),o=np(String(e.rpId||``).trim());Ch(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=Qd(t.configs);if(!s)throw Error(`addSigner requires registration.publishableKey and registration.projectEnvironmentId`);let c=await Pn({relayerUrl:e,walletId:i,request:{walletId:i,rpId:o,signerSelection:n},auth:{publishableKey:s.publishableKey,environmentId:s.projectEnvironmentId}});if(await Cr(c.intent)!==c.addSignerIntentDigestB64u)throw Error(`Add-signer intent digest mismatch`);Ch(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_STARTED,status:`waiting_for_user`,interaction:{kind:`passkey_assert`,overlay:`show`}});let l=Eh(await V.listProfileAuthenticators(String(i))),u=await t.signingEngine.getAuthenticationCredentialsSerialized({subjectId:String(i),challengeB64u:c.addSignerIntentDigestB64u,allowCredentials:l,includeSecondPrfOutput:!1}),d=Dh(u,l),f=fr(u,`Wallet add-signer authorization`);Ch(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_04_PASSKEY_CREATE_SUCCEEDED,status:`succeeded`,interaction:{kind:`passkey_assert`,overlay:`hide`}});let p=await kn({relayerUrl:e,walletId:i,addSignerIntentGrant:c.addSignerIntentGrant,addSignerIntentDigestB64u:c.addSignerIntentDigestB64u,intent:c.intent,auth:{kind:`webauthn_assertion`,rpId:o,credential:Xn(u),expectedChallengeDigestB64u:c.addSignerIntentDigestB64u}});await Oh({started:p,walletId:i,expectedDigestB64u:c.addSignerIntentDigestB64u});let m=await Ph({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 Ch(r.onEvent,a,{authMethod:`passkey`,phase:B.STEP_11_COMPLETED,status:`succeeded`}),Th(r.afterCall,!0,m),m}catch(e){let t=hm(e),n=_e(e,`registration`,a);wh(r.onError,gm(n,t)),Ch(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 Th(r.afterCall,!1),i}}function Ih(e,t,n,r,i){return n===`owner_operations`?{kind:`none`}:ch({signingEngine:e,ceremonyId:t,thresholdSessionId:i,prfFirstB64u:r.prfFirstB64u})}function Lh(e,t){return{kind:`near_ed25519`,accountProvisioning:e.accountProvisioning,resolvedAccount:e.resolvedAccount,nearEd25519SigningKeyId:Bt(e.ed25519.nearEd25519SigningKeyId),operationalPublicKey:t,nearAccountId:je(e.ed25519.nearAccountId),transactionId:e.resolvedAccount.kind===`sponsored_named_account`?e.resolvedAccount.transactionHash:null}}export{Zl as $,Md as A,qs as At,Du as B,ga as Bt,qd as C,Qs as Ct,Fd as D,zs as Dt,Id as E,Vs as Et,Yu as F,po as Ft,vu as G,ta as Gt,Tu as H,ma as Ht,Ju as I,mo as It,xu as J,Pi as Jt,yu as K,la as Kt,Pu as L,Sa as Lt,kd as M,fs as Mt,Ad as N,jo as Nt,Pd as O,tc as Ot,Dd as P,bo as Pt,Jl as Q,Lu as R,Ca as Rt,Jd as S,ec as St,Hd as T,Hs as Tt,wu as U,Ui as Ut,Su as V,pa as Vt,Eu as W,ua as Wt,pu as X,ji as Xt,gu as Y,ei as Yt,Xl as Z,wi as Zt,lf as _,lc as _t,Sh as a,Fl as at,$d as b,bc as bt,Xf as c,el as ct,yf as d,Dc as dt,uu as et,Ef as f,Ec as ft,nf as g,dc as gt,rf as h,Nc as ht,sm as i,du as it,Nd as j,Ws as jt,Vd as k,Js as kt,qf as l,Ic as lt,df as m,Oc as mt,am as n,lu as nt,vp as o,Ll as ot,Tf as p,kc as pt,_u as q,na as qt,im as r,tu as rt,om as s,Il as st,Fh as t,eu as tt,Wf as u,Tc as ut,of as v,cc as vt,Xd as w,Us as wt,Qd as x,Sc as xt,cf as y,gc as yt,Iu as z,_a as zt};