Skip to content

Commit

Permalink
fix: throw null when sri is empty or bad
Browse files Browse the repository at this point in the history
  • Loading branch information
claudiahdz committed Feb 18, 2020
1 parent 1727a7c commit 11963f2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
23 changes: 16 additions & 7 deletions index.js
Expand Up @@ -177,6 +177,10 @@ class Integrity {
return this.toString()
}

isEmpty () {
return Object.keys(this).length === 0
}

toString (opts) {
opts = ssriOpts(opts)
let sep = opts.sep || ' '
Expand Down Expand Up @@ -240,11 +244,6 @@ class Integrity {
opts = ssriOpts(opts)
const pickAlgorithm = opts.pickAlgorithm
const keys = Object.keys(this)
if (!keys.length) {
throw new Error(`No algorithms available for ${
JSON.stringify(this.toString())
}`)
}
return keys.reduce((acc, algo) => {
return pickAlgorithm(acc, algo) || acc
})
Expand All @@ -253,6 +252,7 @@ class Integrity {

module.exports.parse = parse
function parse (sri, opts) {
if (!sri) return null
opts = ssriOpts(opts)
if (typeof sri === 'string') {
return _parse(sri, opts)
Expand All @@ -271,7 +271,7 @@ function _parse (integrity, opts) {
if (opts.single) {
return new Hash(integrity, opts)
}
return integrity.trim().split(/\s+/).reduce((acc, string) => {
const hashes = integrity.trim().split(/\s+/).reduce((acc, string) => {
const hash = new Hash(string, opts)
if (hash.algorithm && hash.digest) {
const algo = hash.algorithm
Expand All @@ -280,6 +280,7 @@ function _parse (integrity, opts) {
}
return acc
}, new Integrity())
return hashes.isEmpty() ? null : hashes
}

module.exports.stringify = stringify
Expand Down Expand Up @@ -347,7 +348,7 @@ module.exports.checkData = checkData
function checkData (data, sri, opts) {
opts = ssriOpts(opts)
sri = parse(sri, opts)
if (!Object.keys(sri).length) {
if (!sri || !Object.keys(sri).length) {
if (opts.error) {
throw Object.assign(
new Error('No valid integrity hashes to check against'), {
Expand Down Expand Up @@ -386,6 +387,14 @@ module.exports.checkStream = checkStream
function checkStream (stream, sri, opts) {
opts = ssriOpts(opts)
opts.integrity = sri
sri = parse(sri, opts)
if (!sri || !Object.keys(sri).length) {
return Promise.reject(Object.assign(
new Error('No valid integrity hashes to check against'), {
code: 'EINTEGRITY'
}
))
}
const checker = integrityStream(opts)
return new Promise((resolve, reject) => {
stream.pipe(checker)
Expand Down
3 changes: 0 additions & 3 deletions test/integrity.js
Expand Up @@ -125,9 +125,6 @@ test('pickAlgorithm()', t => {
'sha384',
'custom pickAlgorithm function accepted'
)
t.throws(() => {
ssri.parse('').pickAlgorithm()
}, /No algorithms available/, 'SRIs without algorithms are invalid')
t.done()
})

Expand Down

0 comments on commit 11963f2

Please sign in to comment.