All files / src/classes/MFKDFDerivedKey reconstitution.js

100% Statements 95/95
100% Branches 41/41
100% Functions 9/9
100% Lines 92/92

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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474                    1x 1x 1x 1x 1x                                                               4x   1x                                                               5x   1x                                                             2x   1x                                                                   2x   1x                                                                     2x   1x                                                                     7x   1x                                                                       2x   1x                                                                                 43x 1x   42x 1x   41x 1x   40x   39x 39x 39x 39x     39x 110x 110x 110x                 110x 110x       39x 14x 1x   13x 1x   12x 12x       37x   29x 1x   28x 1x       27x 1x   26x 1x       25x 1x   24x 1x       23x 1x       22x 1x     21x 21x                   21x           21x 21x 21x       29x 29x 1x       28x 28x 2x     26x   26x   26x 69x   69x                     69x   69x                 69x   69x     26x 26x 26x 26x   26x 25x             25x 25x 25x 25x     1x  
/**
 * @file Multi-Factor Derived Key Reconstitution Functions
 * @copyright Multifactor, Inc. 2022–2025
 *
 * @description
 * Operations for reconstituting a multi-factor derived key
 *
 * @author Vivek Nair (https://nair.me) <[email protected]>
 */
 
const { hkdfSync } = require('crypto')
const share = require('../../secrets/share').share
const crypto = require('crypto')
const { decrypt, encrypt } = require('../../crypt')
const { extract } = require('../../integrity')
 
