Skip to content

Commit

Permalink
problem: password field is inconsistent and uses plain-html
Browse files Browse the repository at this point in the history
solution: refactor and ensure it works the same way on all places
  • Loading branch information
BOOMER74 authored Aug 16, 2023
1 parent 8db8cd9 commit 2391191
Show file tree
Hide file tree
Showing 50 changed files with 1,039 additions and 639 deletions.
10 changes: 1 addition & 9 deletions packages/core/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "lib/",
"rootDir": "src/",
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "ES2021",
"typeRoots": [
"../../node_modules/@types",
"node_modules/@types",
Expand Down
4 changes: 2 additions & 2 deletions packages/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ app.on('ready', () => {

logger.info('Connect to', apiAccess.address);

const persistentStateDir = dataDir == null ? null : resolvePath(joinPath(dataDir, 'state'));
const persistentStateDir = dataDir == null ? undefined : resolvePath(joinPath(dataDir, 'state'));

logger.info(`Setup Persistent State in ${persistentStateDir ?? 'default directory'}`);

const persistentState = new PersistentStateManager(persistentStateDir);

const vaultDir = dataDir == null ? null : resolvePath(joinPath(dataDir, 'vault'));
const vaultDir = dataDir == null ? undefined : resolvePath(joinPath(dataDir, 'vault'));

logger.info(`Setup Vault in ${vaultDir ?? 'default directory'}`);

Expand Down
30 changes: 15 additions & 15 deletions packages/desktop/src/renderer/store/cache/allowances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ export function initAllowancesState(api: WalletApi, backendApi: BackendApi, stor
);

if (entry != null) {
const {
address: { value: address },
} = entry;
const { address } = entry;

const available = tokens.selectors.selectBalance(state, blockchain, owner, token)?.number.toString() ?? '0';
if (address != null) {
const available = tokens.selectors.selectBalance(state, blockchain, owner, token)?.number.toString() ?? '0';

store.dispatch(
allowances.actions.initAddressAllowance({
address,
available,
blockchain,
allowance: amount,
contractAddress: token,
ownerAddress: owner,
spenderAddress: spender,
}) as unknown as Action,
);
store.dispatch(
allowances.actions.initAddressAllowance({
available,
blockchain,
address: address.value,
allowance: amount,
contractAddress: token,
ownerAddress: owner,
spenderAddress: spender,
}) as unknown as Action,
);
}
}
}),
),
Expand Down
15 changes: 10 additions & 5 deletions packages/desktop/src/renderer/store/cache/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { EthereumAddress, PersistentState, WalletApi } from '@emeraldwallet/core
import { IState, accounts, tokens } from '@emeraldwallet/store';
import { Action, Store } from 'redux';

type Balances = {
interface Balances {
coinBalances: PersistentState.Balance[];
tokenBalances: PersistentState.Balance[];
};
}

type EntriesByAddress = Record<string, WalletEntry[]>;

