diff --git a/lib/index.js b/lib/index.js index b82bdbe..d930add 100644 --- a/lib/index.js +++ b/lib/index.js @@ -4,6 +4,7 @@ const crypto = require('crypto') const MiniPass = require('minipass') const SPEC_ALGORITHMS = ['sha256', 'sha384', 'sha512'] +const DEFAULT_ALGORITHMS = ['sha512'] // TODO: this should really be a hardcoded list of algorithms we support, // rather than [a-z0-9]. @@ -12,19 +13,7 @@ const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/ const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ -const defaultOpts = { - algorithms: ['sha512'], - error: false, - options: [], - pickAlgorithm: getPrioritizedHash, - sep: ' ', - single: false, - strict: false, -} - -const getOptString = options => !options || !options.length - ? '' - : `?${options.join('?')}` +const getOptString = options => options?.length ? `?${options.join('?')}` : '' const _onEnd = Symbol('_onEnd') const _getOptions = Symbol('_getOptions') @@ -42,7 +31,7 @@ class IntegrityStream extends MiniPass { this[_getOptions]() // options used for calculating stream. can't be changed. - const algorithms = opts?.algorithms || defaultOpts.algorithms + const algorithms = opts?.algorithms || DEFAULT_ALGORITHMS this.algorithms = Array.from( new Set(algorithms.concat(this.algorithm ? [this.algorithm] : [])) ) @@ -193,10 +182,7 @@ class Hash { return '' } } - const options = this.options && this.options.length - ? `?${this.options.join('?')}` - : '' - return `${this.algorithm}-${this.digest}${options}` + return `${this.algorithm}-${this.digest}${getOptString(this.options)}` } } @@ -272,7 +258,7 @@ class Integrity { } pickAlgorithm (opts) { - const pickAlgorithm = opts?.pickAlgorithm || defaultOpts.pickAlgorithm; + const pickAlgorithm = opts?.pickAlgorithm || getPrioritizedHash const keys = Object.keys(this) return keys.reduce((acc, algo) => { return pickAlgorithm(acc, algo) || acc @@ -339,7 +325,7 @@ function fromHex (hexDigest, algorithm, opts) { module.exports.fromData = fromData function fromData (data, opts) { - const algorithms = opts?.algorithms || defaultOpts.algorithms + const algorithms = opts?.algorithms || DEFAULT_ALGORITHMS const optString = getOptString(opts?.options) return algorithms.reduce((acc, algo) => { const digest = crypto.createHash(algo).update(data).digest('base64') @@ -451,7 +437,7 @@ function integrityStream (opts = Object.create(null)) { module.exports.create = createIntegrity function createIntegrity (opts) { - const algorithms = opts?.algorithms || defaultOpts.algorithms + const algorithms = opts?.algorithms || DEFAULT_ALGORITHMS const optString = getOptString(opts?.options) const hashes = algorithms.map(crypto.createHash)