/**
 * Change the threshold of factors needed to derive a multi-factor derived key
 *
 * @example
 * // setup 3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ])
 *
 * // change threshold to 2/3
 * await setup.setThreshold(2)
 *
 * // derive key with 2 factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password1: mfkdf.derive.factors.password('password1'),
 *  password3: mfkdf.derive.factors.password('password3')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {number} threshold - New threshold for key derivation
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function setThreshold (threshold) {
  await this.reconstitute([], [], threshold)
}
module.exports.setThreshold = setThreshold
 
/**
 * Remove a factor used to derive a multi-factor derived key
 *
 * @example
 * // setup 2-of-3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ], {threshold: 2})
 *
 * // remove one of the factors
 * await setup.removeFactor('password2')
 *
 * // derive key with remaining 2 factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password1: mfkdf.derive.factors.password('password1'),
 *  password3: mfkdf.derive.factors.password('password3')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {string} id - ID of existing factor to remove
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function removeFactor (id) {
  await this.reconstitute([id])
}
module.exports.removeFactor = removeFactor
 
/**
 * Remove factors used to derive a multi-factor derived key
 *
 * @example
 * // setup 1-of-3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ], {threshold: 1})
 *
 * // remove two factors
 * await setup.removeFactors(['password1', 'password2'])
 *
 * // derive key with remaining factor
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password3: mfkdf.derive.factors.password('password3')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {Array.<string>} ids - Array of IDs of existing factors to remove
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function removeFactors (ids) {
  await this.reconstitute(ids)
}
module.exports.removeFactors = removeFactors
 
/**
 * Add a factor used to derive a multi-factor derived key
 *
 * @example
 * // setup 2-of-3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ], {threshold: 2})
 *
 * // add fourth factor
 * await setup.addFactor(
 *  await mfkdf.setup.factors.password('password4', { id: 'password4' })
 * )
 *
 * // derive key with any 2 factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password2: mfkdf.derive.factors.password('password2'),
 *  password4: mfkdf.derive.factors.password('password4')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {MFKDFFactor} factor - Factor to add
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function addFactor (factor) {
  await this.reconstitute([], [factor])
}
module.exports.addFactor = addFactor
 
/**
 * Add new factors to derive a multi-factor derived key
 *
 * @example
 * // setup 2-of-3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *   await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *   await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *   await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ], {threshold: 2})
 *
 * // add two more factors
 * await setup.addFactors([
 *   await mfkdf.setup.factors.password('password4', { id: 'password4' }),
 *   await mfkdf.setup.factors.password('password5', { id: 'password5' })
 * ])
 *
 * // derive key with any 2 factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *   password3: mfkdf.derive.factors.password('password3'),
 *   password5: mfkdf.derive.factors.password('password5')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {Array.<MFKDFFactor>} factors - Array of factors to add
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function addFactors (factors) {
  await this.reconstitute([], factors)
}
module.exports.addFactors = addFactors
 
/**
 * Update a factor used to derive a multi-factor derived key
 *
 * @example
 * // setup 3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ])
 *
 * // change the 2nd factor
 * await setup.recoverFactor(
 *  await mfkdf.setup.factors.password('newPassword2', { id: 'password2' })
 * )
 *
 * // derive key with new factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password1: mfkdf.derive.factors.password('password1'),
 *  password2: mfkdf.derive.factors.password('newPassword2'),
 *  password3: mfkdf.derive.factors.password('password3')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {MFKDFFactor} factor - Factor to replace
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function recoverFactor (factor) {
  await this.reconstitute([], [factor])
}
module.exports.recoverFactor = recoverFactor
 
/**
 * Update the factors used to derive a multi-factor derived key
 *
 * @example
 * // setup 3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *  await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *  await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ])
 *
 * // change 2 factors
 * await setup.recoverFactors([
 *  await mfkdf.setup.factors.password('newPassword2', { id: 'password2' }),
 *  await mfkdf.setup.factors.password('newPassword3', { id: 'password3' })
 * ])
 *
 * // derive key with new factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *  password1: mfkdf.derive.factors.password('password1'),
 *  password2: mfkdf.derive.factors.password('newPassword2'),
 *  password3: mfkdf.derive.factors.password('newPassword3')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {Array.<MFKDFFactor>} factors - Array of factors to replace
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function recoverFactors (factors) {
  await this.reconstitute([], factors)
}
module.exports.recoverFactors = recoverFactors
 
/**
 * Reconstitute the factors used to derive a multi-factor derived key
 *
 * @example
 * // setup 2-of-3-factor multi-factor derived key
 * const setup = await mfkdf.setup.key([
 *   await mfkdf.setup.factors.password('password1', { id: 'password1' }),
 *   await mfkdf.setup.factors.password('password2', { id: 'password2' }),
 *   await mfkdf.setup.factors.password('password3', { id: 'password3' })
 * ], {threshold: 2})
 *
 * // remove 1 factor and add 1 new factor
 * await setup.reconstitute(
 *   ['password1'], // remove
 *   [ await mfkdf.setup.factors.password('password4', { id: 'password4' }) ] // add
 * )
 *
 * // derive key with new factors
 * const derived = await mfkdf.derive.key(setup.policy, {
 *   password3: mfkdf.derive.factors.password('password3'),
 *   password4: mfkdf.derive.factors.password('password4')
 * })
 *
 * setup.key.toString('hex') // -> 6458…dc3c
 * derived.key.toString('hex') // -> 6458…dc3c
 *
 * @param {Array.<string>} [removeFactors] - Array of IDs of existing factors to remove
 * @param {Array.<MFKDFFactor>} [addFactors] - Array of factors to add or replace
 * @param {number} [threshold] - New threshold for key derivation; same as current by default
 * @author Vivek Nair (https://nair.me) <[email protected]>
 * @since 0.14.0
 * @memberOf MFKDFDerivedKey
 * @async
 */
