All files / src/classes/MFKDFDerivedKey reconstitution.js

100% Statements 87/87
100% Branches 43/43
100% Functions 9/9
100% Lines 67/67

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                    1x 1x 1x                                                               3x   1x                                                               4x   1x                                                             2x   1x                                                                   2x   1x                                                                     2x   1x                                                                     4x   1x                                                                       2x   1x                                                                         38x 37x 36x 35x   34x 34x 34x 34x     34x 99x 99x 99x 99x 99x 99x       34x 13x 12x 11x 11x       32x   26x 25x     24x 23x     22x 21x     20x     19x   18x         18x 18x 18x       24x 24x     23x 23x   21x   21x   21x 59x 59x       59x   59x 59x     21x 21x 21x 21x   1x  
/**
 * @file Multi-Factor Derived Key Reconstitution Functions
 * @copyright Multifactor 2022 All Rights Reserved
 *
 * @description
 * Operations for reconstituting a multi-factor derived key
 *
 * @author Vivek Nair (https://nair.me) <[email protected]>
 */
 
const { hkdf } = require('@panva/hkdf')
const xor = require('buffer-xor')
const share = require('../../secrets/share').share
 
/**
 * 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' })
 * ], {size: 8})
 *
 * // 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8, 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8, 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8, 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8, 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8})
 *
 * // 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8})
 *
 * // 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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' })
 * ], {size: 8, 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') // -> 64587f2a0e65dc3c
 * derived.key.toString('hex') // -> 64587f2a0e65dc3c
 *
 * @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 [index, factor] of this.policy.factors.entries()) {
    factors[factor.id] = factor
    const pad = Buffer.from(factor.pad, 'base64')
    const share = this.shares[index]
    let factorMaterial = xor(pad, share)
    if (Buffer.byteLength(factorMaterial) > this.policy.size) factorMaterial = factorMaterial.subarray(Buffer.byteLength(factorMaterial) - this.policy.size)
    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')
 
    factors[factor.id] = {
      id: factor.id,
      type: factor.type,
      params: await factor.params({ key: this.key })
    }
    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]
    let stretched = Buffer.isBuffer(material[factor.id])
      ? material[factor.id]
      : Buffer.from(await hkdf('sha512', data[factor.id], '', '', this.policy.size))
 
    if (Buffer.byteLength(share) > this.policy.size) stretched = Buffer.concat([Buffer.alloc(Buffer.byteLength(share) - this.policy.size), stretched])
 
    factor.pad = xor(share, stretched).toString('base64')
    newFactors.push(factor)
  }
 
  this.policy.factors = newFactors
  this.policy.threshold = threshold
  this.outputs = outputs
  this.shares = shares
}
module.exports.reconstitute = reconstitute