All files / fast-redact/lib validator.js

96.55% Statements 28/29
93.75% Branches 15/16
100% Functions 8/8
100% Lines 23/23

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    1x 1x   1x       1x 4x 29x 1x   1x 101x 1x   100x 126x 4x   122x 122x 582x 121x 121x 121x 121x 117x 116x                   29x          
'use strict'
 
const { createContext, runInContext } = require('vm')
const rx = require('./rx')
 
module.exports = validator
 
function validator (opts = {}) {
  const {
    ERR_CENSOR_MUST_NOT_BE_FUNCTION = () => 'fast-redact – censor may not be a function',
    ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be strings',
    ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})`
  } = opts
 
  return function validate ({paths, serialize, censor}) {
    if (typeof censor === 'function') {
      throw Error(ERR_CENSOR_MUST_NOT_BE_FUNCTION())
    }
    paths.forEach((s) => {
      if (typeof s !== 'string') {
        throw Error(ERR_PATHS_MUST_BE_STRINGS())
      }
      try {
        if (/〇/.test(s)) throw Error()
        const proxy = new Proxy({}, {get: () => proxy, set: () => { throw Error() }})
        const expr = s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]')
        rx.lastIndex = 0
        Iif (rx.test(expr) === false) throw Error()
        if (/\n|\r|;/.test(expr)) throw Error()
        if (/\/\*/.test(expr)) throw Error()
        runInContext(`
          (function () {
            'use strict'
            o.${expr}
            if ([o.${expr}].length !== 1) throw Error()
          })()
        `, createContext({o: proxy, 〇: null}), {
          codeGeneration: {strings: false, wasm: false}
        })
      } catch (e) {
        throw Error(ERR_INVALID_PATH(s))
      }
    })
  }
}