Files
shields/services/snyk/snyk-vulnerability-npm.service.js
Caleb Cartwright 2fe61d2c5c Add [Snyk] badges (#2566)
Adds vulnerability badges from Snyk.io, closes #1642 

- [X] Vulnerability badge for GitHub repos
- [x] Vulnerability badge for npm package
2018-12-20 16:28:54 -05:00

67 lines
2.0 KiB
JavaScript

'use strict'
const { NotFound } = require('../errors')
const SynkVulnerabilityBase = require('./snyk-vulnerability-base')
module.exports = class SnykVulnerabilityNpm extends SynkVulnerabilityBase {
static get route() {
return {
base: 'snyk/vulnerabilities/npm',
pattern: ':packageName(.+)',
}
}
static get examples() {
return [
{
title: 'Snyk Vulnerabilities for npm package',
pattern: ':packageName',
namedParams: {
packageName: 'mocha',
},
staticExample: this.render({ vulnerabilities: '0' }),
},
{
title: 'Snyk Vulnerabilities for npm package version',
pattern: ':packageName',
namedParams: {
packageName: 'mocha@4.0.0',
},
staticExample: this.render({ vulnerabilities: '1' }),
},
{
title: 'Snyk Vulnerabilities for npm scoped package',
pattern: ':packageName',
namedParams: {
packageName: '@babel/core',
},
staticExample: this.render({ vulnerabilities: '0' }),
},
]
}
async handle({ packageName }) {
const url = `https://snyk.io/test/npm/${packageName}/badge.svg`
try {
const { vulnerabilities } = await this.fetch({
url,
// Snyk returns an HTTP 200 with an HTML page when the specified
// npm package is not found that contains the text 404.
// Including this in case Snyk starts returning a 404 response code instead.
errorMessages: {
404: 'npm package is invalid or does not exist',
},
})
return this.constructor.render({ vulnerabilities })
} catch (e) {
// If the package is invalid/nonexistent Snyk will return an HTML page
// which will result in an InvalidResponse error being thrown by the valueFromSvgBadge()
// function. Catching it here to switch to a more contextualized error message.
throw new NotFound({
prettyMessage: 'npm package is invalid or does not exist',
})
}
}
}