UNPKG

@dynamic-labs/sdk-react-core

Version:

A React SDK for implementing wallet web3 authentication and authorization to your website.

272 lines (267 loc) 13.8 kB
'use client' 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _tslib = require('../../../../../_virtual/_tslib.cjs'); var React = require('react'); var sdkApiCore = require('@dynamic-labs/sdk-api-core'); require('@dynamic-labs/utils'); require('../../../config/ApiEndpoint.cjs'); require('../../../store/state/projectSettings/projectSettings.cjs'); require('../../constants/values.cjs'); var errors = require('../../constants/errors.cjs'); require('@dynamic-labs/multi-wallet'); require('../../../shared/logger.cjs'); require('../../constants/colors.cjs'); require('react-international-phone'); require('@dynamic-labs/iconic'); require('@dynamic-labs/wallet-connector-core'); require('react/jsx-runtime'); require('../../../context/ViewContext/ViewContext.cjs'); require('@dynamic-labs/wallet-book'); require('../../../shared/consts/index.cjs'); require('../../../store/state/nonce/nonce.cjs'); var dynamicContextProps = require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs'); require('../../../store/state/primaryWalletId/primaryWalletId.cjs'); var user = require('../../../store/state/user/user.cjs'); require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs'); var mfa = require('../../../data/api/mfa/mfa.cjs'); require('../../../locale/locale.cjs'); var user$1 = require('../../../data/api/user/user.cjs'); var useUserAuth = require('../useUserAuth/useUserAuth.cjs'); var dynamicEvents = require('../../../events/dynamicEvents.cjs'); var useUserUpdateRequest = require('../useUserUpdateRequest/useUserUpdateRequest.cjs'); require('../../../context/DynamicContext/DynamicContext.cjs'); require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs'); require('../../../context/CaptchaContext/CaptchaContext.cjs'); require('../../../context/ErrorContext/ErrorContext.cjs'); require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs'); require('../../../context/AccountExistsContext/AccountExistsContext.cjs'); require('../../../context/UserWalletsContext/UserWalletsContext.cjs'); require('../../../store/state/authMode/authMode.cjs'); require('../../../context/VerificationContext/VerificationContext.cjs'); require('react-dom'); require('../../functions/compareChains/compareChains.cjs'); require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs'); require('../../../context/ThemeContext/ThemeContext.cjs'); require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs'); require('bs58'); require('@dynamic-labs/types'); require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs'); require('yup'); require('../../../context/MockContext/MockContext.cjs'); require('../../../views/CollectUserDataView/useFields.cjs'); require('@dynamic-labs/rpc-providers'); require('../../../store/state/walletOptions/walletOptions.cjs'); require('react-i18next'); require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs'); require('../../../components/Alert/Alert.cjs'); require('../../../context/WalletContext/WalletContext.cjs'); require('../../../components/ShadowDOM/ShadowDOM.cjs'); require('../../../components/IconButton/IconButton.cjs'); require('../../../components/InlineWidget/InlineWidget.cjs'); require('../../../components/Input/Input.cjs'); require('../../../components/IsBrowser/IsBrowser.cjs'); require('../../../components/MenuList/Dropdown/Dropdown.cjs'); require('../../../components/OverlayCard/OverlayCard.cjs'); require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs'); require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs'); require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs'); require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs'); require('../../../components/Popper/Popper/Popper.cjs'); require('../../../components/Popper/PopperContext/PopperContext.cjs'); require('react-focus-lock'); require('qrcode'); require('formik'); require('../../../context/FieldsStateContext/FieldsStateContext.cjs'); require('../useSubdomainCheck/useSubdomainCheck.cjs'); require('../../../context/WalletGroupContext/WalletGroupContext.cjs'); require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs'); require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs'); require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs'); require('@hcaptcha/react-hcaptcha'); require('../../../context/LoadingContext/LoadingContext.cjs'); require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs'); require('../../../context/FooterAnimationContext/index.cjs'); require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs'); require('../../../context/PasskeyContext/PasskeyContext.cjs'); require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs'); require('../../../store/state/sendBalances.cjs'); require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs'); require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs'); require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs'); require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs'); require('../../../widgets/DynamicWidget/views/ManagePasskeysWidgetView/PasskeyCard/PasskeyCard.cjs'); require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs'); require('../../../context/OnrampContext/OnrampContext.cjs'); require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs'); require('../../../../index.cjs'); require('../../../store/state/tokenBalances.cjs'); require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs'); require('../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs'); const useMfa = () => { const { completeAuth } = useUserAuth.useUserAuth({}); const checkUserIsVerifiedAndGetEnvironmentId = React.useCallback(() => { const verifiedUser = user.getUser(); if (!verifiedUser) { throw new Error(errors.USER_NOT_LOGGED_IN); } const environmentId = dynamicContextProps.getEnvironmentId(); return environmentId; }, []); const handleMfaAuth = React.useCallback((code_1, ...args_1) => _tslib.__awaiter(void 0, [code_1, ...args_1], void 0, function* (code, type = sdkApiCore.MFADeviceType.Totp, deviceId, resultHandler) { try { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); let result; yield completeAuth({ onValidUpdatedJwt: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { // This callback is used by authDevice }), updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { const response = yield mfa.authMfaDevice({ code, createMfaToken: { singleUse: true, }, deviceId, environmentId, type, }); dynamicEvents.dynamicEvents.emit('mfaCompletionSuccess', { mfaToken: response.mfaToken, }); result = resultHandler(response); return { isEmailVerificationRequired: false, isSmsVerificationRequired: false, missingFields: [], updateUserProfileResponse: response, }; }), }); return result; } catch (error) { dynamicEvents.dynamicEvents.emit('mfaCompletionFailure', { error }); throw error; } }), [checkUserIsVerifiedAndGetEnvironmentId, completeAuth]); const getUserDevices = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); const devices = yield mfa.getUserMfaDevices({ environmentId }); return devices; }), [checkUserIsVerifiedAndGetEnvironmentId]); const updateUserDevice = React.useCallback((deviceId) => _tslib.__awaiter(void 0, void 0, void 0, function* () { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); yield mfa.updateUserMfaDevice({ environmentId, mfaDeviceId: deviceId, }); }), [checkUserIsVerifiedAndGetEnvironmentId]); const deleteUserDevice = React.useCallback((deviceId, mfaAuthToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); yield mfa.deleteMfaDevice({ environmentId, mfaAuthToken, mfaDeviceId: deviceId, }); // Refresh the user JWT to get the updated MFA acknowledgement // since if it is completed we won't show the QR code again yield user$1.refreshUserJwt({ environmentId }); }), [checkUserIsVerifiedAndGetEnvironmentId]); const addDevice = React.useCallback((...args_2) => _tslib.__awaiter(void 0, [...args_2], void 0, function* (type = sdkApiCore.MFADeviceType.Totp) { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); const { id, secret, uri } = yield mfa.addMfaDevice({ environmentId, type, }); return { id, secret, uri }; }), [checkUserIsVerifiedAndGetEnvironmentId]); // @deprecated Use authenticateDevice instead. // This function authenticates a device and returns a boolean value // indicating if the authentication was successful. const authDevice = React.useCallback((code_2, ...args_3) => _tslib.__awaiter(void 0, [code_2, ...args_3], void 0, function* (code, type = sdkApiCore.MFADeviceType.Totp, deviceId) { let isValid = false; yield handleMfaAuth(code, type, deviceId, () => { isValid = true; return true; }); return isValid; }), [handleMfaAuth]); /** * Authenticates a device and returns a single use MFA token * if the authentication is successful. */ const authenticateDevice = React.useCallback((_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ code, type = sdkApiCore.MFADeviceType.Totp, deviceId, }) { return handleMfaAuth(code, type, deviceId, (response) => response.mfaToken); }), [handleMfaAuth]); const authRecoveryCode = React.useCallback((code) => _tslib.__awaiter(void 0, void 0, void 0, function* () { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); let isValid = false; yield completeAuth({ onValidUpdatedJwt: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { isValid = true; }), updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { const response = yield mfa.authMfaRecovery({ code, environmentId, }); if (!response) { throw new Error('Failed to authenticate recovey code'); } return { isEmailVerificationRequired: false, isSmsVerificationRequired: false, missingFields: [], // in the mfa flow, we only care about the user in the response updateUserProfileResponse: response, }; }), }); return isValid; }), [checkUserIsVerifiedAndGetEnvironmentId, completeAuth]); const verifyDevice = React.useCallback((code_3, ...args_4) => _tslib.__awaiter(void 0, [code_3, ...args_4], void 0, function* (code, type = sdkApiCore.MFADeviceType.Totp) { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); const device = yield mfa.verifyMfaDevice({ code, environmentId, type, }); if (!device) { throw new Error('Failed to verify device'); } return device; }), [checkUserIsVerifiedAndGetEnvironmentId]); const getRecoveryCodes = React.useCallback((...args_5) => _tslib.__awaiter(void 0, [...args_5], void 0, function* (generateNewCodes = false) { const environmentId = checkUserIsVerifiedAndGetEnvironmentId(); const getRecoveryCodesFunc = generateNewCodes ? mfa.createNewRecoveryCodes : mfa.getRecoveryCodes; const recoveryCodes = yield getRecoveryCodesFunc({ environmentId, }); if (!recoveryCodes) { throw new Error('Recovery codes not found'); } return recoveryCodes; }), [checkUserIsVerifiedAndGetEnvironmentId]); const { updateUser } = useUserUpdateRequest.useUserUpdateRequestInternal({ validationSchemaStripUnknown: false, }); const completeAcknowledgement = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { yield updateUser({ mfaBackupCodeAcknowledgement: sdkApiCore.MfaBackupCodeAcknowledgement.Complete, }); }), [updateUser]); return { addDevice, authDevice, authRecoveryCode, authenticateDevice, completeAcknowledgement, deleteUserDevice, getRecoveryCodes, getUserDevices, updateUserDevice, verifyDevice, }; }; exports.useMfa = useMfa;