@particle-network/authkit
Version:
Auth Core provides MPC (Multi-Party Computation)-based threshold signatures.
13 lines (10 loc) • 10.9 kB
JavaScript
"use client";
import{Q as z,R as ae,S as re,W as se,X as ce,a as T,aa as v,b as ne,ba as le,f as q,j as N,k as ie,l as $,p as G,ta as ue,va as pe}from"./chunk-H6TXMQRA.mjs";import{EvmRpcMethod as xe,getEVMChainInfoById as Ue,getSmartAccountAddress as Ve,tronAddressFromHex as ke}from"@particle-network/auth-core";var de=async({chainId:o,erc4337:t,method:p})=>{var c,m;let s=o||Number((c=window.particleAuth)==null?void 0:c.ethereum.chainId),r;return t&&p!==xe.ethSendTransaction?r=await Ve(t):typeof window!="undefined"&&(r=(m=window.particleAuth)==null?void 0:m.ethereum.selectedAddress),le(Ue(s))&&(r=ke(r)),r||""};import B,{Suspense as rt,useEffect as st,useState as ct}from"react";import{AuthCoreEvent as E,connect as Qe,EvmRpcMethod as we,getConnectCaptcha as Xe,getUserInfo as Q,hasPaymentPassword as Ye,isConnected as ye,particleAuth as Ae,SolanaRpcMethod as Ze,syncUserInfo as et}from"@particle-network/auth-core";import tt from"ahooks/es/useAsyncEffect";import X from"ahooks/es/useSetState";import ot from"ahooks/es/useSize";import nt from"bs58";import{EventEmitter as it}from"events";import Y,{useCallback as Z,useEffect as S,useRef as Se,useState as g}from"react";import{getLatestAuthType as qe,getUserInfo as Ne,isNullish as K,requireNotNullish as je}from"@particle-network/auth-core";import De from"bs58";import{v4 as We}from"uuid";var Be=`{0} wants you to sign in with your Ethereum account:
{1}
{2}
URI: https://{3}/
Version: 1
Chain ID: {4}
Nonce: {5}
Issued At: {6}
Expiration Time: {7}`,Fe={isNeedAuthorize({authorization:o,chain:t}){return o?t.name.toLowerCase()==="solana"?"message"in o&&!K(o.message)&&"uniq"in o&&!K(o.uniq):"uniq"in o&&!K(o.uniq):!1},async generateMessage(o,t){var C;let p=location.host,s=Ne(),r=v(o)?(C=window.particleAuth)==null?void 0:C.solana.selectedAddress:await de({...t,chainId:o.id}),c=qe()||"email",m=s[c]||s[`${c}_email`]||ne(s[`${c}_id`]),l=`${c.titleCase()}: ${m}`,y=We().replace(/-/g,""),M=new Date().toISOString(),b=new Date(Date.now()+10*60*1e3).toISOString();return Be.format(p,r||"",l,p,o.id.toString(),y,M,b)},async authorize({authorization:o,chain:t},p){let s=v(t)?o.message:q(await this.generateMessage(t,p)),r=je(window.particleAuth),c;if(v(t)){let{signature:m}=await r.solana.signMessage(De.decode(s));c=Buffer.from(m).toString("base64")}else c=await r.ethereum.signMessage(s);return{message:s,signature:c}}},j=Fe;import{AuthCoreEvent as D,hasMasterPassword as He,hasPaymentPassword as $e,particleAuth as W}from"@particle-network/auth-core";import fe,{useCallback as Ge,useEffect as J,useRef as Ke}from"react";import me from"base64url";var he=()=>{let o=Object.fromEntries(new URLSearchParams(z()?"":window.location.search)),t=o==null?void 0:o.particleThirdpartyParams;if(t){let p=JSON.parse(me.decode(t)),{appState:s,error:r}=p,c=s?JSON.parse(me.decode(s)):{},{purpose:m}=c;return Boolean(!r)&&m!=="bindLoginAccount"}return!1};var Je=({children:o})=>{let{provider:t}=ue(),{userInfo:p}=$(),{wallet:s}=pe(),{connect:r}=ce(),c=Ke(!1),{modalOptions:m}=G(),{needRestoreWallet:l,openAccountAndSecurity:y,openSetMasterPassword:M,openChangeMasterPassword:b,openRestoreByMasterPassword:C,openSetPaymentPassword:_,openChangePaymentPassword:x,openSetSecurityAccount:U,openLinkLoginAccount:V}=se();if(ae()&&!c.current){window.particle?(window.particle.ethereum=t,window.particle.solana=s):window.particle={ethereum:t,solana:s},c.current=!0;let f=he();window.particle.ethereum.isSocialConnecting=f,window.particle.solana.isSocialConnecting=f,window.dispatchEvent(new CustomEvent("particle:authProviderInjected"))}J(()=>{let f=({resolve:P,reject:F,param:H})=>{r(H).then(L=>{P(L)}).catch(L=>{F(L)})};return W.on(D.RequestEthereumAccount,f),W.on(D.RequestSolanaAccount,f),()=>{W.off(D.RequestEthereumAccount,f),W.off(D.RequestSolanaAccount,f)}},[r]);let k=Ge(()=>p,[p]);return J(()=>{window.particle&&(window.particle._internal={needRestoreWallet:l,openAccountAndSecurity:y,openSetMasterPassword:M,openChangeMasterPassword:b,openRestoreByMasterPassword:C,openSetPaymentPassword:_,openChangePaymentPassword:x,openSetSecurityAccount:U,openLinkLoginAccount:V,hasMasterPassword:He,hasPaymentPassword:$e,getUserInfo:k})},[l,y,M,b,C,_,x,U,V,k]),J(()=>{if(t&&typeof window!="undefined"&&m.supportEIP6963!==!1){let f={uuid:"cf589558-848b-4b1b-9ee7-800b5bbc07da",name:"Particle Auth",icon:"https://static.particle.network/logo-small.png",rdns:"network.particle"},P=()=>{window.dispatchEvent(new CustomEvent("eip6963:announceProvider",{detail:Object.freeze({provider:t,info:f})}))};return window.addEventListener("eip6963:requestProvider",P),P(),()=>{window.removeEventListener("eip6963:requestProvider",P)}}},[t,m.supportEIP6963]),fe.createElement(fe.Fragment,null,o)},ge=Je;var at=o=>new Function("id","return import(id)")(o),h=new it;h.setMaxListeners(100);var Ce=o=>{let[t,p]=g(),s=Se(t),r=e=>{p(e),s.current=e},[c,m]=g("en"),[l,y]=X(o.options),[M,b]=g(!1),[C,_]=g(),[x,U]=g({visible:!1}),[V,k]=g({visible:!1}),f=Y.useRef(!1),[P,F]=g({visible:!1}),[H,L]=g(),ee=Se(null),Pe=e=>{L(e),ee.current=e},[Me,be]=g("loading"),te=(e,i)=>{_(i),b(e)},ve=e=>{k(e)},[u,I]=X({path:"/"}),[R,A]=X({viewType:"mobile",particleModalVisible:!1,rootModalContainer:null,rootBody:null,closable:!0}),w=Z((e,i)=>{typeof e=="string"&&e!=="/"&&(e=e.replace(/^\//,""));let{history:a}=u;if(a||(a=[]),(i==null?void 0:i.back)===!0&&typeof e=="string"&&!!a.find(n=>n.path.replace(/^\//,"")===e.replace(/^\//,""))&&(e=a.findIndex(n=>n.path===e)-a.length+1),typeof e=="string"){if(e!=="login"&&e!=="index"&&!ye())throw T.notLogin();let{replace:n=!1,state:d={}}=i||{};a.length&&n&&a.pop(),a.push({path:e,state:d,updateAt:new Date().getTime()}),I({path:e,replace:n,state:d,history:a})}else if(typeof e=="number"&&a.length>0){for(let d=0;d<Math.abs(e);d++)a.pop();if(a.length===0){A({particleModalVisible:!1});return}let n=a[a.length-1];I({path:n==null?void 0:n.path,replace:!1,state:n==null?void 0:n.state,history:a})}},[u,A,I]),Ee=Z(()=>{var e,i,a,n,d,O,oe;if(!((e=t==null?void 0:t.security_account)!=null&&e.has_set_payment_password)){if(!((i=t==null?void 0:t.security_account)!=null&&i.email)&&!((a=t==null?void 0:t.security_account)!=null&&a.phone)){w("/account/bind",{state:{accountType:t!=null&&t.email?"phone":"email",showSwitch:!0,redirectUrl:"/account/set-password"}});return}((n=t==null?void 0:t.security_account)==null?void 0:n.email)&&((d=t==null?void 0:t.security_account)==null?void 0:d.phone)?te(!0):w("/account/set-password",{state:{account:((O=t==null?void 0:t.security_account)==null?void 0:O.email)||((oe=t==null?void 0:t.security_account)==null?void 0:oe.phone)}})}},[t,w]),Le=Z(()=>{let e=s.current,i=ee.current,a;if(i&&j.isNeedAuthorize(i))if(Ye()){if(v(i.chain)){let n=i.authorization.message;w("solana/sign",{state:{method:Ze.signMessage,param:nt.decode(n),loginAuthorizationSign:!0}})}else j.generateMessage(i.chain,l.erc4337).then(n=>{w("evm-chain/sign",{state:{method:i.authorization.uniq?we.personalSignUniq:we.personalSign,param:q(n),loginAuthorizationSign:!0}})}).catch(n=>{h.emit("loginFail",n)});return}else j.authorize(i,l.erc4337).then(n=>{h.emit("loginSuccess",{...e,authorization:n})}).catch(n=>{h.emit("loginFail",n)});else h.emit("loginSuccess",{...e!=null?e:Q(),authorization:a})},[w,t,l.erc4337,H]),Ie=()=>{h.listenerCount("signResponse")>0&&h.emit("signResponse",{error:T.userRejectedRequest()}),h.listenerCount("loginSuccess")&&((u==null?void 0:u.path)==="login"||!t?h.emit("loginFail",T.userCancelOperation()):h.emit("loginSuccess",t)),A({particleModalVisible:!1})};S(()=>{y({...N,...o.options,promptSettingConfig:{...N.promptSettingConfig,...o.options.promptSettingConfig},customStyle:{...N.customStyle,...o.options.customStyle}})},[o.options,y]),S(()=>{if(!document.querySelector(".particle-auth-core-body-style")){let e=document.createElement("style");e.classList.add("particle-auth-core-body-style"),e.innerHTML=".particle-modal-lock { overflow: hidden !important; }",document.head.appendChild(e)}R.particleModalVisible?(document.body.classList.add("particle-modal-lock"),setTimeout(()=>{var i;let e=(i=R.rootModalContainer)==null?void 0:i.querySelector(".p-modal-body");A({rootBody:e})},100)):(setTimeout(()=>{I({path:"/",history:[]})},100),document.body.classList.remove("particle-modal-lock"))},[R.particleModalVisible,R.rootModalContainer]);let Re=ot(z()?null:document.body);if(S(()=>{let e="mobile";document.body.clientWidth>=600&&(e="desktop"),A({viewType:e})},[Re]),S(()=>{(u==null?void 0:u.path)&&(u==null?void 0:u.path)!="/"&&A({particleModalVisible:!0})},[u==null?void 0:u.path]),S(()=>{setTimeout(()=>{m(l.language||"en")})},[l.language]),S(()=>{var i;let e=()=>{w("account/master-password/verify")};return(i=window==null?void 0:window.particleAuth)==null||i.on(E.MasterPasswordChanged,e),()=>{var a;(a=window==null?void 0:window.particleAuth)==null||a.off(E.MasterPasswordChanged,e)}},[u.history,w]),S(()=>{var a,n;let e=d=>{r(d)},i=d=>{r(void 0),h.listenerCount("signResponse")>0&&h.emit("signResponse",{error:d||T.notLogin()}),A({particleModalVisible:!1})};return(a=window==null?void 0:window.particleAuth)==null||a.on(E.UserInfoChanged,e),(n=window==null?void 0:window.particleAuth)==null||n.on(E.ParticleAuthDisconnect,i),()=>{var d,O;(d=window==null?void 0:window.particleAuth)==null||d.off(E.UserInfoChanged,e),(O=window==null?void 0:window.particleAuth)==null||O.off(E.ParticleAuthDisconnect,i)}},[]),!f.current||Ae.chains!=l.chains){Ae.init({projectId:l.projectId||o.options.projectId,clientKey:l.clientKey||o.options.clientKey,appId:l.appId||o.options.appId,chains:l.chains});let e=Q();if(r(e),f.current=!0,e){let{token:i="",...a}=e;re("open",a)}}S(()=>{var e;if(ye()&&et().catch(i=>{}),!((e=o==null?void 0:o.options)!=null&&e.chains.length))throw new Error("Auth Core: Please set chains in options")},[]),z()||(window.__getConnectCaptcha=Xe,window.__connect=Qe,window.__getUserInfo=Q,window.__navigate=w);let[Oe,Te]=g(),[ze,_e]=g();return tt(async()=>{if(l.wallet!==!1)try{let e=await at("@particle-network/wallet");_e(e==null?void 0:e.walletEntryPlugin)}catch{}},[l.wallet]),Y.createElement(ie.Provider,{value:{connectionStatus:Me,setConnectionStatus:be,userInfo:t,modalOptions:l,setModalOptions:y,showSelectSecurityAccount:te,selectSecurityAccount:M,verifySecurityAccountState:C,setWrongPassword:U,wrongPassword:x,setPaymentVerify:F,paymentVerify:P,showAccountTipModal:ve,accountTipModal:V,setPaymentPassword:Ee,loginSuccessRedirectToApp:Le,events:h,authCoreModal:R,setAuthCoreModal:A,customRouter:u,setCustomRouter:I,customNavigate:w,setLoginAuthorization:Pe,authCoreModalClose:Ie,socialConnectCallback:Oe,setSocialConnectCallback:Te,walletEntryPlugin:ze,lang:c,setLang:m}},Y.createElement(ge,null,o.children))};var lt=B.lazy(()=>import("./AuthCoreUI-DOLIMBBU.mjs")),eo=o=>{let[t,p]=ct(!1);return st(()=>p(!0),[]),B.createElement(Ce,{options:o.options},o.children,t&&B.createElement(rt,{fallback:null},B.createElement(lt,null)))};export{de as a,eo as b};