import { decrypt } from './decrypt' ; import { work } from './work' ; const DEFAULT_OPTS = { } ; export async function authenticateAccount ( ident , password , encoding = 'base64' ) { if ( ! ident || ! ident . auth ) { return ; } let decrypted ; try { const proof = await work ( password , ident . auth . s , { encode : encoding } ) ; decrypted = await decrypt ( ident . auth . ek , proof , { encode : encoding } ) ; } catch ( err ) { const proof = await work ( password , ident . auth . s , { encode : 'utf8' } ) ; decrypted = await decrypt ( ident . auth . ek , proof , { encode : encoding } ) ; } if ( ! decrypted ) { return ; } return { alias : ident . alias as string , epriv : decrypted . epriv as string , epub : ident . epub as string , priv : decrypted . priv as string , pub : ident . pub as string } ; } export async function authenticateIdentity ( chaingun , soul , password , encoding = 'base64' ) { const ident = await chaingun . get ( soul ) . then ( ) ; return authenticateAccount ( ident , password , encoding ) ; } export async function authenticate ( chaingun , alias , password , _opt = DEFAULT_OPTS ) { const aliasSoul = `~@${ alias }` ; const idents = await chaingun . get ( aliasSoul ) . then ( ) ; for ( const soul in idents || { } ) { if ( soul === '_' ) { continue ; } let pair ; try { pair = await authenticateIdentity ( chaingun , soul , password ) ; } catch ( e ) { console . warn ( e . stack || e ) ; } if ( pair ) { return pair ; } } throw new Error ( 'Wrong alias or password.' ) ; }