Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(neuron-wallet): use Validate decorator to verify password in… #374

Merged
merged 1 commit into from
May 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions packages/neuron-wallet/src/channel/wallet.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { BrowserWindow } from 'electron'

import Listeners from './listeners'
import { ResponseCode } from '../controllers'
import { Channel } from '../utils/const'
import { Channel, ResponseCode } from '../utils/const'

export default class WalletChannel extends Listeners {
public win: BrowserWindow
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Key from '../keys/key'
import { ResponseCode } from '.'
import { CatchControllerError } from '../decorators'
import { ResponseCode } from '../utils/const'
import i18n from '../utils/i18n'

export enum HelpersMethod {
Expand Down
6 changes: 0 additions & 6 deletions packages/neuron-wallet/src/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ import WalletsController, { WalletsMethod } from './wallets'
import TransactionsController from './transactions'
import HelpersController, { HelpersMethod } from './helpers'

export enum ResponseCode {
Fail,
Success,
}

export const methods = {
NetworksMethod,
WalletsMethod,
Expand All @@ -19,5 +14,4 @@ export default {
WalletsController,
TransactionsController,
HelpersController,
ResponseCode,
}
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/networks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ResponseCode } from '.'
import NetworksService, { NetworkType, NetworkID, Network } from '../services/networks'
import { CatchControllerError } from '../decorators'
import { ResponseCode } from '../utils/const'
import i18n from '../utils/i18n'

export enum NetworksMethod {
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/transactions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { ResponseCode } from '.'
import { Transaction } from '../appTypes/types'
import TransactionsService, {
TransactionsByAddressesParam,
PaginationResult,
TransactionsByLockHashesParam,
} from '../services/transactions'
import { CatchControllerError } from '../decorators'
import { ResponseCode } from '../utils/const'
import i18n from '../utils/i18n'

/**
Expand Down
11 changes: 4 additions & 7 deletions packages/neuron-wallet/src/controllers/wallets.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import WalletsService, { Wallet, WalletProperties } from '../services/wallets'
import { ResponseCode } from './index'
import windowManage from '../utils/windowManage'
import { Channel } from '../utils/const'
import Key from '../keys/key'
import { CatchControllerError } from '../decorators'
import windowManage from '../utils/windowManage'
import { Channel, ResponseCode } from '../utils/const'
import i18n from '../utils/i18n'
import { verifyPasswordComplexity } from '../utils/validators'

export enum WalletsMethod {
GetAll = 'getAll',
Expand Down Expand Up @@ -132,7 +130,7 @@ class WalletsController {
receivingAddressNumber: number
changeAddressNumber: number
}): Promise<Controller.Response<Wallet>> {
const key = Key.fromKeystore(keystore, password, receivingAddressNumber, changeAddressNumber)
const key = await Key.fromKeystore(keystore, password, receivingAddressNumber, changeAddressNumber)
const wallet = WalletsController.service.create({
name,
keystore: key.keystore || null,
Expand Down Expand Up @@ -170,8 +168,7 @@ class WalletsController {

if (newPassword) {
if (WalletsController.service.validate({ id, password })) {
verifyPasswordComplexity(password)
const key = Key.fromKeystore(JSON.stringify(wallet!.loadKeystore()), password)
const key = await Key.fromKeystore(JSON.stringify(wallet!.loadKeystore()), password)
props.keystore = key.toKeystore(JSON.stringify(key.keysData!), newPassword)
} else {
throw new Error(i18n.t('messages.wallet-incorrect-password'))
Expand Down
10 changes: 5 additions & 5 deletions packages/neuron-wallet/src/decorators/errors.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ResponseCode } from '../controllers'
import { ResponseCode } from '../utils/const'

export const CatchControllerError = (_target: any, _name: string, descripor: PropertyDescriptor) => {
const originalMethod = descripor.value
export const CatchControllerError = (_target: any, _name: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value
return {
...descripor,
...descriptor,
async value(...args: any[]) {
try {
return originalMethod(...args)
return await originalMethod(...args)
} catch (err) {
return {
status: ResponseCode.Fail,
Expand Down
9 changes: 6 additions & 3 deletions packages/neuron-wallet/src/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import errorsDecorators from './errors'
import errorDecorators from './errors'
import validatorDecorators from './validators'

export const { CatchControllerError } = errorsDecorators
export const { CatchControllerError } = errorDecorators
export const { Validate, Password, Required } = validatorDecorators

export default {
...errorsDecorators,
...errorDecorators,
...validatorDecorators,
}
75 changes: 75 additions & 0 deletions packages/neuron-wallet/src/decorators/validators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import 'reflect-metadata'

import i18n from '../utils/i18n'
import { MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH } from '../utils/const'

const requiredMetadataKey = Symbol('required')
const passwordMetadataKey = Symbol('password')

export const verifyPasswordComplexity = (password: string) => {
if (password.length < MIN_PASSWORD_LENGTH) {
throw Error(i18n.t('messages.wallet-password-less-than-min-length', { minPasswordLength: MIN_PASSWORD_LENGTH }))
}
if (password.length > MAX_PASSWORD_LENGTH) {
throw Error(i18n.t('messages.wallet-password-more-than-max-length', { maxPasswordLength: MAX_PASSWORD_LENGTH }))
}
let complex = 0
let reg = /\d/
if (reg.test(password)) {
complex++
}
reg = /[a-z]/
if (reg.test(password)) {
complex++
}
reg = /[A-Z]/
if (reg.test(password)) {
complex++
}
reg = /[^0-9a-zA-Z]/
if (reg.test(password)) {
complex++
}
if (complex < 3) {
throw Error(i18n.t('messages.wallet-password-letter-complexity'))
}
}

const Required = (target: Object, propertyKey: string | symbol, index: number) => {
const indices: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || []
indices.push(index)
Reflect.defineMetadata(requiredMetadataKey, indices, target, propertyKey)
}

const Password = (target: Object, propertyKey: string | symbol, parameterIndex: number) => {
Reflect.defineMetadata(passwordMetadataKey, parameterIndex, target, propertyKey)
}

const Validate = (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value
return {
...descriptor,
async value(...args: any[]) {
const requiredIndices: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey)
if (requiredIndices) {
requiredIndices.forEach(idx => {
if (idx >= args.length || args[idx] === undefined) {
throw new Error('Missing required argument')
}
})
}

const passwordIndex: number = Reflect.getOwnMetadata(passwordMetadataKey, target, propertyKey)
if (passwordIndex !== undefined) {
verifyPasswordComplexity(args[passwordIndex])
}
return originalMethod(...args)
},
}
}

export default {
Required,
Password,
Validate,
}
27 changes: 9 additions & 18 deletions packages/neuron-wallet/src/keys/key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import SHA3 from 'sha3'
import { v4 as uuid } from 'uuid'
import Address, { HDAddress } from '../services/addresses'
import { Keystore, KdfParams, KeysData } from './keystore'
import i18n from '../utils/i18n'
import { verifyPasswordComplexity } from '../utils/validators'
import { Keychain } from './hd'
import { Validate, Required, Password } from '../decorators'

export interface Addresses {
receiving: HDAddress[]
Expand Down Expand Up @@ -49,22 +48,17 @@ export default class Key {
return bip39.generateMnemonic()
}

static fromKeystore(
keystore: string,
password: string,
@Validate
static async fromKeystore(
@Required keystore: string,
@Password password: string,
receivingAddressNumber = DefaultAddressNumber.Receiving,
changeAddressNumber = DefaultAddressNumber.Change,
) {
if (!password) throw new Error(i18n.t('messages.password-is-required'))
verifyPasswordComplexity(password)

if (!keystore) throw new Error(i18n.t('messages.keystore-is-required'))
const keystoreObject: Keystore = JSON.parse(keystore)
const key = new Key()
key.keystore = keystoreObject
if (password === undefined) {
throw new Error('No password given.')
} else if (!key.checkPassword(password)) {
if (!key.checkPassword(password)) {
throw new Error('Password error.')
}
const { kdfparams } = keystoreObject.crypto
Expand Down Expand Up @@ -98,16 +92,13 @@ export default class Key {
return key
}

@Validate
public static async fromMnemonic(
mnemonic: string,
password: string,
@Required mnemonic: string,
@Password password: string,
receivingAddressNumber = DefaultAddressNumber.Receiving,
changeAddressNumber = DefaultAddressNumber.Change,
) {
if (!password) throw new Error(i18n.t('messages.password-is-required'))
verifyPasswordComplexity(password)

if (!mnemonic) throw new Error(i18n.t('messages.mnemonic-is-required'))
if (!bip39.validateMnemonic(mnemonic)) {
throw new Error('Wrong Mnemonic')
}
Expand Down
3 changes: 1 addition & 2 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import Store from '../utils/store'
import env from '../env'

import windowManage from '../utils/windowManage'
import { ResponseCode } from '../controllers'
import { NetworksMethod } from '../controllers/networks'
import { Channel } from '../utils/const'
import { Channel, ResponseCode } from '../utils/const'
import nodeService from '../startup/nodeService'

export type NetworkID = string
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/startup/initWindow.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { app, BrowserWindow } from 'electron'
import controllers, { ResponseCode } from '../controllers'
import { Channel } from '../utils/const'
import controllers from '../controllers'
import { Channel, ResponseCode } from '../utils/const'

const { WalletsController, NetworksController } = controllers

Expand Down
6 changes: 6 additions & 0 deletions packages/neuron-wallet/src/utils/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export enum Channel {
Helpers = 'helpers',
}

export enum ResponseCode {
Fail,
Success,
}

export default {
Channel,
ResponseCode,
}
35 changes: 0 additions & 35 deletions packages/neuron-wallet/src/utils/validators.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/neuron-wallet/tests/keys/key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('Key tests', () => {
})

it('import key from keystore', async () => {
const key = Key.fromKeystore(keystoreJson, '1qaz.2wsx', 20, 10)
const key = await Key.fromKeystore(keystoreJson, '1qaz.2wsx', 20, 10)
expect(privateKey).toBe(key.keysData!.privateKey)
expect(key.addresses!.receiving.length).toEqual(20)
expect(key.addresses!.change.length).toEqual(10)
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/tests/utils/validators.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { verifyPasswordComplexity } from '../../src/utils/validators'
import { verifyPasswordComplexity } from '../../src/decorators/validators'
import i18n from '../../src/utils/i18n'
import { MIN_PASSWORD_LENGTH } from '../../src/utils/const'

Expand Down