Skip to content

Commit

Permalink
fix: [LW-11855] (#1552)
Browse files Browse the repository at this point in the history
* fix: lw-11855
* feat(nami): add dedicated password component
  • Loading branch information
mchappell authored Dec 6, 2024
1 parent 74fd93b commit 6f838b9
Show file tree
Hide file tree
Showing 38 changed files with 467 additions and 447 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
EnableAccountConfirmWithHW,
EnableAccountConfirmWithHWState,
EnableAccountPasswordPrompt,
useDialogWithData
useDialogWithData,
useSecrets
} from '@lace/core';
import { useWalletStore } from '@src/stores';
import { useWalletManager } from '@hooks';
Expand Down Expand Up @@ -58,6 +59,7 @@ export const WalletAccounts = ({ isPopup, onBack }: { isPopup: boolean; onBack:
account: activeAccount
}
} = cardanoWallet;
const { clearSecrets, password } = useSecrets();

const editAccountDrawer = useDialogWithData<ProfileDropdown.AccountData | undefined>();
const disableAccountConfirmation = useDialogWithData<ProfileDropdown.AccountData | undefined>();
Expand Down Expand Up @@ -117,9 +119,10 @@ export const WalletAccounts = ({ isPopup, onBack }: { isPopup: boolean; onBack:
accountIndex
});
const accountName = accountsData.find((acc) => acc.accountNumber === accountIndex)?.label;
clearSecrets();
closeDropdownAndShowAccountActivated(accountName);
},
[wallet.walletId, activateWallet, accountsData, closeDropdownAndShowAccountActivated, analytics]
[wallet.walletId, activateWallet, accountsData, closeDropdownAndShowAccountActivated, analytics, clearSecrets]
);

