All files / src/lib generate.js

100% Statements 16/16
100% Branches 6/6
100% Functions 4/4
100% Lines 16/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                        317x 297x 297x   297x   20x 20x                   36x             36x   36x 35x 32x 30x 29x   24x 21x   21x        
/*!
 * SuperGenPass library
 * https://github.com/chriszarate/supergenpass-lib
 * https://chriszarate.github.com/supergenpass/
 * License: GPLv2
 */
 
import hash from './hash';
import hostname from './hostname';
import {
  validateCallback,
  validateLength,
  validatePassword,
  validatePasswordInput,
  validatePasswordLength,
} from './validate';
 
// Hash the input for the requested number of rounds, then continue hashing
// until the password policy is satisfied. Finally, pass result to callback.
function hashRound(input, length, hashFunction, rounds, callback) {
  if (rounds > 0 || !validatePassword(input, length)) {
    process.nextTick(() => {
      hashRound(hashFunction(input), length, hashFunction, rounds - 1, callback);
    });
    return;
  }
  process.nextTick(() => {
    callback(input.substring(0, length));
  });
}
 
function generate(
    masterPassword,
    url,
    userOptions = {},
    callback = console.log // eslint-disable-line no-console
  ) {
  const defaults = {
    hashRounds: 10,
    length: 10,
    method: 'md5',
    removeSubdomains: true,
    secret: '',
  };
  const options = Object.assign({}, defaults, userOptions);
 
  validateCallback(callback);
  validatePasswordInput(masterPassword);
  validatePasswordInput(options.secret);
  validatePasswordLength(masterPassword + options.secret);
  validateLength(options.length);
 
  const domain = hostname(url, options);
  const input = `${masterPassword}${options.secret}:${domain}`;
 
  hashRound(input, options.length, hash(options.method), options.hashRounds, callback);
}
 
export default generate;