All files / src/setup/factors hotp.js

100% Statements 35/35
100% Branches 18/18
100% Functions 4/4
100% Lines 32/32

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132                  1x 1x 1x 1x 1x     17x                                                                   25x   25x 1x   24x 23x 1x   22x 21x 20x 1x   19x 6x   19x 1x   18x 1x     17x 17x 17x   17x   17x           17x                   17x   17x                 17x                                             1x  
/**
 * @file MFKDF HOTP Factor Setup
 * @copyright Multifactor, Inc. 2022–2025
 *
 * @description
 * Setup an HOTP factor for multi-factor key derivation
 *
 * @author Vivek Nair (https://nair.me) <[email protected]>
 */
const defaults = require('../../defaults')
const crypto = require('crypto')
const { encrypt } = require('../../crypt')
const speakeasy = require('speakeasy')
const { randomInt: random } = require('crypto')
 
function mod (n, m) {
  return ((n % m) + m) % m
}
 
/**
 * Setup an MFKDF HOTP factor
 *
 * @example
 * // setup key with hotp factor
 * const setup = await mfkdf.setup.key([
 *   await mfkdf.setup.factors.hotp({ secret: Buffer.from('abcdefghijklmnopqrst') })
 * ])
 *
 * // derive key with hotp factor
 * const derive = await mfkdf.derive.key(setup.policy, {
 *   hotp: mfkdf.derive.factors.hotp(241063)
 * })
 *
 * setup.key.toString('hex') // -> 01d0…2516
 * derive.key.toString('hex') // -> 01d0…2516
 *
 * @param {Object} [options] - Configuration options
 * @param {string} [options.id='hotp'] - Unique identifier for this factor
 * @param {string} [options.hash='sha1'] - Hash algorithm to use; sha512, sha256, or sha1
 * @param {number} [options.digits=6] - Number of digits to use
 * @param {Buffer} [options.secret] - HOTP secret to use; randomly generated by default
 * @param {Buffer} [options.issuer='MFKDF'] - OTPAuth issuer string
 * @param {Buffer} [options.label='mfkdf.com'] - OTPAuth label string
 * @returns {MFKDFFactor} MFKDF factor information
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.12.0
 * @async
 * @memberof setup.factors
 */
async function hotp (options) {
  options = Object.assign(Object.assign({}, defaults.hotp), options)
 
  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 (!Number.isInteger(options.digits)) {
    throw new TypeError('digits must be an interger')
  }
  if (options.digits < 6) throw new RangeError('digits must be at least 6')
  if (options.digits > 8) throw new RangeError('digits must be at most 8')
  if (!['sha1', 'sha256', 'sha512'].includes(options.hash)) {
    throw new RangeError('unrecognized hash function')
  }
  if (typeof options.secret === 'undefined') {
    options.secret = crypto.randomBytes(20)
  }
  if (!Buffer.isBuffer(options.secret)) {
    throw new TypeError('secret must be a buffer')
  }
  if (Buffer.byteLength(options.secret) !== 20) {
    throw new RangeError('secret must be 20 bytes')
  }
 
  const target = await random(0, 10 ** options.digits - 1)
  const buffer = Buffer.allocUnsafe(4)
  buffer.writeUInt32BE(target, 0)
 
  const paddedSecret = Buffer.concat([options.secret, crypto.randomBytes(12)])
 
  return {
    type: 'hotp',
    id: options.id,
    data: buffer,
    entropy: Math.log2(10 ** options.digits),
    params: async ({ key }) => {
      const code = parseInt(
        speakeasy.hotp({
          secret: paddedSecret.subarray(0, 20).toString('hex'),
          encoding: 'hex',
          counter: 1,
          algorithm: options.hash,
          digits: options.digits
        })
      )
 
      const offset = mod(target - code, 10 ** options.digits)
 
      return {
        hash: options.hash,
        digits: options.digits,
        pad: encrypt(paddedSecret, key).toString('base64'),
        counter: 1,
        offset
      }
    },
    output: async () => {
      return {
        scheme: 'otpauth',
        type: 'hotp',
        label: options.label,
        secret: options.secret,
        issuer: options.issuer,
        algorithm: options.hash,
        digits: options.digits,
        counter: 1,
        uri: speakeasy.otpauthURL({
          secret: options.secret.toString('hex'),
          encoding: 'hex',
          label: options.label,
          type: 'hotp',
          counter: 1,
          issuer: options.issuer,
          algorithm: options.hash,
          digits: options.digits
        })
      }
    }
  }
}
module.exports.hotp = hotp