const editAccount = useCallback(
Expand Down Expand Up @@ -198,29 +201,30 @@ export const WalletAccounts = ({ isPopup, onBack }: { isPopup: boolean; onBack:
[wallet.type, enableAccountPasswordDialog, enableAccountHWSigningDialog, unlockHWAccount]
);

const unlockInMemoryWalletAccountWithPassword = useCallback(
async (passphrase: Uint8Array) => {
const { accountIndex } = enableAccountPasswordDialog.data;
const name = defaultAccountName(accountIndex);
try {
await addAccount({
wallet,
accountIndex,
passphrase,
metadata: { name: defaultAccountName(accountIndex) }
});
analytics.sendEventToPostHog(PostHogAction.MultiWalletEnableAccount, {
// eslint-disable-next-line camelcase
$set: { wallet_accounts_quantity: await getWalletAccountsQtyString(walletRepository) }
});
enableAccountPasswordDialog.hide();
closeDropdownAndShowAccountActivated(name);
} catch {
enableAccountPasswordDialog.setData({ ...enableAccountPasswordDialog.data, wasPasswordIncorrect: true });
}
},
[wallet, addAccount, enableAccountPasswordDialog, closeDropdownAndShowAccountActivated, analytics, walletRepository]
);
const unlockInMemoryWalletAccountWithPassword = async () => {
const { accountIndex } = enableAccountPasswordDialog.data;
const name = defaultAccountName(accountIndex);
const passphrase = Buffer.from(password?.value);
try {
await addAccount({
wallet,
accountIndex,
passphrase,
metadata: { name: defaultAccountName(accountIndex) }
});
analytics.sendEventToPostHog(PostHogAction.MultiWalletEnableAccount, {
// eslint-disable-next-line camelcase
$set: { wallet_accounts_quantity: await getWalletAccountsQtyString(walletRepository) }
});
enableAccountPasswordDialog.hide();
closeDropdownAndShowAccountActivated(name);
} catch {
enableAccountPasswordDialog.setData({ ...enableAccountPasswordDialog.data, wasPasswordIncorrect: true });
} finally {
passphrase.fill(0);
clearSecrets();
}
};

const lockAccount = useCallback(async () => {
await walletRepository.removeAccount({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Lock } from '@src/views/browser-view/components/Lock';
import { MainLoader } from '@components/MainLoader';
import { FailedMigration } from './FailedMigration';
import { MigrationInProgress } from './MigrationInProgress';
import { OnPasswordChange } from '@lace/core';
import { OnPasswordChange, useSecrets } from '@lace/core';

export interface MigrationContainerProps {
children: React.ReactNode;
Expand All @@ -33,22 +33,22 @@ export const MigrationContainer = ({ children, appMode }: MigrationContainerProp
const [renderState, setRenderState] = useState<RenderState>(INITIAL_RENDER_STATE);

const [isVerifyingPassword, setIsVerifyingPassword] = useState(false);
const [password, setPassword] = useState<string>();
const { password, setPassword, clearSecrets } = useSecrets();
const [isValidPassword, setIsValidPassword] = useState(true);

const migrate = useCallback(async () => {
setRenderState(INITIAL_RENDER_STATE);
if (appMode === APP_MODE_POPUP) await applyMigrations(migrationState, password);
if (appMode === APP_MODE_POPUP) await applyMigrations(migrationState, password.value);
}, [migrationState, password, appMode]);

const handlePasswordChange = useCallback<OnPasswordChange>(
(target) => {
if (!isValidPassword) {
setIsValidPassword(true);
}
setPassword(target.value);
setPassword(target);
},
[isValidPassword]
[isValidPassword, setPassword]
);

const lockAndMigrate = useCallback(async () => {
Expand All @@ -66,11 +66,14 @@ export const MigrationContainer = ({ children, appMode }: MigrationContainerProp
await unlockWallet();
setIsValidPassword(true);
await migrate();
clearSecrets();
} catch {
setIsValidPassword(false);
} finally {
clearSecrets();
}
setIsVerifyingPassword(false);
}, [unlockWallet, migrate]);
}, [unlockWallet, migrate, clearSecrets]);

useEffect(() => {
// Load initial migrationState value
Expand Down Expand Up @@ -143,7 +146,7 @@ export const MigrationContainer = ({ children, appMode }: MigrationContainerProp
isLoading={isVerifyingPassword}
onUnlock={onUnlock}
passwordInput={{ handleChange: handlePasswordChange, invalidPass: !isValidPassword }}
unlockButtonDisabled={password === ''}
unlockButtonDisabled={!password.value}
// TODO: show forgot password here too. Use same logic as in ResetDataError on click
showForgotPassword={false}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Spin } from 'antd';
import { Wallet } from '@lace/cardano';
import { useTranslation } from 'react-i18next';
import { Button } from '@lace/common';
import { OnPasswordChange, Password } from '@lace/core';
import { Password, useSecrets } from '@lace/core';
import { useRedirection } from '@hooks';
import { dAppRoutePaths } from '@routes';
import { Layout } from './Layout';
Expand All @@ -20,15 +20,17 @@ export const SignData = (): React.ReactElement => {
const redirectToSignFailure = useRedirection(dAppRoutePaths.dappDataSignFailure);
const redirectToSignSuccess = useRedirection(dAppRoutePaths.dappDataSignSuccess);
const [isLoading, setIsLoading] = useState(false);
const [password, setPassword] = useState<string>();
const [validPassword, setValidPassword] = useState<boolean>();
const { password, setPassword, clearSecrets } = useSecrets();

const onConfirm = useCallback(async () => {
setIsLoading(true);
const passphrase = Buffer.from(password.value, 'utf8');
try {
const passphrase = Buffer.from(password, 'utf8');
await request.sign(passphrase, { willRetryOnFailure: true });
setValidPassword(true);
clearSecrets();
passphrase.fill(0);
redirectToSignSuccess();
} catch (error) {
if (error instanceof Wallet.KeyManagement.errors.AuthenticationError) {
Expand All @@ -37,11 +39,11 @@ export const SignData = (): React.ReactElement => {
redirectToSignFailure();
}
} finally {
passphrase.fill(0);
clearSecrets();
setIsLoading(false);
}
}, [password, redirectToSignFailure, redirectToSignSuccess, request]);

const handleChange: OnPasswordChange = (target) => setPassword(target.value);
}, [password, redirectToSignFailure, redirectToSignSuccess, request, clearSecrets]);

const confirmIsDisabled = useMemo(() => {
if (request.walletType !== WalletType.InMemory) return false;
Expand All @@ -68,7 +70,7 @@ export const SignData = (): React.ReactElement => {
{t('browserView.transaction.send.enterWalletPasswordToConfirmTransaction')}
</h5>
<Password
onChange={handleChange}
onChange={setPassword}
onSubmit={handleSubmit}
error={validPassword === false}
errorMessage={t('browserView.transaction.send.error.invalidPassword')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Spin } from 'antd';
import { Wallet } from '@lace/cardano';
import { useTranslation } from 'react-i18next';
import { Button, PostHogAction } from '@lace/common';
import { OnPasswordChange, Password } from '@lace/core';
import { Password, useSecrets } from '@lace/core';
import { useRedirection } from '@hooks';
import { dAppRoutePaths } from '@routes';
import { Layout } from './Layout';
Expand All @@ -21,7 +21,7 @@ export const SignTransaction = (): React.ReactElement => {
const redirectToSignFailure = useRedirection(dAppRoutePaths.dappTxSignFailure);
const redirectToSignSuccess = useRedirection(dAppRoutePaths.dappTxSignSuccess);
const [isLoading, setIsLoading] = useState(false);
const [password, setPassword] = useState<string>();
const { password, setPassword, clearSecrets } = useSecrets();
const [validPassword, setValidPassword] = useState<boolean>();
const analytics = useAnalyticsContext();

Expand All @@ -35,10 +35,12 @@ export const SignTransaction = (): React.ReactElement => {
[TX_CREATION_TYPE_KEY]: TxCreationType.External
});

const passphrase = Buffer.from(password.value, 'utf8');
try {
const passphrase = Buffer.from(password, 'utf8');
await request.sign(passphrase, { willRetryOnFailure: true });
setValidPassword(true);
clearSecrets();
passphrase.fill(0);
redirectToSignSuccess();
} catch (error) {
if (error instanceof Wallet.KeyManagement.errors.AuthenticationError) {
Expand All @@ -47,11 +49,11 @@ export const SignTransaction = (): React.ReactElement => {
redirectToSignFailure();
}
} finally {
clearSecrets();
passphrase.fill(0);
setIsLoading(false);
}
}, [password, analytics, redirectToSignFailure, redirectToSignSuccess, request]);

const handleChange: OnPasswordChange = (target) => setPassword(target.value);
}, [password, analytics, redirectToSignFailure, redirectToSignSuccess, request, clearSecrets]);

const confirmIsDisabled = useMemo(() => {
if (request.walletType !== WalletType.InMemory) return false;
Expand Down Expand Up @@ -85,7 +87,7 @@ export const SignTransaction = (): React.ReactElement => {
{t('browserView.transaction.send.enterWalletPasswordToConfirmTransaction')}
</h5>
<Password
onChange={handleChange}
onChange={setPassword}
onSubmit={handleSubmit}
error={validPassword === false}
errorMessage={t('browserView.transaction.send.error.invalidPassword')}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
/* eslint-disable react/no-multi-comp */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { DappCreateCollateralProps } from './types';
import { OnPasswordChange, Password, DappInfo, RowContainer, renderAmountInfo, renderLabel } from '@lace/core';
import {
OnPasswordChange,
Password,
DappInfo,
RowContainer,
renderAmountInfo,
renderLabel,
useSecrets
} from '@lace/core';
import { APIErrorCode, ApiError } from '@cardano-sdk/dapp-connector';
import { Wallet } from '@lace/cardano';
import { useTranslation } from 'react-i18next';
Expand Down Expand Up @@ -31,12 +39,12 @@ export const CreateCollateral = ({
const { inMemoryWallet, walletType, isInMemoryWallet } = useWalletStore();
const addresses = useObservable(inMemoryWallet.addresses$);
const [isSubmitting, setIsSubmitting] = useState(false);
const [password, setPassword] = useState('');
const { password, setPassword, clearSecrets } = useSecrets();
const [isPasswordValid, setIsPasswordValid] = useState(true);

const handleChange: OnPasswordChange = (target) => {
setIsPasswordValid(true);
setPassword(target.value);
setPassword(target);
};
const { priceResult } = useFetchCoinPrice();
const { fiatCurrency } = useCurrencyStore();
Expand Down Expand Up @@ -76,15 +84,16 @@ export const CreateCollateral = ({
};

try {
await withSignTxConfirmation(submitTx, password);
await withSignTxConfirmation(submitTx, password.value);
} catch (error) {
if (error instanceof Wallet.KeyManagement.errors.AuthenticationError) {
setPassword('');
setIsPasswordValid(false);
}
} finally {
clearSecrets();
}
setIsSubmitting(false);
}, [collateralTx, collateralInfo.amount, inMemoryWallet, password, confirm]);
}, [collateralTx, collateralInfo.amount, inMemoryWallet, password, confirm, clearSecrets]);

const confirmButtonLabel = useMemo(() => {
if (isInMemoryWallet) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useWalletStore } from '@src/stores';
import { useBackgroundServiceAPIContext } from '@providers/BackgroundServiceAPI';
import { saveValueInLocalStorage } from '@src/utils/local-storage';
import { useKeyboardShortcut } from '@lace/common';
import { OnPasswordChange } from '@lace/core';
import { OnPasswordChange, useSecrets } from '@lace/core';
import { BrowserViewSections } from '@lib/scripts/types';
import { useAnalyticsContext } from '@providers';
import { PostHogAction } from '@providers/AnalyticsProvider/analyticsTracker';
Expand All @@ -22,17 +22,17 @@ export const UnlockWalletContainer = ({ validateMnemonic }: UnlockWalletContaine
const backgroundService = useBackgroundServiceAPIContext();

const [isVerifyingPassword, setIsVerifyingPassword] = useState(false);
const [password, setPassword] = useState('');
const { password, setPassword, clearSecrets } = useSecrets();
const [isValidPassword, setIsValidPassword] = useState(true);

const handlePasswordChange = useCallback<OnPasswordChange>(
(target) => {
if (!isValidPassword) {
setIsValidPassword(true);
}
setPassword(target.value);
setPassword(target);
},
[isValidPassword]
[isValidPassword, setPassword]
);

useEffect(() => {
Expand All @@ -52,6 +52,8 @@ export const UnlockWalletContainer = ({ validateMnemonic }: UnlockWalletContaine
}
} catch {
setIsValidPassword(false);
} finally {
clearSecrets();
}
setIsVerifyingPassword(false);
};
Expand All @@ -73,7 +75,7 @@ export const UnlockWalletContainer = ({ validateMnemonic }: UnlockWalletContaine
isLoading={isVerifyingPassword}
onUnlock={onUnlock}
passwordInput={{ handleChange: handlePasswordChange, invalidPass: !isValidPassword }}
unlockButtonDisabled={password === ''}
unlockButtonDisabled={!password.value}
onForgotPasswordClick={onForgotPasswordClick}
/>
);
Expand Down
Loading

0 comments on commit 6f838b9

Please sign in to comment.