All files / src/setup/factors question.js

100% Statements 21/21
100% Branches 12/12
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 61 62 63 64 65 66 67 68                  1x 1x                                                           10x 10x 9x   8x 7x   6x 6x   5x 5x   5x           5x     5x       1x  
/**
 * @file MFKDF Question Factor Setup
 * @copyright Multifactor 2022 All Rights Reserved
 *
 * @description
 * Setup question factor for multi-factor key derivation
 *
 * @author Vivek Nair (https://nair.me) <[email protected]>
 */
const defaults = require('../../defaults')
const zxcvbn = require('zxcvbn')
 
/**
 * Setup an MFKDF Security Question factor
 *
 * @example
 * // setup key with security question factor
 * const setup = await mfkdf.setup.key([
 *   await mfkdf.setup.factors.question('Fido')
 * ], {size: 8})
 *
 * // derive key with security question factor
 * const derive = await mfkdf.derive.key(setup.policy, {
 *   question: mfkdf.derive.factors.question('Fido')
 * })
 *
 * setup.key.toString('hex') // -> 01d0c7236adf2516
 * derive.key.toString('hex') // -> 01d0c7236adf2516
 *
 * @param {string} answer - The answer from which to derive an MFKDF factor
 * @param {Object} [options] - Configuration options
 * @param {string} [options.question] - Security question corresponding to this factor
 * @param {string} [options.id='question'] - Unique identifier for this factor
 * @returns {MFKDFFactor} MFKDF factor information
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 1.0.0
 * @async
 * @memberof setup.factors
 */
async function question (answer, options) {
  options = Object.assign(Object.assign({}, defaults.question), options)
  if (typeof answer !== 'string') throw new TypeError('answer must be a string')
  if (answer.length === 0) throw new RangeError('answer cannot be empty')
 
  if (typeof options.id !== 'string') throw new TypeError('id must be a string')
  if (options.id.length === 0) throw new RangeError('id cannot be empty')
 
  if (typeof options.question === 'undefined') options.question = ''
  if (typeof options.question !== 'string') throw new TypeError('question must be a string')
 
  answer = answer.toLowerCase().replace(/[^0-9a-z ]/gi, '').trim()
  const strength = zxcvbn(answer)
 
  return {
    type: 'question',
    id: options.id,
    entropy: Math.log2(strength.guesses),
    data: Buffer.from(answer),
    params: async () => {
      return { question: options.question }
    },
    output: async () => {
      return { strength }
    }
  }
}
module.exports.question = question