async function reconstitute (
  removeFactors = [],
  addFactors = [],
  threshold = this.policy.threshold
) {
  if (!Array.isArray(removeFactors)) {
    throw new TypeError('removeFactors must be an array')
  }
  if (!Array.isArray(addFactors)) {
    throw new TypeError('addFactors must be an array')
  }
  if (!Number.isInteger(threshold)) {
    throw new TypeError('threshold must be an integer')
  }
  if (threshold <= 0) throw new RangeError('threshold must be positive')
 
  const factors = {}
  const material = {}
  const outputs = {}
  const data = {}
 
  // add existing factors
  for (const factor of this.policy.factors.values()) {
    factors[factor.id] = factor
    const pad = Buffer.from(factor.secret, 'base64')
    const secretKey = Buffer.from(
      hkdfSync(
        'sha256',
        this.key,
        Buffer.from(factor.salt, 'base64'),
        'mfkdf2:factor:secret:' + factor.id,
        32
      )
    )
    const factorMaterial = decrypt(pad, secretKey)
    material[factor.id] = factorMaterial
  }
 
  // remove selected factors
  for (const factor of removeFactors) {
    if (typeof factor !== 'string') {
      throw new TypeError('factor must be a string')
    }
    if (typeof factors[factor] !== 'object') {
      throw new RangeError('factor does not exist: ' + factor)
    }
    delete factors[factor]
    delete material[factor]
  }
 
  // add new factors
  for (const factor of addFactors) {
    // type
    if (typeof factor.type !== 'string') {
      throw new TypeError('factor type must be a string')
    }
    if (factor.type.length === 0) {
      throw new RangeError('factor type must not be empty')
    }
 
    // id
    if (typeof factor.id !== 'string') {
      throw new TypeError('factor id must be a string')
    }
    if (factor.id.length === 0) {
      throw new RangeError('factor id must not be empty')
    }
 
    // data
    if (!Buffer.isBuffer(factor.data)) {
      throw new TypeError('factor data must be a buffer')
    }
    if (factor.data.length === 0) {
      throw new RangeError('factor data must not be empty')
    }
 
    // params
    if (typeof factor.params !== 'function') {
      throw new TypeError('factor params must be a function')
    }
 
    // output
    if (typeof factor.output !== 'function') {
      throw new TypeError('factor output must be a function')
    }
 
    const salt = crypto.randomBytes(32)
    const paramsKey = Buffer.from(
      hkdfSync(
        'sha256',
        this.key,
        salt,
        'mfkdf2:factor:params:' + factor.id,
        32
      )
    )
 
    factors[factor.id] = {
      id: factor.id,
      type: factor.type,
      params: await factor.params({ key: paramsKey }),
      salt: salt.toString('base64')
    }
    outputs[factor.id] = await factor.output()
    data[factor.id] = factor.data
    if (Buffer.isBuffer(material[factor.id])) delete material[factor.id]
  }
 
  // new factor id uniqueness
  const ids = addFactors.map((factor) => factor.id)
  if (new Set(ids).size !== ids.length) {
    throw new RangeError('factor ids must be unique')
  }
 
  // threshold correctness
  const n = Object.entries(factors).length
  if (!(threshold <= n)) {
    throw new RangeError('threshold cannot be greater than number of factors')
  }
 
  const shares = share(this.secret, threshold, n)
 
  const newFactors = []
 
  for (const [index, factor] of Object.values(factors).entries()) {
    const share = shares[index]
 
    const stretched = Buffer.isBuffer(material[factor.id])
      ? material[factor.id]
      : Buffer.from(
        hkdfSync(
          'sha256',
          data[factor.id],
          Buffer.from(factor.salt, 'base64'),
          'mfkdf2:factor:pad:' + factor.id,
          32
        )
      )
    factor.pad = encrypt(share, stretched).toString('base64')
 
    const secretKey = Buffer.from(
      hkdfSync(
        'sha256',
        this.key,
        Buffer.from(factor.salt, 'base64'),
        'mfkdf2:factor:secret:' + factor.id,
        32
      )
    )
    factor.secret = encrypt(stretched, secretKey).toString('base64')
 
    newFactors.push(factor)
  }
 
  this.policy.factors = newFactors
  this.policy.threshold = threshold
  this.outputs = outputs
  this.shares = shares
 
  if (this.policy.hmac) {
    const integrityKey = hkdfSync(
      'sha256',
      this.key,
      Buffer.from(this.policy.salt, 'base64'),
      'mfkdf2:integrity',
      32
    )
    const newPolicyData = await extract(this.policy)
    const newHmac = crypto.createHmac('sha256', integrityKey)
    newHmac.update(newPolicyData)
    this.policy.hmac = newHmac.digest('base64')
  }
}
module.exports.reconstitute = reconstitute