UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

2 lines (1 loc) • 17.4 kB
import{u as e,g as o,a as i,b as n,c as s,d as l,C as h,e as d,s as p,P as m,f as k,h as C,i as f,G as T,W,j as U,k as P,l as R,m as S,n as O,o as _,p as j}from"./privy-provider-8kKbowq5.mjs";export{t as Captcha,v as ConnectorManager,E as EthereumWalletConnector,N as LoginModal,F as PrivyClient,q as PrivyProvider,V as VERSION,w as WalletConnector,B as errorIndicatesMaxMfaRetries,D as errorIndicatesMfaTimeout,A as errorIndicatesMfaVerificationFailed,r as getAccessToken,K as useCreateWallet,H as useIdentityToken,M as useImportWallet,I as useLogout,y as useMfa,z as useMfaEnrollment,x as usePrivy,J as useRegisterMfaListener,L as useSolanaWallets}from"./privy-provider-8kKbowq5.mjs";import{useCallback as G,useMemo as Q,useEffect as X,useContext as $,useRef as Y}from"react";import{u as Z,P as ee,a as te,I as re}from"./internal-context-D5bEplez.mjs";export{c as useActiveWallet,a as useConnectWallet,b as useFundWallet,u as useLogin}from"./useActiveWallet-Cpqv9qnc.mjs";import{F as oe}from"./frame-DTkUHpPA.mjs";import{zeroAddress as ie,getAddress as ne,createWalletClient as ae,http as se,parseSignature as ce}from"viem";import{hashAuthorization as le}from"viem/utils";export{DEFAULT_SUPPORTED_CHAINS as SUPPORTED_CHAINS,addPrivyRpcToChain,addRpcUrlOverrideToChain}from"@privy-io/js-sdk-core";export{g as getEmbeddedConnectedWallet}from"./getEmbeddedConnectedWallet-CSSBWE2p.mjs";import"react/jsx-runtime";import"mipd";import"react-device-detect";import"uuid";import"jose";import"eventemitter3";import"@coinbase/wallet-sdk";import"@marsidev/react-turnstile";import"styled-components";import"tinycolor2";import"@heroicons/react/24/outline/DevicePhoneMobileIcon";import"@heroicons/react/24/outline/FingerPrintIcon";import"@heroicons/react/24/outline/PhoneIcon";import"@heroicons/react/24/outline/ShieldCheckIcon";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/QuestionMarkCircleIcon";import"@heroicons/react/24/outline/XMarkIcon";import"@heroicons/react/24/outline/ChevronDownIcon";import"@heroicons/react/24/outline/CalendarIcon";import"@heroicons/react/24/outline/ExclamationTriangleIcon";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"zustand";import"fast-password-entropy";import"secure-password-utilities";import"secure-password-utilities/wordlists";import"@heroicons/react/24/outline/UserCircleIcon";import"@heroicons/react/24/outline/EnvelopeIcon";import"@heroicons/react/20/solid/CheckIcon";import"@heroicons/react/24/outline/WalletIcon";import"@heroicons/react/24/outline/CheckIcon";import"@heroicons/react/24/outline/Square2StackIcon";import"@heroicons/react/24/outline/ExclamationCircleIcon";import"@heroicons/react/24/outline/ArrowTopRightOnSquareIcon";import"@heroicons/react/24/solid/DocumentCheckIcon";import"@heroicons/react/24/solid/XCircleIcon";import"@heroicons/react/24/solid/CheckCircleIcon";import"qrcode";import"@heroicons/react/24/outline/ChevronRightIcon";import"@heroicons/react/24/outline/LockClosedIcon";import"@heroicons/react/24/outline/PencilSquareIcon";import"@heroicons/react/24/outline/ArrowPathIcon";import"@heroicons/react/24/outline/EyeIcon";import"@heroicons/react/24/outline/EyeSlashIcon";import"@heroicons/react/24/outline/KeyIcon";import"@heroicons/react/24/outline/ArrowDownTrayIcon";import"@heroicons/react/24/outline/ClipboardDocumentCheckIcon";import"@heroicons/react/24/outline/DocumentDuplicateIcon";import"@heroicons/react/24/solid/LockClosedIcon";import"@heroicons/react/24/outline/CheckCircleIcon";import"@heroicons/react/24/outline/InformationCircleIcon";import"@heroicons/react/24/outline/CreditCardIcon";import"@heroicons/react/24/outline/QrCodeIcon";import"@heroicons/react/24/solid/ArrowsRightLeftIcon";import"@heroicons/react/24/outline/GlobeAltIcon";import"ofetch";import"@heroicons/react/24/outline";import"@heroicons/react/24/outline/ClipboardDocumentIcon";import"@heroicons/react/24/outline/CloudArrowUpIcon";import"@heroicons/react/24/outline/NoSymbolIcon";import"@heroicons/react/24/outline/ClockIcon";import"@heroicons/react/24/outline/TrashIcon";import"@heroicons/react/24/solid/CheckBadgeIcon";import"@heroicons/react/24/solid/IdentificationIcon";import"@heroicons/react/24/outline/MinusCircleIcon";import"@heroicons/react/24/outline/ArrowRightEndOnRectangleIcon";import"@heroicons/react/24/solid/ShieldCheckIcon";import"js-cookie";const ue=()=>{let{user:t}=e(),{walletProxy:r}=Z();return{recover:G((async e=>{if(!r)throw Error("Wallet proxy is not ready");let n=await o();if(!t||!n)throw new ee("User must be logged in before attempting to modify the recovery method.");let{entropyId:a,entropyIdVerifier:s}=i(t);try{await r.recover({entropyId:a,entropyIdVerifier:s,accessToken:n,...e})}catch{throw new ee("Unable to recover wallets")}}),[r,t])}},he=()=>{let{client:e,setAuthenticated:t,setUser:r}=Z();return Q((()=>({init:async()=>{if(!e)throw new ee("Must initialize Privy client first.");let t=new oe;return e.startAuthFlow(t),await t.init()},login:async({fid:o,message:i,signature:n})=>{if(!e)throw new ee("Must initialize Privy client first.");if(!(e.authFlow instanceof oe))throw new ee("Must initialize Farcaster frame flow first.");e.authFlow.setAuthData({message:i,signature:n,fid:o});let{user:a}=await e.authenticate();if(!a)throw new ee("Failed to login with Farcaster V2");return r(a),t(!0),{user:a}}})),[e,r,t])},de=t=>{n("login",t);let r=s(),o=l(),{ready:i,user:a}=e(),{initLoginWithHeadlessOAuth:c,loginWithHeadlessOAuth:u,oAuthState:w,setOAuthState:m,isHeadlessOAuthLoading:g}=Z(),y=G((async e=>{try{if(r.enabled&&"success"!==r.status)throw new h(r.error,null,te.CAPTCHA_FAILURE);return await c(e.provider,r.token,e.disableSignup)}catch(e){throw m({status:"error",error:e}),e}}),[c,r]),A=G((async()=>{let e=d();try{if(a)return console.warn("Cannot login with OAuth when already logged in"),a;if(!e.inProgress)throw Error("Cannot login with OAuth because no OAuth flow is in progress");if(e.popupFlow)return}catch(e){throw m({status:"error",error:e}),e}try{return await u(e)}catch(e){throw m({status:"error",error:e}),e}finally{p()}}),[u]);return X((()=>{let e=d();i&&o&&e.inProgress&&!e.withPrivyUi&&!e.popupFlow&&A().catch((()=>{}))}),[i,o]),{initOAuth:y,loading:g,state:w}},pe=e=>{let t=s(),{emailOtpState:r,setEmailOtpState:o,initLoginWithEmail:i,loginWithCode:n}=Z();return{sendCode:G((async({email:r,disableSignup:n})=>{try{let e;if(!r)throw Error("Email required to send OTP code");if(t.enabled&&"error"===t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await i({email:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||te.UNKNOWN_AUTH_ERROR),r}}),[i]),loginWithCode:G((async({code:r})=>{try{if(t.enabled&&"error"===t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:s}=await n(r);e?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"email",loginAccount:s})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||te.UNKNOWN_AUTH_ERROR),r}}),[n,t.status]),state:r}},we=e=>{let t=s(),{initSignupWithPasskey:r,signupWithPasskey:o,passkeyAuthState:i,setPasskeyAuthState:n}=Z();return{signupWithPasskey:G((async()=>{try{let i;if(t.enabled&&"error"===t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),i=await t.waitForResult()),await r({captchaToken:i,withPrivyUi:!1});let{user:n,isNewUser:a,wasAlreadyAuthenticated:s,loginAccount:c}=await o();e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:s,loginMethod:"passkey",loginAccount:c})}catch(t){throw n({status:"error",error:t}),e?.onError?.(t.privyErrorCode||te.UNKNOWN_AUTH_ERROR),t}}),[o,t.status]),state:i}},me=e=>{let t=s(),{initLoginWithPasskey:r,loginWithPasskey:o,passkeyAuthState:i,setPasskeyAuthState:n}=Z();return{loginWithPasskey:G((async i=>{try{let n;if(t.enabled&&"error"===t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);t.enabled&&"success"!==t.status&&(t.execute(),n=await t.waitForResult()),await r({captchaToken:n,withPrivyUi:!1});let{user:a,isNewUser:s,wasAlreadyAuthenticated:c,loginAccount:l}=await o(i);e?.onComplete?.({user:a,isNewUser:s,wasAlreadyAuthenticated:c,loginMethod:"passkey",loginAccount:l})}catch(i){throw n({status:"error",error:i}),e?.onError?.(i.privyErrorCode||te.UNKNOWN_AUTH_ERROR),i}}),[o,t.status]),state:i}},ge=e=>{let{initLinkWithPasskey:t,linkWithPasskey:r,passkeyAuthState:o,setPasskeyAuthState:i}=Z();return{linkWithPasskey:G((async()=>{try{await t();let o=await r();if(!o)throw Error("Error, user not found");let i=o.linkedAccounts.filter((e=>"passkey"===e.type)).sort(((e,t)=>t.latestVerifiedAt.getTime()-e.latestVerifiedAt.getTime()))[0];e?.onSuccess?.({user:o,linkMethod:"passkey",linkedAccount:i})}catch(t){throw i({status:"error",error:t}),e?.onError?.(t.privyErrorCode||te.UNKNOWN_AUTH_ERROR,{linkMethod:"passkey"}),t}}),[r]),state:o}},ye=e=>{let t=s(),{smsOtpState:r,setSmsOtpState:o,initLoginWithSms:i,loginWithCode:n}=Z();return{sendCode:G((async({phoneNumber:r,disableSignup:n})=>{try{let e;if(!r)throw Error("SMS required to send OTP code");if(t.enabled&&"error"===t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);return t.enabled&&"success"!==t.status&&(t.execute(),e=await t.waitForResult()),await i({phoneNumber:r,captchaToken:e,disableSignup:n,withPrivyUi:!1})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||te.UNKNOWN_AUTH_ERROR),r}}),[i]),loginWithCode:G((async({code:r})=>{try{if(t.enabled&&"success"!==t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);let{user:o,isNewUser:i,wasAlreadyAuthenticated:a,linkedAccount:s}=await n(r);e?.onComplete?.({user:o,isNewUser:i,wasAlreadyAuthenticated:a,loginMethod:"sms",loginAccount:s})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||te.UNKNOWN_AUTH_ERROR),r}}),[n,t.status]),state:r}},Ae=t=>{let{connectOrCreateWallet:r}=e();return n("connectOrCreateWallet",t),{connectOrCreateWallet:r}},ke=e=>{let t=s(),{siweState:r,setSiweState:o,linkWithSiwe:i,generateSiweMessage:n}=Z();return{generateSiweMessage:G((async({address:t,chainId:r})=>{try{if(!t||!r)throw Error("wallet address and chainId required to generate nonce");return await n({address:t,chainId:r}).then((e=>e))}catch(t){throw o({status:"error",error:t}),e?.onError?.(t.privyErrorCode||te.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),t}}),[n]),linkWithSiwe:G((async({signature:r,message:n,chainId:a,walletClientType:s,connectorType:c})=>{try{if(t.enabled&&"success"!==t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);let{user:o,linkedAccount:l}=await i({message:n,signature:r,chainId:a,walletClientType:s,connectorType:c});l&&e?.onSuccess?.({user:o,linkMethod:"siwe",linkedAccount:l})}catch(r){throw o({status:"error",error:r}),e?.onError?.(r.privyErrorCode||te.UNKNOWN_AUTH_ERROR,{linkMethod:"siwe"}),r}}),[i,t.status]),state:r}};function Ce(){let{signTransaction:e}=$(m);return{signTransaction:e}}function fe(e){let{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:i,linkApple:a,linkTwitter:s,linkDiscord:c,linkGithub:l,linkLinkedIn:u,linkTiktok:h,linkSpotify:d,linkInstagram:p,linkTelegram:w,linkFarcaster:g}=$(m);return n("linkAccount",e),{linkEmail:t,linkPhone:r,linkWallet:o,linkGoogle:i,linkApple:a,linkTwitter:s,linkDiscord:c,linkGithub:l,linkLinkedIn:u,linkTiktok:h,linkSpotify:d,linkInstagram:p,linkFarcaster:g,linkTelegram:w}}function Ie(e){let{updateEmail:t,updatePhone:r}=$(m);return n("update",e),{updateEmail:t,updatePhone:r}}const Te=()=>{let{connectCoinbaseSmartWallet:e}=Z();return{connectCoinbaseSmartWallet:e}},Ee=()=>{let{startCrossAppAuthFlow:t,unlinkCrossAppAccount:r,signMessageWithCrossAppWallet:o,signTypedDataWithCrossAppWallet:i,sendTransactionWithCrossAppWallet:n}=e();return{loginWithCrossAppAccount:({appId:e})=>t({appId:e,action:"login"}),linkCrossAppAccount:({appId:e})=>t({appId:e,action:"link"}),unlinkCrossAppAccount:r,signMessage:o,signTypedData:i,sendTransaction:n}};function We(e){let{sendTransaction:t}=$(m);return n("sendTransaction",e),{sendTransaction:t}}function Ue(e){let{setWalletPassword:t}=$(m);return n("setWalletPassword",e),{setWalletPassword:t}}function Pe(){let t=k(),{getAccessToken:r}=e(),o=C(),{client:i,setUser:n,setAuthenticated:a,setIsNewUser:s,initializeWalletProxy:c}=Z(),{create:l}=f();return{createGuestAccount:async()=>{if(!t.id||!i)throw Error("SDK not yet ready");i.startAuthFlow(new T(t.id));try{let e=await i.authenticate(),u=e.user,h=e.isNewUser??!1;if(!u)throw new ee("Unable to authenticate guest account");let d=await r(),p=await c(W);if(d&&p)try{let e=U(u,t.embeddedWallets.ethereum.createOnLogin),r=P(u,t.embeddedWallets.solana.createOnLogin);e&&r?(u=(await l({chainType:"ethereum",latestUser:u})).user,u=(await l({chainType:"solana",latestUser:u})).user):r?u=(await l({chainType:"solana",latestUser:u})).user:e?u=(await l({chainType:"ethereum",latestUser:u})).user:n(u)}catch(e){n(u),console.warn("Unable to create embedded wallet for guest account")}return s(h),a(!0),o("login","onComplete",{user:u,isNewUser:h,wasAlreadyAuthenticated:!1,loginMethod:"guest",loginAccount:null}),u}catch(e){throw o("login","onError",e.privyErrorCode||te.UNKNOWN_AUTH_ERROR),e}}}}function Re(e){let{setWalletRecovery:t}=$(m);return n("setWalletRecovery",e),{setWalletRecovery:t}}function ve(e){let{signMessage:t}=$(m);return n("signMessage",e),{signMessage:t}}const Se=()=>{let{ready:t,wallets:r}=R(),{user:o}=e(),{rpcConfig:i,chains:n,appId:a}=Z();return{signAuthorization:G((async(e,s)=>{if(!o)throw Error("User must be authenticated before signing with a Privy wallet");if(!t)throw Error("Wallets are not ready");let c=s?.address??S(o)?.address??ie,l=r.find((e=>ne(e.address)===ne(c)));if(!l)throw Error("Signing wallet not found.");let u=e.chainId??Number(l.chainId.split(":")[1]),h=n.find((e=>e.id===u));if(!h)throw Error("Error, chain not configured in PrivyProvider config");let d=ae({account:c,chain:h,transport:se(O(h,i,a))}),p=await d.prepareAuthorization({...e}),w=await l.getEthereumProvider(),m=await w.request({method:"secp256k1_sign",params:[le(p)]});return{...p,...ce(m)}}),[t,r,o,n])}};function Ne(e){let{signTypedData:t}=$(m);return n("signTypedData",e),{signTypedData:t}}const be=()=>{let{isModalOpen:e}=$(m);return{isOpen:e}};function Oe(e){let{getAccessToken:t}=$(m);return n("accessToken",e),{getAccessToken:t}}function Me(t){let{authenticated:r,user:o}=e(),{initLoginWithOAuth:i}=Z(),a=C();return n("oAuthAuthorization",t),{reauthorize:e=>Fe(r,o,i,a,e.provider)}}let Fe=async(e,t,r,o,i)=>{if(!e)throw o("linkAccount","onError",te.MUST_BE_AUTHENTICATED,{linkMethod:i}),new ee("User must be authenticated before linking an account.");if(!t?.linkedAccounts.some((e=>e.type.includes(i))))throw new ee(`OAuth account of type ${i} not linked to the account.`);await r(i)};const _e=e=>{let t=_();return n("customAuth",e),{status:t}};function Le({isAuthenticated:e,isLoading:t,...r}){let o=Y();X((()=>{t||o.current?.()}),[e,t]);let i=G((e=>(o.current=e,()=>{o.current=void 0})),[]);return j({...r,subscribe:i})}function De(){let{getFarcasterSignerPublicKey:t,signFarcasterMessage:r,requestFarcasterSignerFromWarpcast:o}=e();return{getFarcasterSignerPublicKey:t,signFarcasterMessage:r,requestFarcasterSignerFromWarpcast:o}}const He=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Z();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!0}),revokeWallets:async()=>await e({showDelegationUIs:!0})}},xe=()=>{let{setUser:e,client:t}=$(re),{user:r}=$(m);return{user:r,refreshUser:G((async()=>{let r=await(t?.updateUserAndIdToken());return e(r??null),r}),[t,e])}},Ke=e=>{let t=s(),{initLoginWithTelegram:r,loginWithTelegram:o,telegramAuthState:i,setTelegramAuthState:n}=Z();return{login:G((async i=>{try{if(t.enabled&&"success"!==t.status)throw new h(t.error,null,te.CAPTCHA_FAILURE);await r(t.token,i?.disableSignup);let{user:n,isNewUser:a,loginAccount:s,wasAlreadyAuthenticated:c}=await o({intent:"login"});e?.onComplete?.({user:n,isNewUser:a,wasAlreadyAuthenticated:c,loginMethod:"telegram",loginAccount:s})}catch(i){throw n({status:"error",error:i}),e?.onError?.(i.privyErrorCode||te.UNKNOWN_AUTH_ERROR),i}}),[r,o,t]),state:i}},je=()=>{let{revokeDelegatedWallets:e,delegateWallet:t}=Z();return{delegateWallet:async({address:e,chainType:r})=>await t({address:e,chainType:r,showDelegationUIs:!1}),revokeWallets:async()=>await e({showDelegationUIs:!1})}};export{Te as useConnectCoinbaseSmartWallet,Ae as useConnectOrCreateWallet,Ee as useCrossAppAccounts,_e as useCustomAuth,He as useDelegatedActions,De as useFarcasterSigner,Pe as useGuestAccounts,je as useHeadlessDelegatedActions,fe as useLinkAccount,ge as useLinkWithPasskey,ke as useLinkWithSiwe,pe as useLoginWithEmail,he as useLoginWithFarcasterV2,de as useLoginWithOAuth,me as useLoginWithPasskey,ye as useLoginWithSms,Ke as useLoginWithTelegram,be as useModalStatus,Me as useOAuthTokens,ue as useRecoverEmbeddedWallet,We as useSendTransaction,Ue as useSetWalletPassword,Re as useSetWalletRecovery,Se as useSignAuthorization,ve as useSignMessage,Ce as useSignTransaction,Ne as useSignTypedData,we as useSignupWithPasskey,Le as useSubscribeToJwtAuthWithFlag,j as useSyncJwtBasedAuthState,Oe as useToken,Ie as useUpdateAccount,xe as useUser,R as useWallets};