audit.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const Arborist = require('@npmcli/arborist')
  2. const auditReport = require('npm-audit-report')
  3. const reifyFinish = require('./utils/reify-finish.js')
  4. const auditError = require('./utils/audit-error.js')
  5. const ArboristWorkspaceCmd = require('./workspaces/arborist-cmd.js')
  6. class Audit extends ArboristWorkspaceCmd {
  7. /* istanbul ignore next - see test/lib/load-all-commands.js */
  8. static get description () {
  9. return 'Run a security audit'
  10. }
  11. /* istanbul ignore next - see test/lib/load-all-commands.js */
  12. static get name () {
  13. return 'audit'
  14. }
  15. /* istanbul ignore next - see test/lib/load-all-commands.js */
  16. static get params () {
  17. return [
  18. 'audit-level',
  19. 'dry-run',
  20. 'force',
  21. 'json',
  22. 'package-lock-only',
  23. 'omit',
  24. ...super.params,
  25. ]
  26. }
  27. /* istanbul ignore next - see test/lib/load-all-commands.js */
  28. static get usage () {
  29. return ['[fix]']
  30. }
  31. async completion (opts) {
  32. const argv = opts.conf.argv.remain
  33. if (argv.length === 2)
  34. return ['fix']
  35. switch (argv[2]) {
  36. case 'fix':
  37. return []
  38. default:
  39. throw new Error(argv[2] + ' not recognized')
  40. }
  41. }
  42. exec (args, cb) {
  43. this.audit(args).then(() => cb()).catch(cb)
  44. }
  45. async audit (args) {
  46. const reporter = this.npm.config.get('json') ? 'json' : 'detail'
  47. const opts = {
  48. ...this.npm.flatOptions,
  49. audit: true,
  50. path: this.npm.prefix,
  51. reporter,
  52. workspaces: this.workspaceNames,
  53. }
  54. const arb = new Arborist(opts)
  55. const fix = args[0] === 'fix'
  56. await arb.audit({ fix })
  57. if (fix)
  58. await reifyFinish(this.npm, arb)
  59. else {
  60. // will throw if there's an error, because this is an audit command
  61. auditError(this.npm, arb.auditReport)
  62. const result = auditReport(arb.auditReport, opts)
  63. process.exitCode = process.exitCode || result.exitCode
  64. this.npm.output(result.report)
  65. }
  66. }
  67. }
  68. module.exports = Audit