All files / src/policy evaluate.js

100% Statements 10/10
100% Branches 6/6
100% Functions 1/1
100% Lines 8/8

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                                                                              166x 166x 166x 320x 102x   218x     166x   1x  
/**
 * @file MFKDF Policy Evaluation
 * @copyright Multifactor 2022 All Rights Reserved
 *
 * @description
 * Determine whether key can be derived from given factors
 *
 * @author Vivek Nair (https://nair.me) <[email protected]>
 */
 
/**
 * Evaluate a policy-based multi-factor derived key
 *
 * @example
 * // setup key that can be derived from passwordA AND (passwordB OR passwordC)
 * const setup = await mfkdf.policy.setup(
 *   await mfkdf.policy.and(
 *     await mfkdf.setup.factors.password('passwordA', { id: 'passwordA' }),
 *     await mfkdf.policy.or(
 *       await mfkdf.setup.factors.password('passwordB', { id: 'passwordB' }),
 *       await mfkdf.setup.factors.password('passwordC', { id: 'passwordC' })
 *     )
 *   )
 * )
 *
 * // check if key can be derived with passwordA and passwordC
 * const valid1 = await mfkdf.policy.evaluate(setup.policy, ['passwordA', 'passwordC']) // -> true
 *
 * // check if key can be derived with passwordB and passwordC
 * const valid2 = await mfkdf.policy.evaluate(setup.policy, ['passwordB', 'passwordC']) // -> false
 *
 * @param {Object} policy - The key policy for the key being derived
 * @param {Array.<string>} factors - Array of factor ids used to derive this key
 * @returns {boolean} Whether the key can be derived with given factor ids
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.16.0
 * @memberOf policy
 */
function evaluate (policy, factors) {
  const threshold = policy.threshold
  let actual = 0
  for (const factor of policy.factors) {
    if (factor.type === 'stack') {
      if (evaluate(factor.params, factors)) actual++
    } else {
      if (factors.includes(factor.id)) actual++
    }
  }
  return (actual >= threshold)
}
module.exports.evaluate = evaluate