Skip to content

Instantly share code, notes, and snippets.

@char0n
Last active September 15, 2021 17:50
Show Gist options
  • Save char0n/2964395223d7943c10396f59df9a8ea0 to your computer and use it in GitHub Desktop.
Save char0n/2964395223d7943c10396f59df9a8ea0 to your computer and use it in GitHub Desktop.

BSD 3-Clause License

Copyright 2020 Vladimír Gorej

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#!/usr/bin/env node
'use strict';
const util = require('util');
const { exec } = require('child_process');
const auditArguments = process.argv
.slice(2)
.filter((arg) => arg !== '--parseable') // we ignore parseable output
.filter((arg) => arg !== '--json'); // we ignore json output
const execAsync = util.promisify(exec);
const execShellCommand = async (cmd) => {
let stdout;
let stderr;
try {
({ stdout, stderr } = await execAsync(cmd, { maxBuffer: 1024 * 1024 * 1024 }));
} catch (error) {
({ stdout, stderr } = error);
}
return stdout || stderr;
};
const parseAuditWhitelist = (ignoredList) => {
try {
return JSON.parse(ignoredList.trim()).map(Number);
} catch (error) {
return [];
}
};
const auditLevelFromArguments = (auditArgs) => {
const concatenatedArguments = auditArgs.join(' ');
const match = concatenatedArguments.match(/--audit-level=(low|moderate|high|critical)/);
return Array.isArray(match) ? match[1] : 'low';
};
const lteLevel = (level) => (advisory) => {
const levelMapping = {
low: 1,
moderate: 2,
high: 3,
critical: 4,
};
const { severity } = advisory;
const severityMapped = levelMapping[severity] || levelMapping.low;
return severityMapped >= levelMapping[level];
};
const isAdvisoryNotWhitelisted = (whitelist) => (advisory) => !whitelist.includes(advisory.id);
(async () => {
const auditLevel = auditLevelFromArguments(auditArguments);
const jsonReport = JSON.parse(
await execShellCommand(`npm audit --json ${auditArguments.join(' ')}`)
);
const whitelist = parseAuditWhitelist(await execShellCommand('npm config get audit-whitelist'));
const advisoriesIds = (jsonReport.advisories ? Object.values(jsonReport.advisories) : [])
.filter(isAdvisoryNotWhitelisted(whitelist))
.filter(lteLevel(auditLevel));
const exitCode = advisoriesIds.length > 0 ? 1 : 0;
if (exitCode === 1 || !process.env.CI) {
const textReport = await execShellCommand(`npm audit ${auditArguments.join(' ')}`);
console.log(textReport);
}
if (exitCode === 1 && whitelist.length > 0 && !process.env.CI) {
console.info(
`Ignoring following security advisories:\n\n ----------------------------------${whitelist
.map(
(advisoryId) =>
`\n https://npmjs.com/advisories/${advisoryId} \n ----------------------------------`
)
.join('')}`
);
}
process.exit(exitCode);
})();
{
"name": "@char0n/npm-audit",
"description": "Wrapper script around `npm audit` with whitelist support",
"version": "0.1.1",
"main": "./npm-audit.js",
"bin": {"npm-audit" : "./npm-audit.js"},
"engines": {
"node": ">=10.21.0",
"npm": ">=6.10.0"
}
}
@char0n
Copy link
Author

char0n commented Aug 6, 2020

Feature list

  • Separate whitelists for production and development dependencies

@char0n
Copy link
Author

char0n commented Sep 15, 2021

This script no longer work on audit format v2 as the format no longer exposes advisories IDs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment