Skip to content

Commit

Permalink
Further cleaning up
Browse files Browse the repository at this point in the history
  • Loading branch information
mok-seekasia committed Jul 10, 2021
1 parent 5c85a88 commit 0348070
Show file tree
Hide file tree
Showing 32 changed files with 405 additions and 404 deletions.
14 changes: 5 additions & 9 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,14 @@ module.exports = {
parserOptions: {
ecmaVersion: 12,
},
extends: [
'eslint:recommended',
'google',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
extends: ['eslint:recommended', 'google', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended'],
rules: {
'prettier/prettier': 'error',
'arrow-parens': ['error', 'as-needed'],
'max-len': ['error', { code: 160, ignoreUrls: true }],
'arrow-parens': ['error', 'always'],
'max-len': ['error', { code: 140, ignoreUrls: true }],
'object-curly-spacing': ['off'],
indent: ['error', 2, { SwitchCase: 1 }],
// eslint-disable-next-line prettier/prettier
'indent': ['error', 2, { SwitchCase: 1 }],
},
ignorePatterns: ['lib'],
plugins: ['prettier'],
Expand Down
4 changes: 3 additions & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"singleQuote": true
"singleQuote": true,
"printWidth": 140,
"arrowParens": "always"
}
69 changes: 34 additions & 35 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,79 +1,78 @@
## 3.0.0

* TypeScript!
* Less bugs?
* Smaller package size (without building the test files into it)
* Should not have any breaking changes (Most of the test passed), but just in case, I've put it into a major version to continue
* Hope you all like it!
* [TODO:] `/interfaces` still gets build, somehow `exclude` in the config isn't working properly
- TypeScript 🎉
- Lesser bugs
- Smaller build size
- Shouldn't have any breaking changes (according to the written test cases), but let's bump into a major version just in case
- Upgraded `commander` from version `2.19.0` to `8.0.0`

---

## 2.0.5 (June 22, 2021)

* Removed unused packages from dependencies list
* Added nodejs v16.x coverage in CI
- Removed unused packages from dependencies list
- Added nodejs v16.x coverage in CI

## 2.0.4 (June 22, 2021)

### Notable changes

* Simplified the workflow and improved overall performance by running lesser in the process.
* Added [`table`](https://www.npmjs.com/package/table) module to display summaries (Initially used [`cli-table`](https://www.npmjs.com/package/cli-table) for its small size, however the issues in the repo concerns me in its display quality in other OS. Hence, chosen `table` module despite its package size is much bigger)
* Added table display for security report
* Added table display of exceptions from `.nsprc` file
* Cleaned up test cases structure to be more straight forward and easier to maintain
- Simplified the workflow and improved overall performance by running lesser in the process.
- Added [`table`](https://www.npmjs.com/package/table) module to display summaries (Initially used [`cli-table`](https://www.npmjs.com/package/cli-table) for its small size, however the issues in the repo concerns me in its display quality in other OS. Hence, chosen `table` module despite its package size is much bigger)
- Added table display for security report
- Added table display of exceptions from `.nsprc` file
- Cleaned up test cases structure to be more straight forward and easier to maintain

### Breaking changes

* Renamed `--ignore -i` flag to `--exclude -x` for better clarity.
* Removed `--display-full` flag that was used to ignore the maximum display limit. Now with the summary table it would be unlikely to display large size of information.
* Removed `--display-notes` flag that was used for displaying exception notes. Now it is included in the exceptions table.
* Renamed `ignore` field to `active` in `.nsprc` file for better clarity.
* Renamed `reason` field to `notes` in `.nsprc` file for better clarity.
- Renamed `--ignore -i` flag to `--exclude -x` for better clarity.
- Removed `--display-full` flag that was used to ignore the maximum display limit. Now with the summary table it would be unlikely to display large size of information.
- Removed `--display-notes` flag that was used for displaying exception notes. Now it is included in the exceptions table.
- Renamed `ignore` field to `active` in `.nsprc` file for better clarity.
- Renamed `reason` field to `notes` in `.nsprc` file for better clarity.

### Others

* Removed logging of flags used in the command
* Added NPM audit into the CI pipeline
* Added `.github/FUNDING.yml`
* Updated `README.md`
- Removed logging of flags used in the command
- Added NPM audit into the CI pipeline
- Added `.github/FUNDING.yml`
- Updated `README.md`

### Closed issues

* [#20](https://github.com/jeemok/better-npm-audit/issues/20) Provide more output when parsing exceptions file
* [#27](https://github.com/jeemok/better-npm-audit/issues/27) Hide excepted vulnerabilities from output
* [#28](https://github.com/jeemok/better-npm-audit/issues/28) Missing [ in truncation message
- [#20](https://github.com/jeemok/better-npm-audit/issues/20) Provide more output when parsing exceptions file
- [#27](https://github.com/jeemok/better-npm-audit/issues/27) Hide excepted vulnerabilities from output
- [#28](https://github.com/jeemok/better-npm-audit/issues/28) Missing [ in truncation message

---

## 1.12.1 (June 21, 2021)

* Added `FUNDING.yml`
* Updated `README.md`
- Added `FUNDING.yml`
- Updated `README.md`

## 1.12.0 (June 18, 2021)

* [#38](https://github.com/jeemok/better-npm-audit/pull/38) Display warning when `exceptionIds` are unused
- [#38](https://github.com/jeemok/better-npm-audit/pull/38) Display warning when `exceptionIds` are unused

## 1.11.2 (June 11, 2021)

* [#37](https://github.com/jeemok/better-npm-audit/pull/37) Fixed security CVE-2020-28469: Bump glob-parent from 5.1.1 to 5.1.2
- [#37](https://github.com/jeemok/better-npm-audit/pull/37) Fixed security CVE-2020-28469: Bump glob-parent from 5.1.1 to 5.1.2

## 1.11.1 (June 11, 2021)

* Updated `README.md`
- Updated `README.md`

## 1.11.0 (June 11, 2021)

* [#36](https://github.com/jeemok/better-npm-audit/pull/36) Added environment variable support `process.env.NPM_CONFIG_AUDIT_LEVEL` to set the audit level
- [#36](https://github.com/jeemok/better-npm-audit/pull/36) Added environment variable support `process.env.NPM_CONFIG_AUDIT_LEVEL` to set the audit level

## 1.10.1 (June 7, 2021)

* Updated `--full` flag logging from `[full log mode enabled]` to `[report display limit disabled]`
* [#32](https://github.com/jeemok/better-npm-audit/issues/32) Added new flag `--display-notes` to display reasons for the exceptions
- Updated `--full` flag logging from `[full log mode enabled]` to `[report display limit disabled]`
- [#32](https://github.com/jeemok/better-npm-audit/issues/32) Added new flag `--display-notes` to display reasons for the exceptions

## 1.9.3 (June 6, 2021)

* [#31](https://github.com/jeemok/better-npm-audit/issues/31) Added `CHANGELOG.md`
* Updated `README.md`
- [#31](https://github.com/jeemok/better-npm-audit/issues/31) Added `CHANGELOG.md`
- Updated `README.md`
122 changes: 24 additions & 98 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,125 +1,51 @@
#!/usr/bin/env node

const get = require('lodash.get');
const program = require('commander');
const { exec } = require('child_process');
const packageJson = require('./package');
import { Command } from 'commander';
import { exec } from 'child_process';

import { getExceptionsIds, processAuditJson } from 'utils/vulnerability';
import { printSecurityReport } from 'utils/print';
import { isWholeNumber } from 'utils/common';
import { readFile } from 'utils/file';
import { AuditLevel, CommandOptions } from 'src/types';

import { AuditLevel } from 'interfaces/level';
import { NsprcFile } from 'interfaces/nsprc';
import handleInput from './src/handlers/handleInput';
import handleFinish from './src/handlers/handleFinish';

const MAX_BUFFER_SIZE = 1024 * 1000 * 50; // 50 MB

/**
* Process and analyze the NPM audit JSON
* @param {String} jsonBuffer NPM audit stringified JSON payload
* @param {Number} auditLevel The level of vulnerabilities we care about
* @param {Array} exceptionIds List of vulnerability IDs to exclude
* @return {undefined}
*/
export function handleFinish(jsonBuffer: string, auditLevel: AuditLevel, exceptionIds: number[]): void {
const { unhandledIds, vulnerabilityIds, report, failed } = processAuditJson(jsonBuffer, auditLevel, exceptionIds);
import packageJson from './package.json';

// If unable to process the audit JSON
if (failed) {
console.error('Unable to process the JSON buffer string.');
// Exit failed
process.exit(1);
return;
}

// Print the security report
if (report.length) {
printSecurityReport(report);
}

// Grab any un-filtered vulnerabilities at the appropriate level
const unusedExceptionIds = exceptionIds.filter(id => !vulnerabilityIds.includes(id));

// Display the unused exceptionId's
if (unusedExceptionIds.length) {
const messages = [
`${unusedExceptionIds.length} of the excluded vulnerabilities did not match any of the found vulnerabilities: ${unusedExceptionIds.join(', ')}.`,
`${unusedExceptionIds.length > 1 ? 'They' : 'It'} can be removed from the .nsprc file or --exclude -x flags.`,
];
console.warn(messages.join(' '));
}

// Display the found unhandled vulnerabilities
if (unhandledIds.length) {
console.error(`${unhandledIds.length} vulnerabilities found. Node security advisories: ${unhandledIds.join(', ')}`);
// Exit failed
process.exit(1);
} else {
// Happy happy, joy joy
console.info('🤝 All good!');
}
}
const MAX_BUFFER_SIZE = 1024 * 1000 * 50; // 50 MB
const program = new Command();

/**
* Run audit
* @param {String} auditCommand The NPM audit command to use (with flags)
* @param {Number} auditLevel The level of vulnerabilities we care about
* @param {Array} exceptionIds List of vulnerability IDs to exclude
*/
export function audit(auditCommand: string, auditLevel: AuditLevel, exceptionIds: number[]): void {
* @param {String} auditCommand The NPM audit command to use (with flags)
* @param {String} auditLevel The level of vulnerabilities we care about
* @param {Array} exceptionIds List of vulnerability IDs to exclude
*/
export function callback(auditCommand: string, auditLevel: AuditLevel, exceptionIds: number[]): void {
// Increase the default max buffer size (1 MB)
const audit = exec(`${auditCommand} --json`, { maxBuffer: MAX_BUFFER_SIZE });

// Grab the data in chunks and buffer it as we're unable to parse JSON straight from stdout
let jsonBuffer: string = '';
let jsonBuffer = '';

audit.stdout.on('data', (data: string) => (jsonBuffer += data));
if (audit.stdout) {
audit.stdout.on('data', (data: string) => (jsonBuffer += data));
}

// Once the stdout has completed, process the output
audit.stderr.on('close', () => handleFinish(jsonBuffer, auditLevel, exceptionIds));

// stderr
audit.stderr.on('data', console.error);
}

/**
* Handle user's input
* @param {Object} options User's options or flags
* @param {Function} fn The function to handle the inputs
*/
function handleAction(options: NsprcFile, fn: (T1: string, T2: AuditLevel, T3: number[]) => void) {
// Generate NPM Audit command
const auditCommand: string = [
'npm audit',
// flags
get(options, 'production') ? '--production' : '',
].join(' ');

// Taking the audit level from the command or environment variable
const auditLevel = get(options, 'level', process.env.NPM_CONFIG_AUDIT_LEVEL) || 'info';

// Get the exceptions
const nsprc = readFile('.nsprc');
const cmdExceptions: number[] = get(options, 'exclude', '').split(',').filter(isWholeNumber).map(Number);
const exceptionIds: number[] = getExceptionsIds(nsprc, cmdExceptions);

fn(auditCommand, auditLevel, exceptionIds);
if (audit.stderr) {
audit.stderr.on('close', () => handleFinish(jsonBuffer, auditLevel, exceptionIds));
// stderr
audit.stderr.on('data', console.error);
}
}

program.version(packageJson.version);
program.name(packageJson.name).version(packageJson.version);

program
.command('audit')
.description('execute npm audit')
.option('-x, --exclude <ids>', 'Exceptions or the vulnerabilities ID(s) to exclude.')
.option('-l, --level <auditLevel>', 'The minimum audit level to validate.')
.option('-p, --production', 'Skip checking the devDependencies.')
.action((options: NsprcFile) => handleAction(options, audit));
.action((options: CommandOptions) => handleInput(options, callback));

program.parse(process.argv);

module.exports = {
handleFinish,
handleAction,
};
49 changes: 0 additions & 49 deletions interfaces/general.ts

This file was deleted.

9 changes: 0 additions & 9 deletions interfaces/nsprc.ts

This file was deleted.

Loading

0 comments on commit 0348070

Please sign in to comment.