@privy-io/react-auth
Version:
React client for the Privy Auth API
2 lines (1 loc) • 9.37 kB
JavaScript
import{jsxs as e,Fragment as t,jsx as r}from"react/jsx-runtime";import{useState as o,useEffect as a,useCallback as i}from"react";import{P as c}from"./Button-BCV6mjvS.mjs";import{M as l,B as s}from"./ModalHeader-BTru6YQw.mjs";import{C as n}from"./ScreenHeader-Biz1wq02.mjs";import{q as d}from"./context-DRLoVlsO.mjs";import{o as p,q as u,r as m,R as h,l as v}from"./index-NL2cPmJD.mjs";import{a as w,f as y,b as f,u as _}from"./internal-context-e-Eni5bG.mjs";import{a as A,u as E,g}from"./get-is-unified-wallet-gMDXpX6C.mjs";import{a8 as C,a9 as b,aa as R}from"./paths-3HW55qZg.mjs";import{g as k}from"./useWallets-kObl6ZLS.mjs";import{a as T}from"./events-context-CI0iqAXA.mjs";import{u as O}from"./use-create-wallet-without-fallback-C0dI_RFZ.mjs";import{A as N,G as S,R as I}from"./styles-BxA7nKxI.mjs";import"styled-components";import"./useActiveWallet-BeOB3HTh.mjs";import"zustand";import"react-device-detect";import"./prepareFundingModalData-BVTcQcmw.mjs";import"@privy-io/js-sdk-core";import"eventemitter3";import"viem";import"viem/utils";import"./getPublicClient-A9RSftUZ.mjs";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"tinycolor2";import"uuid";import"jose";import"@coinbase/wallet-sdk";import"@privy-io/ethereum";import"mipd";import"@privy-io/popup";import"./usePrivy-BWtc2XF-.mjs";import"@scure/base";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"@privy-io/urls";import"ofetch";import"js-cookie";import"./frame-CwE9r3cT.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"viem/accounts";import"./use-sign-with-user-signer-eEm9Olt_.mjs";import"./getEmbeddedConnectedWallet-CM6cDQCS.mjs";async function M({url:e,popup:t,provider:r}){return t.location=e,new Promise(((e,r)=>{function o(){t?.close(),window.removeEventListener("message",a)}function a(t){t.data&&("PRIVY_OAUTH_RESPONSE"===t.data.type&&t.data.stateCode&&t.data.authorizationCode&&(e(t.data),o()),"https://cdn.apple-cloudkit.com"===t.origin&&t.data.ckSession&&(e({type:"PRIVY_OAUTH_RESPONSE",ckWebAuthToken:t.data.ckSession}),o()),"PRIVY_OAUTH_ERROR"===t.data.type&&(r(t.data.error),o()))}window.addEventListener("message",a)}))}async function j({api:e,provider:t,stateCode:r,codeVerifier:o,authorizationCode:a}){if(!a||!r)throw new w("[OAuth AuthFlow] Authorization and state codes code must be set prior to calling authenicate.");if("undefined"===a)throw new w("User denied confirmation during OAuth flow");try{return(await e.post(C,{authorization_code:a,state_code:r,code_verifier:o,provider:t})).access_token}catch(e){let t=y(e);if(t.privyErrorCode)throw new w(t.message||"Invalid code during OAuth flow.",void 0,t.privyErrorCode);if("User denied confirmation during OAuth flow"===t.message)throw new w("Invalid code during oauth flow.",void 0,f.OAUTH_USER_DENIED);throw new w("Invalid code during OAuth flow.",void 0,f.UNKNOWN_AUTH_ERROR)}}async function x({api:e,provider:t}){let r=p(),o=u(),a=await m(r);try{return"icloud"===t?{url:(await e.post(b,{client_type:"web"})).url}:{url:(await e.post(R,{redirect_to:window.location.href,code_challenge:a,state_code:o})).url,codeVerifier:r,stateCode:o,provider:t}}catch(e){throw y(e)}}let U={"google-drive":{name:"Google Drive",component:S},icloud:{name:"iCloud",component:N}};const W={component:()=>{let{logout:p}=E(),{navigate:u,setModalData:m,data:y}=A(),{closePrivyModal:C,createAnalyticsEvent:b}=_(),{execute:R}=(()=>{let{client:e,walletProxy:t,refreshSessionAndUser:r}=_(),{data:o}=A(),{user:a}=E(),i=T(),{create:c}=O();return{execute:async({provider:l,action:s,popup:n,shouldCreateEth:d,shouldCreateSol:p})=>{let u,m;if(!e)throw new w("Missing client");function h(t){if(!t&&e)throw e.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:"Unable to open recovery OAuth popup",provider:l}}),new w("Recovery OAuth failed")}switch(l){case"google-drive":{let t,r,{url:o,codeVerifier:a,stateCode:i}=await x({api:e.api,provider:l});h(o);try{let a=await M({url:o,popup:n,provider:l});if(t=a.stateCode,r=a.authorizationCode,t!==i)throw e.createAnalyticsEvent({eventName:"possible_phishing_attempt",payload:{provider:l,storedStateCode:i??"",returnedStateCode:t??""}}),new w("Unexpected auth flow. This may be a phishing attempt.",void 0,f.OAUTH_UNEXPECTED)}catch(t){throw e.createAnalyticsEvent({eventName:"recovery_oauth_error",payload:{error:t.toString(),provider:l}}),new w("Recovery OAuth failed")}[u,m]=await Promise.all([e.getAccessToken(),j({api:e.api,provider:l,codeVerifier:a,stateCode:t,authorizationCode:r})]);break}case"icloud":{let{url:t}=await x({api:e.api,provider:l});h(t);let{ckWebAuthToken:r}=await M({url:t,popup:n,provider:l});m=r,u=await e.getAccessToken()}}if(!t)throw new w("Cannot connect to wallet proxy");if(!u)throw new w("Unable to authorize user");switch(s){case"recover":{let r=o?.recoverWallet?.entropyId,a=o?.recoverWallet?.entropyIdVerifier;if(!r||!a)throw new w("Recovery OAuth failed");e.createAnalyticsEvent({eventName:"embedded_wallet_recovery_started",payload:{walletAddress:r,recoveryMethod:l}}),await t.recover({accessToken:u,entropyId:r,entropyIdVerifier:a,recoveryAccessToken:m}),e.createAnalyticsEvent({eventName:"embedded_wallet_recovery_completed",payload:{walletAddress:r,recoveryMethod:l}});break}case"create-wallet":{let t;if(e.createAnalyticsEvent({eventName:"embedded_wallet_creation_started"}),d&&p)t=await c({recoveryMethod:l,recoveryAccessToken:m,chainType:"ethereum",walletIndex:0,latestUser:a}),t=await c({chainType:"solana",walletIndex:0,latestUser:t.user});else if(p)t=await c({recoveryMethod:l,recoveryAccessToken:m,chainType:"solana",walletIndex:0,latestUser:a});else{if(!d)throw Error("Invalid args to create wallet");t=await c({recoveryMethod:l,recoveryAccessToken:m,chainType:"ethereum",walletIndex:0,latestUser:a})}if(!t)throw i("createWallet","onError",f.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to create wallet");e.createAnalyticsEvent({eventName:"embedded_wallet_creation_completed",payload:{walletAddress:t.account.address}}),i("createWallet","onSuccess",{wallet:t.account});break}case"set-recovery":{let o=g(a);if(!o)throw i("setWalletRecovery","onError",f.EMBEDDED_WALLET_NOT_FOUND),Error("Embedded wallet not found");e.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_started",payload:{walletAddress:o.address,existingRecoveryMethod:o.recoveryMethod,targetRecoveryMethod:l}});let{entropyId:c,entropyIdVerifier:s}=k(a);await t.setRecovery({accessToken:u,entropyId:c,entropyIdVerifier:s,recoveryMethod:l,recoveryAccessToken:m});let n=g(await r());if(!n)throw i("createWallet","onError",f.UNKNOWN_EMBEDDED_WALLET_ERROR),Error("Failed to set recovery on wallet");e.createAnalyticsEvent({eventName:"embedded_wallet_set_recovery_completed",payload:{walletAddress:o.address,existingRecoveryMethod:o.recoveryMethod,targetRecoveryMethod:l}}),i("setWalletRecovery","onSuccess",{method:l,wallet:n});break}default:throw new w("Unsupported recovery action")}}}})(),[N,S]=o(!1),{provider:W,action:D,isInAccountCreateFlow:P,shouldCreateEth:V,shouldCreateSol:L}=y?.recoveryOAuthStatus,[z,H]=o(void 0),[$,B]=o("create-wallet"===D);if("user-passcode"===W)throw Error("RecoveryOAuthScreen should never be called with a wallet that specifies recoveryMethod: `user-passcode`");let F=U[W].name,G=U[W].component,K=y?.recoverWallet?.onCompleteNavigateTo,Y=new h((async(e="create-wallet")=>(B(!0),new Promise(((t,r)=>{setTimeout((async()=>{try{let r=window.open();await R({provider:W,action:e,popup:r,shouldCreateEth:V,shouldCreateSol:L}),S(!0),t()}catch(t){H({message:`${"recover"===e?"Recovery":"Back up"} with ${F} unsuccessful`,detail:"recover"===D?`Please verify that you are selecting the ${F} account associated with your backup.`:"",retryable:!0}),r()}}),0)})))));a((()=>{"recover"!==D&&Y.execute(P?"create-wallet":"set-recovery")}),[]),a((()=>{if(!N)return;let e=setTimeout((()=>{P?(m({createWallet:{onSuccess:()=>{},onFailure:e=>{b({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"RecoveryOAuthScreen"}}),p()},callAuthOnSuccessOnClose:!0,shouldCreateEth:!1,shouldCreateSol:!1}}),u("EmbeddedWalletCreatedScreen")):C({shouldCallAuthOnSuccess:!1})}),d);return()=>clearTimeout(e)}),[N]);let q=i((async()=>{await Y.execute("recover"),K?u(K):S(!0)}),[]),X="google-drive"===W?"Google Drive":"Apple iCloud",Q=N&&`Successfully ${"recover"===D?"recovered":"backed up"} with ${X}.`||z&&z.message||`${"recover"===D?"Recovering":"Backing up"} with ${X}...`,J=z?z.detail:"";/*#__PURE__*/return e(t,{children:[/*#__PURE__*/r(l,{}),$?/*#__PURE__*/r(t,{children:/*#__PURE__*/e(I,{children:[/*#__PURE__*/r(n,{title:Q,icon:/*#__PURE__*/r(G,{style:{width:"38px",height:"38px"}}),description:J}),z&&z?.retryable?/*#__PURE__*/r(c,{onClick:()=>{v(),H(void 0),"create-wallet"===D?Y.execute("create-wallet"):q()},disabled:!N&&!z?.retryable,children:"Try again"}):null]})}):/*#__PURE__*/e(I,{children:[/*#__PURE__*/r(n,{title:"Confirm it's really you",icon:/*#__PURE__*/r(G,{style:{height:42,width:48}}),description:`To confirm your identity, please log in to ${X} where your account is backed up.`}),/*#__PURE__*/e(c,{onClick:q,children:["Confirm with ",X]})]}),/*#__PURE__*/r(s,{})]})}};export{W as RecoveryOAuthScreen,W as default};