export function initBalancesState(api: WalletApi, store: Store<IState>): void {
const entries = accounts.selectors.allEntries(store.getState());
Expand Down Expand Up @@ -57,10 +59,13 @@ export function initBalancesState(api: WalletApi, store: Store<IState>): void {
{ coinBalances: [], tokenBalances: [] },
);

const entryByAddress = Object.entries(balanceByIdentifier).reduce<Record<string, WalletEntry[]>>(
const entryByAddress = Object.entries(balanceByIdentifier).reduce<EntriesByAddress>(
(carry, [identifier, balances]) => {
return balances.reduce(
(balancesCarry, balance) => ({ ...balancesCarry, [balance.address]: entryByIdentifier.get(identifier) }),
return balances.reduce<EntriesByAddress>(
(balancesCarry, balance) => ({
...balancesCarry,
[balance.address]: entryByIdentifier.get(identifier) ?? [],
}),
carry,
);
},
Expand Down
6 changes: 5 additions & 1 deletion packages/desktop/src/renderer/store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,11 @@ function startSync(): void {
});

triggers.onceAccountsLoaded(store).then(() => {
RemoteCache.get('rates').then((rates) => store.dispatch(settings.actions.setRates(JSON.parse(rates))));
RemoteCache.get('rates').then((rates) => {
if (rates != null) {
store.dispatch(settings.actions.setRates(JSON.parse(rates)));
}
});

triggers.onceTokenBalancesLoaded(store).then(() => initAllowancesState(api, backendApi, store));

Expand Down
11 changes: 3 additions & 8 deletions packages/desktop/tsconfig.base.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"esModuleInterop": true,
"composite": false,
"jsx": "react",
"module": "CommonJS",
"moduleResolution": "Node",
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": false,
"target": "ES2021"
"resolveJsonModule": true
},
"files": [
"commit-data.json",
Expand Down
11 changes: 2 additions & 9 deletions packages/electron-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"esModuleInterop": true,
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "lib/",
"rootDir": "src/",
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "ES2021"
"rootDir": "src/"
},
"exclude": [
"node_modules",
Expand Down
10 changes: 1 addition & 9 deletions packages/persistent-state/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "lib/",
"rootDir": "src/",
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "ES2021",
"typeRoots": [
"../../node_modules/@types",
"node_modules/@types",
Expand Down
19 changes: 6 additions & 13 deletions packages/react-app/.storybook/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"esModuleInterop": true,
"baseUrl": "../src",
"composite": false,
"jsx": "react",
"module": "CommonJS",
"moduleResolution": "Node",
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "ES2021",
"resolveJsonModule": true,
"rootDirs": [
"src",
"stories"
"../src",
"../stories"
],
"typeRoots": [
"node_modules/@types",
"../../node_modules/@types"
]
},
"exclude": [
"../../node_modules",
"../src/**/*.spec.ts",
"../src/**/*.spec.tsx",
"node_modules"
"../src/**/*.spec.tsx"
],
"include": [
"../src/**/*.ts",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,58 +45,67 @@ const useStyles = makeStyles(
);

interface DispatchProps {
checkGlobalKey(password: string): Promise<boolean>;
getLegacyItems(): Promise<OddPasswordItem[]>;
goHome(): Promise<void>;
upgradeLegacyItems(globalPassword: string, password: string): Promise<Uuid[]>;
upgradeLegacyItems(legacyPassword: string, globalPassword: string): Promise<Uuid[]>;
verifyGlobalKey(password: string): Promise<boolean>;
}

type PasswordType = OddPasswordItem & { upgraded?: boolean };

const PasswordMigration: React.FC<DispatchProps> = ({ checkGlobalKey, getLegacyItems, goHome, upgradeLegacyItems }) => {
const PasswordMigration: React.FC<DispatchProps> = ({
getLegacyItems,
goHome,
upgradeLegacyItems,
verifyGlobalKey,
}) => {
const styles = useStyles();

const [initializing, setInitializing] = useState(true);
const [upgrading, setUpgrading] = useState(false);
const [verifying, setVerifying] = React.useState(false);

const [legacyItems, setLegacyItems] = React.useState<PasswordType[]>([]);

const [globalPassword, setGlobalPassword] = React.useState('');
const [password, setPassword] = React.useState('');

const [globalPassword, setGlobalPassword] = React.useState<string>();
const [globalPasswordError, setGlobalPasswordError] = React.useState<string>();
const [passwordError, setPasswordError] = React.useState<string>();

const applyPassword = React.useCallback(async () => {
const [legacyPassword, setLegacyPassword] = React.useState<string>();
const [legacyPasswordError, setLegacyPasswordError] = React.useState<string>();

const applyPassword = async (): Promise<void> => {
if (globalPassword == null || legacyPassword == null || legacyPassword.length === 0) {
return;
}

setGlobalPasswordError(undefined);
setPasswordError(undefined);
setLegacyPasswordError(undefined);

setVerifying(true);

const correctGlobalPassword = await checkGlobalKey(globalPassword);
const correctGlobalPassword = await verifyGlobalKey(globalPassword);

if (!correctGlobalPassword) {
setGlobalPasswordError('Incorrect password');

return;
}

if (password.length === 0) {
setPasswordError('Incorrect password');
setVerifying(false);

return;
}

setUpgrading(true);

const upgraded = await upgradeLegacyItems(globalPassword, password);
const upgraded = await upgradeLegacyItems(legacyPassword, globalPassword);

setUpgrading(false);
setLegacyItems(
legacyItems.map((item) => ({
...item,
upgraded: item.upgraded === true ? item.upgraded : upgraded.includes(item.id),
})),
);
}, [legacyItems, globalPassword, password, checkGlobalKey, upgradeLegacyItems]);

setUpgrading(false);
setVerifying(false);
};

React.useEffect(
() => {
Expand All @@ -114,6 +123,9 @@ const PasswordMigration: React.FC<DispatchProps> = ({ checkGlobalKey, getLegacyI

const allItemsUpgraded = legacyItems.reduce((carry, item) => carry && item.upgraded === true, true);

const processing = initializing || upgrading || verifying;
const applyDisabled = processing || (globalPassword?.length ?? 0) === 0 || (legacyPassword?.length ?? 0) === 0;

return (
<Page title="Setup Global Password">
<Alert severity="info" style={{ marginBottom: 15 }}>
Expand All @@ -133,22 +145,22 @@ const PasswordMigration: React.FC<DispatchProps> = ({ checkGlobalKey, getLegacyI
</TableRow>
</TableHead>
<TableBody>
{legacyItems.map((password) => (
<TableRow key={password.id}>
<TableCell>{password.type === 'key' ? 'Private Key' : 'Seed'}</TableCell>
<TableCell>{password.id}</TableCell>
{legacyItems.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.type === 'key' ? 'Private Key' : 'Seed'}</TableCell>
<TableCell>{item.id}</TableCell>
<TableCell>
{upgrading && !password.upgraded ? (
{upgrading && !item.upgraded ? (
<div className={styles.status}>
<CircularProgress color="primary" className={styles.loader} size="1em" />
<span>Migrating...</span>
</div>
) : password.upgraded == null ? (
) : item.upgraded == null ? (
<div className={styles.status}>
<WarningIcon style={{ color: orangeColor['500'] }} />
<span>Migration required</span>
</div>
) : password.upgraded ? (
) : item.upgraded ? (
<div className={styles.status}>
<DoneIcon style={{ color: greenColor['500'] }} />
<span>Migration successful</span>
Expand All @@ -169,23 +181,35 @@ const PasswordMigration: React.FC<DispatchProps> = ({ checkGlobalKey, getLegacyI
<PasswordInput
disabled={initializing}
error={globalPasswordError}
minLength={1}
placeholder="Enter existing password"
showLengthNotice={false}
onChange={(value) => setGlobalPassword(value)}
/>
</FormRow>
<FormRow>
<FormLabel classes={{ root: styles.label }}>Old password (for any of the items above):</FormLabel>
<PasswordInput disabled={initializing} error={passwordError} onChange={(value) => setPassword(value)} />
<PasswordInput
disabled={initializing}
error={legacyPasswordError}
minLength={1}
placeholder="Enter existing password"
showLengthNotice={false}
onChange={(value) => setLegacyPassword(value)}
/>
</FormRow>
<FormRow>
<FormLabel classes={{ root: styles.label }} />
<ButtonGroup classes={{ container: styles.buttons }}>
<Button
disabled={initializing}
disabled={processing}
label={allItemsUpgraded ? 'Continue' : 'Skip'}
primary={allItemsUpgraded}
onClick={goHome}
/>
{!allItemsUpgraded && <Button disabled={initializing} label="Apply" primary={true} onClick={applyPassword} />}
{!allItemsUpgraded && (
<Button disabled={applyDisabled} label="Apply" primary={true} onClick={applyPassword} />
)}
</ButtonGroup>
</FormRow>
</Page>
Expand All @@ -196,17 +220,17 @@ export default connect<unknown, DispatchProps>(
null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(dispatch: any) => ({
checkGlobalKey(password) {
return dispatch(accounts.actions.verifyGlobalKey(password));
},
getLegacyItems() {
return dispatch(accounts.actions.getOddPasswordItems());
},
goHome() {
return dispatch(screen.actions.gotoWalletsScreen());
},
upgradeLegacyItems(globalPassword, password) {
return dispatch(accounts.actions.tryUpgradeOddItems(password, globalPassword));
upgradeLegacyItems(legacyPassword, globalPassword) {
return dispatch(accounts.actions.tryUpgradeOddItems(legacyPassword, globalPassword));
},
verifyGlobalKey(password) {
return dispatch(accounts.actions.verifyGlobalKey(password));
},
}),
)(PasswordMigration);
Loading

0 comments on commit 2391191

Please sign in to comment.