├── .circleci ├── circleci-readme.md └── config.yml ├── .eslintrc.js ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md └── pull_request_template.md ├── .gitignore ├── .npmignore ├── .nycrc ├── .prettierrc.js ├── .releaserc ├── .sonatype-config.yml ├── .vscode └── launch.json ├── CHANGELOG.md ├── CONTRIBUTORS.md ├── Jenkinsfile ├── LICENSE ├── NOTICE ├── README.md ├── SECURITY.md ├── assets └── images │ ├── auditjs.png │ └── auditjsnew.png ├── dev-auditjs.json ├── header.txt ├── license-excludes.xml ├── package.json ├── src ├── Application │ ├── Application.spec.ts │ ├── Application.ts │ ├── Logger │ │ └── Logger.ts │ └── Spinner │ │ └── Spinner.ts ├── Audit │ ├── AuditIQServer.spec.ts │ ├── AuditIQServer.ts │ ├── AuditOSSIndex.spec.ts │ ├── AuditOSSIndex.ts │ └── Formatters │ │ ├── Formatter.ts │ │ ├── JsonFormatter.ts │ │ ├── TextFormatter.ts │ │ └── XmlFormatter.ts ├── Config │ ├── AppConfig.ts │ ├── Config.ts │ ├── ConfigPersist.ts │ ├── IqServerConfig.spec.ts │ ├── IqServerConfig.ts │ ├── OssIndexServerConfig.spec.ts │ └── OssIndexServerConfig.ts ├── CycloneDX │ ├── CycloneDXSbomCreator.spec.ts │ ├── CycloneDXSbomCreator.ts │ ├── Helpers │ │ └── Helpers.ts │ ├── Options.ts │ ├── Types │ │ ├── Component.ts │ │ ├── ExternalReference.ts │ │ ├── Hash.ts │ │ └── LicenseContent.ts │ └── typings │ │ ├── parse-packagejson-name │ │ └── index.d.ts │ │ ├── read-installed │ │ └── index.d.ts │ │ └── spdx-license-ids │ │ └── index.d.ts ├── Munchers │ ├── Bower.ts │ ├── Muncher.ts │ ├── NpmList.ts │ └── NpmShrinkwrap.ts ├── Services │ ├── IqRequestService.spec.ts │ ├── IqRequestService.ts │ ├── OssIndexRequestService.spec.ts │ ├── OssIndexRequestService.ts │ ├── RequestHelpers.spec.ts │ └── RequestHelpers.ts ├── Tests │ └── TestHelper.ts ├── Types │ ├── Coordinates.ts │ ├── IqServerResult.ts │ ├── OssIndexCoordinates.ts │ ├── OssIndexServerResult.ts │ └── ReportStatus.ts ├── Visual │ └── VisualHelper.ts ├── Whitelist │ ├── VulnerabilityExcluder.spec.ts │ └── VulnerabilityExcluder.ts └── index.ts ├── tsconfig.development.json ├── tsconfig.json └── yarn.lock /.circleci/circleci-readme.md: -------------------------------------------------------------------------------- 1 | CI Debug Notes 2 | ================ 3 | To validate some circleci stuff, I was able to run a “build locally” using the steps below. 4 | The local build runs in a docker container. 5 | 6 | * (Once) Install circleci client (`brew install circleci`) 7 | 8 | * Convert the “real” config.yml into a self-contained (non-workspace) config via: 9 | 10 | circleci config process .circleci/config.yml > .circleci/local-config.yml 11 | 12 | * Run a local build with the following command: 13 | 14 | circleci local execute -c .circleci/local-config.yml 'build' 15 | 16 | Typically, both commands are run together: 17 | 18 | circleci config process .circleci/config.yml > .circleci/local-config.yml && circleci local execute -c .circleci/local-config.yml 'build' 19 | 20 | With the above command, operations that cannot occur during a local build will show an error like this: 21 | 22 | ``` 23 | ... Error: FAILED with error not supported 24 | ``` 25 | 26 | However, the build will proceed and can complete “successfully”, which allows you to verify scripts in your config, etc. 27 | 28 | If the build does complete successfully, you should see a happy yellow `Success!` message. 29 | 30 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | orbs: 4 | slack: circleci/slack@4.12.5 5 | 6 | executors: 7 | node_executor: 8 | docker: 9 | - image: cimg/node:20.16 10 | 11 | jobs: 12 | build: 13 | working_directory: ~/auditjs 14 | executor: node_executor 15 | steps: 16 | - checkout 17 | - restore_cache: 18 | name: Restore Yarn Package Cache 19 | keys: 20 | - yarn-packages-{{ checksum "yarn.lock" }} 21 | - run: 22 | name: Install Dependencies 23 | command: yarn install 24 | - save_cache: 25 | name: Save Yarn Package Cache 26 | key: yarn-packages-{{ checksum "yarn.lock" }} 27 | paths: 28 | - ~/.cache/yarn 29 | - run: 30 | name: Lint auditjs 31 | command: yarn lint 32 | - run: 33 | name: build 34 | command: yarn build 35 | - run: 36 | name: make test reports directory 37 | command: mkdir reports 38 | - run: 39 | name: test 40 | command: yarn test-ci 41 | # - run: 42 | # name: code coverage 43 | # command: | 44 | # yarn coverage 45 | # yarn generate-coverage-report 46 | - store_test_results: 47 | path: reports 48 | - store_artifacts: 49 | path: ./reports/test-results.xml 50 | - store_artifacts: 51 | path: ./lcov.info 52 | prefix: tests 53 | - run: 54 | name: dogfood scan 55 | command: yarn run start ossi --whitelist dev-auditjs.json 56 | # - slack/notify: 57 | # event: fail 58 | # template: basic_fail_1 59 | # branch_pattern: main 60 | 61 | release: 62 | working_directory: ~/auditjs 63 | executor: node_executor 64 | steps: 65 | - checkout 66 | - run: 67 | name: Allow global installs of npm packages 68 | command: sudo chown -R circleci:circleci /usr/local/lib && sudo chown -R circleci:circleci /usr/local/bin 69 | - run: 70 | name: Install dependencies 71 | command: yarn install 72 | - run: 73 | name: Build auditjs 74 | command: yarn build 75 | - run: 76 | name: Install publishing packages 77 | command: yarn global add semantic-release@latest @semantic-release/changelog @semantic-release/git@latest @semantic-release/npm@latest 78 | - run: 79 | name: Attempt publish 80 | command: yarn exec semantic-release 81 | - slack/notify: 82 | event: fail 83 | template: basic_fail_1 84 | 85 | workflows: 86 | version: 2.1 87 | build_and_release: 88 | jobs: 89 | - build 90 | # - build: 91 | # context: slack_community_oss_fun 92 | - release: 93 | filters: 94 | branches: 95 | only: main 96 | context: 97 | - auditjs 98 | - slack_community_oss_fun 99 | requires: 100 | - build 101 | 102 | build_nightly: 103 | triggers: 104 | - schedule: 105 | cron: "40 20 * * *" 106 | filters: 107 | branches: 108 | only: main 109 | jobs: 110 | - build: 111 | context: slack_community_oss_fun 112 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 3 | extends: [ 4 | 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 5 | 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 6 | 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 7 | ], 8 | parserOptions: { 9 | ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features 10 | sourceType: 'module', // Allows for the use of imports 11 | }, 12 | rules: { 13 | '@typescript-eslint/no-use-before-define': 'off', 14 | 'prefer-spread': 'off', 15 | '@typescript-eslint/no-array-constructor': 'off', 16 | '@typescript-eslint/no-var-requires': 'off', 17 | '@typescript-eslint/no-explicit-any': 'off', 18 | }, 19 | }; 20 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## How to be a contributor to this project 2 | 3 | ### Are you submitting a pull request? 4 | 5 | * Make sure to fill out an issue for your PR, so that we have traceability as to what you are trying to fix, 6 | versus how you fixed it. 7 | * Spaces (not tabs), and 2 of them, that's what we like. Set your code style :) 8 | * Sign the [Sonatype CLA](https://sonatypecla.herokuapp.com/sign-cla) 9 | * Try to fix one thing per pull request! Many people work on this code, so the more focused your changes are, the less 10 | of a headache other people will have when they merge their work in. 11 | * Ensure your Pull Request passes tests either locally or via CircleCI (it will run automatically on your PR) 12 | * Make sure to add yourself or your organization to CONTRIBUTORS.md as a part of your PR, if you are new to the project! 13 | * If you're stuck, ask our [gitter channel](https://gitter.im/sonatype/nexus-developers)! There are a number of 14 | experienced programmers who are happy to help with learning and troubleshooting. 15 | 16 | ### Are you new and looking to dive in? 17 | 18 | * Check our issues to see if there is something you can dive in to. 19 | * Come hang out with us at our [gitter channel](https://gitter.im/sonatype/nexus-developers). 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Run '...' 16 | 2. See error 17 | 18 | **Expected behavior** 19 | A clear and concise description of what you expected to happen. 20 | 21 | **Screenshots** 22 | If applicable, add screenshots to help explain your problem. 23 | 24 | **Desktop (please complete the following information):** 25 | - OS: [e.g. Mac OS X, Linux] 26 | - NodeJS Version: [e.g. 10.0.x] 27 | - Version [e.g. 4.0.0-alpha.0] 28 | 29 | **Additional context** 30 | Add any other context about the problem here. 31 | 32 | cc @bhamail / @DarthHater / @allenhsieh / @Slim-Shary 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | * **What are you trying to do?** 11 | 12 | * **What feature or behavior is this required for?** 13 | 14 | * **How could we solve this issue? (Not knowing is okay!)** 15 | 16 | * **Anything else?** 17 | 18 | cc @bhamail / @DarthHater / @allenhsieh / @ken-duck 19 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | (brief, plain english overview of your changes here) 2 | 3 | This pull request makes the following changes: 4 | * (your change here) 5 | * (another change here) 6 | * (etc) 7 | 8 | (If there are changes to user behavior in general, please make sure to 9 | update the docs, as well) 10 | 11 | It relates to the following issue #s: 12 | * Fixes #X 13 | 14 | cc @bhamail / @DarthHater / @allenhsieh / @ken-duck 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | .DS_Store 3 | /bin/ 4 | auditjs.json 5 | # ci config for local ci build 6 | /.circleci/local-config.yml 7 | # Instanbul code coverage report 8 | .nyc_output/ 9 | reports/ 10 | lcov.info 11 | test-results.xml 12 | # IDEA config files 13 | *.iml 14 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sonatype-nexus-community/auditjs/d18ff4cddc6aab0fe59464e4a338f0e9236bf727/.npmignore -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "exclude": ["**/*/*.spec.ts"] 3 | } 4 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: true, 3 | trailingComma: 'all', 4 | singleQuote: true, 5 | printWidth: 120, 6 | arrowParens: 'always', 7 | tabWidth: 2, 8 | }; 9 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branches": [ 3 | "main", 4 | ], 5 | "plugins": [ 6 | ["@semantic-release/commit-analyzer", { 7 | "preset": "angular", 8 | "releaseRules": [ 9 | { "type": "major-release", "release": "major" } 10 | ] 11 | }], 12 | ["@semantic-release/npm", { 13 | "tarballDir": "dist" 14 | }], 15 | ["@semantic-release/release-notes-generator", { 16 | "preset": "angular", 17 | "writerOpts": { 18 | "commitsSort": ["subject", "scope"] 19 | } 20 | }], 21 | [ 22 | "@semantic-release/github", 23 | { 24 | "assets": "dist/*.tgz" 25 | } 26 | ], 27 | [ 28 | "@semantic-release/changelog", 29 | { 30 | "changelogFile": "CHANGELOG.md" 31 | } 32 | ], 33 | [ 34 | "@semantic-release/git", 35 | { 36 | "assets": ["package.json", "CHANGELOG.md", "package-lock.json"], 37 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" 38 | } 39 | ] 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /.sonatype-config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | iq: 3 | PublicApplication: testapp 4 | application: 5 | IncludeDev: false 6 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "node", 6 | "request": "launch", 7 | "name": "Launch with OSS Index", 8 | "args": ["ossi", "--dev"], 9 | "program": "${workspaceFolder}/src/index.ts", 10 | "preLaunchTask": "tsc: build - tsconfig.json", 11 | "console": "integratedTerminal", 12 | "outFiles": ["${workspaceFolder}/bin/**/*.js"] 13 | }, 14 | { 15 | "type": "node", 16 | "request": "launch", 17 | "name": "Launch with Nexus IQ Server", 18 | "args": ["iq", "-a", "auditjs"], 19 | "program": "${workspaceFolder}/src/index.ts", 20 | "preLaunchTask": "tsc: build - tsconfig.json", 21 | "console": "integratedTerminal", 22 | "outFiles": ["${workspaceFolder}/bin/**/*.js"] 23 | }, 24 | { 25 | "type": "node", 26 | "request": "launch", 27 | "name": "Launch With Config", 28 | "args": ["config"], 29 | "program": "${workspaceFolder}/src/index.ts", 30 | "preLaunchTask": "tsc: build - tsconfig.json", 31 | "console": "integratedTerminal", 32 | "outFiles": ["${workspaceFolder}/bin/**/*.js"] 33 | }, 34 | { 35 | "type": "node", 36 | "request": "launch", 37 | "name": "Launch with Cache clearing", 38 | "args": ["ossi", "--clear"], 39 | "program": "${workspaceFolder}/src/index.ts", 40 | "preLaunchTask": "tsc: build - tsconfig.json", 41 | "console": "integratedTerminal", 42 | "outFiles": ["${workspaceFolder}/bin/**/*.js"] 43 | } 44 | ] 45 | } 46 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [4.0.46](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.45...v4.0.46) (2024-11-13) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * latest mock-fs fixes failing unit tests after other updates, resolve CVE-2024-21538 in cross-spawn 7.0.3 ([7a66cbb](https://github.com/sonatype-nexus-community/auditjs/commit/7a66cbb5f7bd88e2ee6ccff70cb5ca2c88ee4846)) 7 | * resolve CVE-2024-21538 in cross-spawn : 7.0.3 ([4ade2a7](https://github.com/sonatype-nexus-community/auditjs/commit/4ade2a7fd575bb7adf33191e14ab9ee7ef2786a9)) 8 | * resolve CVE-2024-21538 in cross-spawn : 7.0.3 (update CI node version) ([d3378f5](https://github.com/sonatype-nexus-community/auditjs/commit/d3378f5b0c82f201558a74dc1496540f2306c90a)) 9 | * resolve CVE-2024-4068 in braces : 3.0.2 ([d065149](https://github.com/sonatype-nexus-community/auditjs/commit/d06514982d97f9f5258b98e1a6f5731e899b79c4)) 10 | * update CI 'release' target to use latest semantic-release, now that we use newer node version ([e2ac821](https://github.com/sonatype-nexus-community/auditjs/commit/e2ac821e5934a40a8d9f71666d7ca77f77a9984f)) 11 | 12 | ## [4.0.45](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.44...v4.0.45) (2024-01-17) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * use semantic-release version that works with node 18 (newer node causes build errors). ([a122b0e](https://github.com/sonatype-nexus-community/auditjs/commit/a122b0e828066d13c9f39e300ee5fe7df8023bc6)) 18 | 19 | ## [4.0.44](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.43...v4.0.44) (2024-01-10) 20 | 21 | 22 | ### Bug Fixes 23 | 24 | * minor change to trigger release of PR# 276 ([f676f91](https://github.com/sonatype-nexus-community/auditjs/commit/f676f91a4a96b44f95d2e050acbe0f7e0fdd6943)) 25 | 26 | ## [4.0.43](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.42...v4.0.43) (2023-12-13) 27 | 28 | 29 | ### Bug Fixes 30 | 31 | * minor change to trigger release of fix for sonatype-2023-4801 ([032b20a](https://github.com/sonatype-nexus-community/auditjs/commit/032b20a36882fc77ed65134b3b79e1c1d428d42e)) 32 | 33 | ## [4.0.42](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.41...v4.0.42) (2023-12-13) 34 | 35 | 36 | ### Bug Fixes 37 | 38 | * error TS2688: Cannot find type definition file for 'node'. ([#274](https://github.com/sonatype-nexus-community/auditjs/issues/274)) ([2d79b85](https://github.com/sonatype-nexus-community/auditjs/commit/2d79b850bbee6f231518f562b3d506794d206672)) 39 | 40 | ## [4.0.41](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.40...v4.0.41) (2023-07-12) 41 | 42 | 43 | ### Bug Fixes 44 | 45 | * sonatype-2022-3677 in node-fetch 2.6.7 ([d1b15ab](https://github.com/sonatype-nexus-community/auditjs/commit/d1b15abaec2a4626bec5a6b73207cc2e47837a6e)) 46 | 47 | ## [4.0.40](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.39...v4.0.40) (2023-06-22) 48 | 49 | 50 | ### Bug Fixes 51 | 52 | * CVE-2022-25883 in semver : 5.7.1 ([51d1dd0](https://github.com/sonatype-nexus-community/auditjs/commit/51d1dd00b04702f5de258ba6031001cbc4639cc4)) 53 | 54 | ## [4.0.39](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.38...v4.0.39) (2022-10-31) 55 | 56 | 57 | ### Bug Fixes 58 | 59 | * CVE-2022-39353 in @xmldom/xmldom : 0.8.3 ([73b65bd](https://github.com/sonatype-nexus-community/auditjs/commit/73b65bd186e08091840114124694f1f456c27714)) 60 | 61 | ## [4.0.38](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.37...v4.0.38) (2022-10-13) 62 | 63 | 64 | ### Bug Fixes 65 | 66 | * CVE-2022-37616 in @xmldom/xmldom : 0.7.2 ([5269bef](https://github.com/sonatype-nexus-community/auditjs/commit/5269bef10e5bebb7b0e8d342c7156bc47674a4ab)) 67 | 68 | ## [4.0.37](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.36...v4.0.37) (2022-04-20) 69 | 70 | 71 | ### Bug Fixes 72 | 73 | * security(npm): lock colors library to 1.4.0 ([#251](https://github.com/sonatype-nexus-community/auditjs/issues/251)) ([36ae07f](https://github.com/sonatype-nexus-community/auditjs/commit/36ae07fa0588bb77436c06f6d3fa9cc627062628)), closes [#250](https://github.com/sonatype-nexus-community/auditjs/issues/250) 74 | 75 | ## [4.0.36](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.35...v4.0.36) (2022-02-08) 76 | 77 | 78 | ### Bug Fixes 79 | 80 | * sonatype-2021-4879 in minimatch : 3.0.4 ([384a99f](https://github.com/sonatype-nexus-community/auditjs/commit/384a99f4ec56dd1f4ad811d1342f06ea57149911)) 81 | 82 | ## [4.0.35](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.34...v4.0.35) (2022-01-20) 83 | 84 | 85 | ### Bug Fixes 86 | 87 | * CVE-2022-21704 in log4js : 6.3.0 ([b7f1548](https://github.com/sonatype-nexus-community/auditjs/commit/b7f1548527d4866a5dad7cdb252230f4975bd37b)) 88 | 89 | ## [4.0.34](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.33...v4.0.34) (2022-01-20) 90 | 91 | 92 | ### Bug Fixes 93 | 94 | * CVE-2022-0235 in node-fetch : 2.6.1 ([cde4677](https://github.com/sonatype-nexus-community/auditjs/commit/cde4677621066f1087b1111f8bdc233c3ecdfb7d)) 95 | 96 | ## [4.0.33](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.32...v4.0.33) (2021-10-25) 97 | 98 | 99 | ### Bug Fixes 100 | 101 | * Error message formatting ([#248](https://github.com/sonatype-nexus-community/auditjs/issues/248)) ([c8acb04](https://github.com/sonatype-nexus-community/auditjs/commit/c8acb04de235a79686e66d97231c72fb7a961563)), closes [#206](https://github.com/sonatype-nexus-community/auditjs/issues/206) 102 | 103 | ## [4.0.32](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.31...v4.0.32) (2021-09-16) 104 | 105 | 106 | ### Bug Fixes 107 | 108 | * revert fix for SONATYPE-2021-1169, breaks eslint. needs more work ([a7428e2](https://github.com/sonatype-nexus-community/auditjs/commit/a7428e22d29a62dfdb50dd812fd472f16b598260)) 109 | * SONATYPE-2021-1169 ([74abe3c](https://github.com/sonatype-nexus-community/auditjs/commit/74abe3cba69ab75deb756e595ccb6394e2d6a405)) 110 | 111 | ## [4.0.31](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.30...v4.0.31) (2021-09-07) 112 | 113 | 114 | ### Bug Fixes 115 | 116 | * Make caching class return undefined if property does not exist ([#247](https://github.com/sonatype-nexus-community/auditjs/issues/247)) ([8e3b3ad](https://github.com/sonatype-nexus-community/auditjs/commit/8e3b3ad2daaf6eee5a5caf7bcd63cd9fe555d07e)) 117 | * use newer node version in CI release process, required to run semantic-release. ([589e0ce](https://github.com/sonatype-nexus-community/auditjs/commit/589e0cee02a260bde777edef3acd504221896f4f)) 118 | * use newly published @xmldom/xmldom package. fixes [#243](https://github.com/sonatype-nexus-community/auditjs/issues/243) ([9f8b646](https://github.com/sonatype-nexus-community/auditjs/commit/9f8b64689d5cc16591a37065c79c6a82b764040b)) 119 | 120 | ## [4.0.30](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.29...v4.0.30) (2021-08-09) 121 | 122 | 123 | ### Bug Fixes 124 | 125 | * CVE-2021-32796, will change when xmldom@0.7.0 is published on npm ([#242](https://github.com/sonatype-nexus-community/auditjs/issues/242)) ([a6c8e32](https://github.com/sonatype-nexus-community/auditjs/commit/a6c8e327015025b65f681f25b3d31c7d695733a1)) 126 | 127 | ## [4.0.29](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.28...v4.0.29) (2021-08-05) 128 | 129 | 130 | ### Bug Fixes 131 | 132 | * Initial move to yarn ([#241](https://github.com/sonatype-nexus-community/auditjs/issues/241)) ([88b063f](https://github.com/sonatype-nexus-community/auditjs/commit/88b063f66a3998d175e144ef162b550fb892ce6c)) 133 | 134 | ## [4.0.28](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.27...v4.0.28) (2021-08-03) 135 | 136 | 137 | ### Bug Fixes 138 | 139 | * workaround to fix issue [#239](https://github.com/sonatype-nexus-community/auditjs/issues/239). may convert to yarn later ([2056567](https://github.com/sonatype-nexus-community/auditjs/commit/2056567345da061b6823e4b715dfbdc8e4f03eca)) 140 | 141 | ## [4.0.27](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.26...v4.0.27) (2021-07-30) 142 | 143 | 144 | ### Bug Fixes 145 | 146 | * switch to force-resolutions to avoid error when running on a project without a package-lock.json ([a07ae78](https://github.com/sonatype-nexus-community/auditjs/commit/a07ae78f1c0bdcbe606754aa2288dd06150c855d)) 147 | 148 | ## [4.0.26](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.25...v4.0.26) (2021-07-29) 149 | 150 | 151 | ### Bug Fixes 152 | 153 | * avoid ab-end in Application.spec.ts test by using process.exitCode instead of process.exit(). @TNeer rules! ([1e63108](https://github.com/sonatype-nexus-community/auditjs/commit/1e631088da66d45e72aa4c4c90c3ace1560439f1)) 154 | * CWE-20: Improper Input Validation in y18n version 5.0.5 ([1b6a7cb](https://github.com/sonatype-nexus-community/auditjs/commit/1b6a7cbd191433df4bfb6dd992bb6773b16f5604)) 155 | * the releases must flow. remove semantic-release dry-run flag ([9bb8efb](https://github.com/sonatype-nexus-community/auditjs/commit/9bb8efb8308dbae863a63066af61bbd767cec829)) 156 | 157 | ## [4.0.25](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.24...v4.0.25) (2021-03-12) 158 | 159 | 160 | ### Bug Fixes 161 | 162 | * CVE-2021-21366 in commit 4d727dcd ([7875242](https://github.com/sonatype-nexus-community/auditjs/commit/787524261bc23312c01f76172fc84fd5ae29bed8)) 163 | 164 | ## [4.0.24](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.23...v4.0.24) (2021-02-12) 165 | 166 | 167 | ### Bug Fixes 168 | 169 | * Handle relative URLs ([#224](https://github.com/sonatype-nexus-community/auditjs/issues/224)) ([c2e192c](https://github.com/sonatype-nexus-community/auditjs/commit/c2e192c87a3acd00aaf030b216f72aac49217f76)) 170 | 171 | ## [4.0.23](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.22...v4.0.23) (2021-01-11) 172 | 173 | 174 | ### Bug Fixes 175 | 176 | * take whitelist path parameter into account ([#219](https://github.com/sonatype-nexus-community/auditjs/issues/219)) ([f2f14ac](https://github.com/sonatype-nexus-community/auditjs/commit/f2f14aca311ab9a9a1edd9b770e656e912c26dc7)) 177 | 178 | ## [4.0.22](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.21...v4.0.22) (2020-12-18) 179 | 180 | 181 | ### Bug Fixes 182 | 183 | * document release process, test release credentials ([3e5b2ba](https://github.com/sonatype-nexus-community/auditjs/commit/3e5b2ba5ad3df3518ba46ccc7820740e2dd18c51)) 184 | 185 | ## [4.0.21](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.20...v4.0.21) (2020-12-17) 186 | 187 | 188 | ### Bug Fixes 189 | 190 | * Adds insecure flag, implements ([#213](https://github.com/sonatype-nexus-community/auditjs/issues/213)) ([88e7d87](https://github.com/sonatype-nexus-community/auditjs/commit/88e7d873754c96755ee50229115bcee1ecbead2d)) 191 | 192 | ## [4.0.20](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.19...v4.0.20) (2020-11-17) 193 | 194 | 195 | ### Bug Fixes 196 | 197 | * Vulnerability field ([#216](https://github.com/sonatype-nexus-community/auditjs/issues/216)) ([0b91917](https://github.com/sonatype-nexus-community/auditjs/commit/0b91917f0a8ae3dce3c18695b074ea3852219387)) 198 | 199 | ## [4.0.19](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.18...v4.0.19) (2020-11-06) 200 | 201 | 202 | ### Bug Fixes 203 | 204 | * YARGS TO THE FUTURE ([#214](https://github.com/sonatype-nexus-community/auditjs/issues/214)) ([254ea3d](https://github.com/sonatype-nexus-community/auditjs/commit/254ea3dcbe5e4bc0a345b3846ba6fb6ae28cd961)) 205 | 206 | ## [4.0.18](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.17...v4.0.18) (2020-06-04) 207 | 208 | 209 | ### Bug Fixes 210 | 211 | * Bump node-persist version ([#201](https://github.com/sonatype-nexus-community/auditjs/issues/201)) ([144e370](https://github.com/sonatype-nexus-community/auditjs/commit/144e37080c5674865d28e2f9d4116e6f3de08a3e)) 212 | 213 | ## [4.0.17](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.16...v4.0.17) (2020-06-02) 214 | 215 | 216 | ### Bug Fixes 217 | 218 | * Add support of proxy environment variable ([#191](https://github.com/sonatype-nexus-community/auditjs/issues/191)) ([#199](https://github.com/sonatype-nexus-community/auditjs/issues/199)) ([276974d](https://github.com/sonatype-nexus-community/auditjs/commit/276974da21a5bc4fa2996d03586154dabb7052be)) 219 | 220 | ## [4.0.16](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.15...v4.0.16) (2020-05-20) 221 | 222 | 223 | ### Bug Fixes 224 | 225 | * Mention support on README ([e09edfd](https://github.com/sonatype-nexus-community/auditjs/commit/e09edfdc2810035685084e7006438127568593cc)) 226 | 227 | ## [4.0.15](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.14...v4.0.15) (2020-05-08) 228 | 229 | 230 | ### Bug Fixes 231 | 232 | * Pipe cyclonedx sbom to std_out ([#194](https://github.com/sonatype-nexus-community/auditjs/issues/194)) ([9bf2ae0](https://github.com/sonatype-nexus-community/auditjs/commit/9bf2ae0df50290698d5a84d4b43ebc6ae198a1cb)), closes [#195](https://github.com/sonatype-nexus-community/auditjs/issues/195) 233 | 234 | ## [4.0.14](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.13...v4.0.14) (2020-03-27) 235 | 236 | 237 | ### Bug Fixes 238 | 239 | * Bump yargs due to https://github.com/yargs/yargs-parser/pull/258 ([#190](https://github.com/sonatype-nexus-community/auditjs/issues/190)) ([69598e5](https://github.com/sonatype-nexus-community/auditjs/commit/69598e584834b9ae52b43320d9c7da25ac067765)) 240 | 241 | ## [4.0.13](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.12...v4.0.13) (2020-03-24) 242 | 243 | 244 | ### Bug Fixes 245 | 246 | * Allow someone to force a Bower scan, if they so wish ([#182](https://github.com/sonatype-nexus-community/auditjs/issues/182)) ([840e81c](https://github.com/sonatype-nexus-community/auditjs/commit/840e81c9e39b60a03ecce54134a51b5cd5eba7df)) 247 | 248 | ## [4.0.12](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.11...v4.0.12) (2020-03-12) 249 | 250 | 251 | ### Bug Fixes 252 | 253 | * pkg.homepage, not pkg.repository.url ([213e52d](https://github.com/sonatype-nexus-community/auditjs/commit/213e52da1eac425f319693a074819d76308ce5a7)) 254 | 255 | ## [4.0.11](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.10...v4.0.11) (2020-03-12) 256 | 257 | 258 | ### Bug Fixes 259 | 260 | * (bug) Fixed NPE in logger if meta is not passed in ([#183](https://github.com/sonatype-nexus-community/auditjs/issues/183)) ([c113741](https://github.com/sonatype-nexus-community/auditjs/commit/c113741de9dbbcb87a8a509a24a047bb85c34e51)) 261 | 262 | ## [4.0.10](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.9...v4.0.10) (2020-03-04) 263 | 264 | 265 | ### Bug Fixes 266 | 267 | * -d flag *in*cludes dev dependencies, not *ex*cludes ([#181](https://github.com/sonatype-nexus-community/auditjs/issues/181)) ([188b9be](https://github.com/sonatype-nexus-community/auditjs/commit/188b9be1a7755dcc147a3b9ce3a61ecf80805143)) 268 | 269 | ## [4.0.9](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.8...v4.0.9) (2020-03-03) 270 | 271 | 272 | ### Bug Fixes 273 | 274 | * move to formatters ([#180](https://github.com/sonatype-nexus-community/auditjs/issues/180)) ([fa59842](https://github.com/sonatype-nexus-community/auditjs/commit/fa59842d8f57f2371900ca5cc00e21add0dcff81)) 275 | 276 | ## [4.0.8](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.7...v4.0.8) (2020-02-28) 277 | 278 | 279 | ### Bug Fixes 280 | 281 | * add some info on AuditJS and IQ CLI Scanner, and differences ([ca3c119](https://github.com/sonatype-nexus-community/auditjs/commit/ca3c119d62712fce5155bc83cb7ee9b757e9e064)) 282 | * add verbiage to identify some potential differences with using AuditJS vs using the Sonatype Nexus IQ CLI Scanner ([1d5a2d7](https://github.com/sonatype-nexus-community/auditjs/commit/1d5a2d762f9fcdd017103d48b26a94035132880c)) 283 | 284 | ## [4.0.7](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.6...v4.0.7) (2020-02-26) 285 | 286 | 287 | ### Bug Fixes 288 | 289 | * memorialize Allen, through AllenJS ([592fb93](https://github.com/sonatype-nexus-community/auditjs/commit/592fb93e88b4d4837388ea10bea60223c956cca6)) 290 | 291 | ## [4.0.6](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.5...v4.0.6) (2020-02-24) 292 | 293 | 294 | ### Bug Fixes 295 | 296 | * Added Istanbul (not Constantinople) as a code coverage checker ([#173](https://github.com/sonatype-nexus-community/auditjs/issues/173)) ([c7d3536](https://github.com/sonatype-nexus-community/auditjs/commit/c7d353690afcdf6b539f02f837e1671226ecdaf0)) 297 | 298 | ## [4.0.5](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.4...v4.0.5) (2020-02-21) 299 | 300 | 301 | ### Bug Fixes 302 | 303 | * Moving from Winston to Log4JS ([#166](https://github.com/sonatype-nexus-community/auditjs/issues/166)) ([b22a9e0](https://github.com/sonatype-nexus-community/auditjs/commit/b22a9e05751f6b87f26c961ba0e793f783735b8a)) 304 | 305 | ## [4.0.4](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.3...v4.0.4) (2020-02-21) 306 | 307 | 308 | ### Bug Fixes 309 | 310 | * Suggest to run with dev flag if 0 dependencies are found ([#171](https://github.com/sonatype-nexus-community/auditjs/issues/171)) ([39b7d73](https://github.com/sonatype-nexus-community/auditjs/commit/39b7d733c077b2b8f0a5e5bcd2992476f0335e44)) 311 | 312 | ## [4.0.3](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.2...v4.0.3) (2020-02-21) 313 | 314 | 315 | ### Bug Fixes 316 | 317 | * Make sure CycloneDXSbomCreator handles URIs if it runs into a bad one ([#170](https://github.com/sonatype-nexus-community/auditjs/issues/170)) ([d6d24ba](https://github.com/sonatype-nexus-community/auditjs/commit/d6d24ba03ee4e77380bfbf4b277d6041d217e7d4)) 318 | 319 | ## [4.0.2](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.1...v4.0.2) (2020-02-19) 320 | 321 | 322 | ### Bug Fixes 323 | 324 | * Remove some deps ([#165](https://github.com/sonatype-nexus-community/auditjs/issues/165)) ([36d3bde](https://github.com/sonatype-nexus-community/auditjs/commit/36d3bde248a4f36af3ffbf75c189a18f4f036009)) 325 | 326 | ## [4.0.1](https://github.com/sonatype-nexus-community/auditjs/compare/v4.0.0...v4.0.1) (2020-02-18) 327 | 328 | 329 | ### Bug Fixes 330 | 331 | * turn off Dry Run, publish to npm, hang on to your butts ([5a96d2a](https://github.com/sonatype-nexus-community/auditjs/commit/5a96d2aa53ae1d9afad05f8859a88a0f686adea6)) 332 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | A lot of awesome people have contributed to this project! Here they are: 2 | 3 | Sonatype internal people: 4 | 5 | - [@ken-duck](https://github.com/ken-duck/) (Ken Duck) 6 | - [@DarthHater](https://github.com/darthhater/) (Jeffry Hesse) 7 | - [@allenhsieh](https://github.com/allenhsieh) (Allen Hsieh) 8 | - [@ajurgenson55](https://github.com/ajurgenson55) (Artie) 9 | 10 | External contributors: 11 | 12 | - [@francois-roget](https://github.com/francois-roget) (François Roget) for [Ingenico Group](https://github.com/ingenico-group) 13 | - [@tomhooijenga](https://github.com/tomhooijenga) (Tom Hooijenga) 14 | - [@lostunicorn](https://github.com/lostunicorn) (Jeroen De Wachter) 15 | 16 | Possibly You! 17 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | @Library(['private-pipeline-library', 'jenkins-shared']) _ 17 | 18 | dockerizedBuildPipeline( 19 | buildImageId: "${sonatypeDockerRegistryId()}/cdi/node-16", 20 | deployBranch: 'main', 21 | buildAndTest: { 22 | sh ''' 23 | yarn 24 | yarn build 25 | yarn test-ci 26 | # prep for scan of only production dependencies 27 | rm -rf node_modules 28 | yarn install --production --frozen-lockfile 29 | ''' 30 | }, 31 | vulnerabilityScan: { 32 | withDockerImage(env.DOCKER_IMAGE_ID, { 33 | withCredentials([usernamePassword(credentialsId: 'jenkins-saas-service-acct', 34 | usernameVariable: 'IQ_USERNAME', passwordVariable: 'IQ_PASSWORD')]) { 35 | sh 'npx auditjs@latest iq -x -a auditjs -s release -u $IQ_USERNAME -p $IQ_PASSWORD -h https://sonatype.sonatype.app/platform' 36 | } 37 | }) 38 | }, 39 | testResults: [ 'reports/test-results.xml' ], 40 | onFailure: { 41 | notifyChat(currentBuild: currentBuild, env: env, room: 'community-oss-fun') 42 | sendEmailNotification(currentBuild, env, [], 'community-group@sonatype.com') 43 | } 44 | ) 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AuditJS 2 | Copyright 2020 Sonatype. 3 | 4 | This product includes software developed by Erlend Oftedal and Steve Springett and 5 | contains code derived from the @cyclonedx/bom (cyclonedx-node-module) 6 | package distributed on GitHub and npm. The software has been modified to: 7 | 8 | - Be written in TypeScript 9 | - Allow for the ability to exclude license data, or license text 10 | - Changes to how a purl is constructed 11 | 12 | The original code and repository can be found at: https://github.com/CycloneDX/cyclonedx-node-module 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 18 | 19 |

20 | 21 |

22 | 23 | # AuditJS 24 | 25 | [![CircleCI](https://circleci.com/gh/sonatype-nexus-community/auditjs.svg?style=svg)](https://circleci.com/gh/sonatype-nexus-community/auditjs) 26 | 27 | **IMPORTANT NOTE**: Welcome to AuditJS 4.0.0, lots has changed since 3.0.0, mainly around usage. Make sure to read the new docs. 28 | 29 | If you have an issue migrating from AuditJS 3.x to AuditJS 4.x, please [file a GitHub issue here](https://github.com/sonatype-nexus-community/auditjs/issues). 30 | 31 | Audits JavaScript projects using the [OSS Index v3 REST API](https://ossindex.sonatype.org/rest) 32 | to identify known vulnerabilities and outdated package versions. 33 | 34 | Supports any project with package managers that install npm dependencies into a node_modules folder including: 35 | 36 | - npm 37 | - Angular 38 | - yarn 39 | - bower 40 | 41 | 42 | 43 | ## Requirements 44 | 45 | For users wanting to use Nexus IQ Server as their data source for scanning: 46 | 47 | 1. Version 77 or above must be installed. This is when the [Third-Party Scan REST API](https://help.sonatype.com/iqserver/automating/rest-apis/third-party-scan-rest-api---v2) was incorporated into Nexus IQ Server. 48 | 49 | 2. The User performing the scan must have the permission "Can Evaluate Applications", this can be found in the Role Editor > _User_ > Permissions > IQ 50 | 51 | ## Installation 52 | 53 | You can use `auditjs` a number of ways: 54 | 55 | via npx (least permanent install) 56 | 57 | ``` 58 | npx auditjs@latest ossi 59 | ``` 60 | 61 | via global install (most permanent install) 62 | 63 | ``` 64 | npm install -g auditjs 65 | ``` 66 | 67 | We suggest you use it via `npx`, as global installs are generally frowned upon in the nodejs world. 68 | 69 | ## Usage 70 | 71 | `auditjs` supports node LTS versions of 8.x forward at the moment. Usage outside of these node versions will error. 72 | 73 | Note that the OSS Index v3 API is rate limited. If you are seeing errors that 74 | indicate a problem (HTTP code 429) then you may need to make an account at 75 | OSS Index and supply the username and "token". See below for more details. 76 | 77 | ### Generic Usage 78 | 79 | ```terminal 80 | auditjs [command] 81 | 82 | Commands: 83 | auditjs iq [options] Audit this application using Nexus IQ Server 84 | auditjs config Set config for OSS Index or Nexus IQ Server 85 | auditjs ossi [options] Audit this application using Sonatype OSS Index 86 | 87 | Options: 88 | --version Show version number [boolean] 89 | --help Show help [boolean] 90 | ``` 91 | 92 | ### OSS Index Usage 93 | 94 | ```terminal 95 | auditjs ossi [options] 96 | 97 | Audit this application using Sonatype OSS Index 98 | 99 | Options: 100 | --version Show version number [boolean] 101 | --help Show help [boolean] 102 | --user, -u Specify OSS Index username [string] 103 | --password, -p Specify OSS Index password or token [string] 104 | --cache, -c Specify path to use as a cache location [string] 105 | --quiet, -q Only print out vulnerable dependencies [boolean] 106 | --json, -j Set output to JSON [boolean] 107 | --xml, -x Set output to JUnit XML format [boolean] 108 | --whitelist, -w Set path to whitelist file [string] 109 | --clear Clears cache location if it has been set in config [boolean] 110 | --bower Force the application to explicitly scan for Bower [boolean] 111 | ``` 112 | 113 | ### Nexus IQ Server Usage 114 | 115 | ``` 116 | auditjs iq [options] 117 | 118 | Audit this application using Nexus IQ Server 119 | 120 | Options: 121 | --version Show version number [boolean] 122 | --help Show help [boolean] 123 | --application, -a Specify IQ application public ID [string] [required] 124 | --stage, -s Specify IQ app stage 125 | [choices: "develop", "build", "stage-release", "release"] [default: "develop"] 126 | --server, -h Specify IQ server url/port 127 | [string] [default: "http://localhost:8070"] 128 | --timeout, -t Specify an optional timeout in seconds for IQ Server 129 | Polling [number] [default: 300] 130 | --user, -u Specify username for request [string] [default: "admin"] 131 | --password, -p Specify password for request [string] [default: "admin123"] 132 | --artie, -x Artie [boolean] 133 | --dev, -d Include Development Dependencies [boolean] 134 | ``` 135 | 136 | #### AuditJS usage with IQ Server, and what to expect 137 | 138 | ##### TL;DR 139 | 140 | AuditJS should catch most if not the exact same amount of issues as the Sonatype Nexus IQ CLI Scanner. It however can't catch a few cases. If you want total visibility, please use the Sonatype Nexus IQ CLI Scanner. You can use both in tandem, too. 141 | 142 | ##### The full scoop 143 | 144 | AuditJS functions by traversing your `node_modules` folder in your project, so it will pick up the dependencies that are physically installed. This will capture your declared as well as transititive dependencies. Once it has done this, it takes the list and converts it into something that we use to communicate with Sonatype Nexus IQ Server. The crux of this approach is that we do "coordinate" or "name based matching", which we've found to be reliable in the JavaScript ecosystem, but it will not catch corner cases such as if you've: 145 | 146 | - Drug a vulnerable copy of jQuery into your project and left it in a folder (npm does not know about this) 147 | - Copied and pasted code from a project into one of your files 148 | 149 | The Nexus IQ CLI Scanner is equipped to locate and identify cases such as what I've just described. As such if you are using AuditJS, you would not be made aware of these cases, potentially until your code is audited by the IQ CLI Scanner later on. 150 | 151 | It is our suggestion that when you are using this tooling to: 152 | 153 | - Use AuditJS in your dev environments, etc... and use it to scan as early and as often as possible. This will alert you and other developers to using bad dependencies right off the bat. 154 | - Use the Sonatype Nexus IQ CLI Scanner in CI/CD for a more thorough scan, and have development and your Application Security experts evaluate this scan for any "gotchas" 155 | 156 | ### Usage Information 157 | 158 | Execute from inside a node project (above the node_modules directory) to audit 159 | the dependencies. This will audit not only the direct dependencies of the project, 160 | but all **transitive** dependencies. To identify transitive dependencies they must 161 | all be installed for the project under audit. 162 | 163 | If a vulnerability is found to be affecting an installed library the package 164 | header will be highlighted in red and information about the pertinent 165 | vulnerability will be printed to the screen. 166 | 167 | By default we write all silly debug and error data to: 168 | 169 | `YOUR_HOME_DIR/.ossindex/.auditjs.combined.log` 170 | 171 | ``` 172 | { level: 'debug', 173 | message: 'Results audited', 174 | label: 'AuditJS', 175 | timestamp: '2019-12-22T20:09:33.447Z' } 176 | ``` 177 | 178 | ### Usage in CI 179 | 180 | #### Jenkins 181 | 182 | TBD 183 | 184 | #### CircleCI 185 | 186 | We've provided an example repo with a working CircleCI config on a "fake" but real project, you can see how it is all setup by clicking [this link](https://github.com/sonatype-nexus-community/example-auditjs-repo#usage-in-circleci). 187 | 188 | #### TravisCI 189 | 190 | We've provided an example repo with a working TravisCI config on a "fake" but real project, you can see how it is all setup by clicking [this link](https://github.com/sonatype-nexus-community/example-auditjs-repo#usage-in-travisci). 191 | 192 | #### GitHub Actions 193 | 194 | We've provided an example repo with a working GitHub Action on a "fake" but real project, you can see how it is all setup by clicking [this link](https://github.com/sonatype-nexus-community/example-auditjs-repo#usage-with-github-actions). 195 | 196 | #### Proxy integration 197 | 198 | The tool reads the `http_proxy` or `https_proxy` environment variables to perform network request through a Proxy. 199 | 200 | ### Usage As A NPM Script 201 | 202 | `auditjs` can be added as a devDependency to your project, and then an npm script can be added so you can leverage it in your npm scripts. 203 | 204 | You would install `auditjs` like so: 205 | 206 | ``` 207 | $ npm i auditjs -D 208 | ``` 209 | 210 | An example snippet from a `package.json`: 211 | 212 | ``` 213 | }, 214 | "scripts": { 215 | "test": "mocha -r ts-node/register src/**/*.spec.ts", 216 | "build": "tsc -p tsconfig.json", 217 | "build-dev": "tsc -p tsconfig.development.json", 218 | "start": "node ./bin/index.js", 219 | "prepare": "npm run build", 220 | "prepublishOnly": "npm run test", 221 | "scan": "auditjs ossi" 222 | }, 223 | "keywords": [ 224 | ``` 225 | 226 | Now that we've added a `scan` script, you can run `yarn run scan` and your project will invoke `auditjs` and scan your dependencies. This can be handy for local work, or for if you want to run `auditjs` in CI/CD without installing it globally. 227 | 228 | Note: these reference implementations are applicable to running an IQ scan as well. The caveat is that the config for the IQ url and auth needs to either be in the home directory of the user running the job, or stored as (preferably secret) environmental variables. 229 | 230 | ## Config file 231 | 232 | Config is now set via the command line, you can do so by running `auditjs config`. You will be prompted if you'd like to set Nexus IQ Server config or Sonatype OSS Index config. Reasonable defaults are provided for Sonatype Nexus IQ Server that will work for an out of the box install. It is STRONGLY suggested that you do not save your password in config (although it will work), but rather use a token from OSS Index or Nexus IQ Server. 233 | 234 | Config passed in via the command line will be respected over filesystem based config so that you can override specific calls to either Sonatype OSS Index or Nexus IQ Server. Please see usage of either command to see how to set this command line config. 235 | 236 | ## OSS Index Credentials 237 | 238 | The OSS Index API is rate limited to prevent abuse. Guests (non-authorized users) 239 | are restricted to 16 requests of 120 packages each, which replenish at a rate 240 | of one request per minute. This means if you have 600 dependencies, then 5 requests 241 | will be used. No problem! If you have many projects which are run close to each 242 | other you could run into the limit. 243 | 244 | You can either wait for the cool-down period to expire, or make a free account at 245 | OSS Index. By going to the "settings" page for your account, you will see your 246 | "token". Using your username (email address) and this security token you would 247 | have access to 64 requests, which is likely plenty for most use cases. 248 | 249 | Audit.js caches results, which means if you run against multiple projects which 250 | have a common set of dependencies (and they almost certainly will) then you will 251 | not use up requests getting the same results more than once. 252 | 253 | You can specify your credentials on either the command line or the configuration 254 | file. It is almost certainly better to put the credentials in a configuration 255 | file as described above, as using them on the command line is less secure. 256 | 257 | ## Whitelisting 258 | 259 | Whitelisting of vulnerabilities can be done! To accomplish this thus far we have implemented the ability to have a file named `auditjs.json` checked in to your repo ideally, so that it would be at the root where you run `auditjs`. Alternatively you can run `auditjs` with a whitelist file at a different location, with an example such as: 260 | 261 | ```terminal 262 | $ auditjs ossi --whitelist /Users/cooldeveloperperson/code/sonatype-nexus-community/auditjs/auditjs.json 263 | ``` 264 | 265 | The file should look like: 266 | 267 | ```json 268 | { 269 | "ignore": [{ "id": "78a61524-80c5-4371-b6d1-6b32af349043", "reason": "Insert reason here" }] 270 | } 271 | ``` 272 | 273 | The only field that actually matters is `id` and that is the ID you receive from OSS Index for a vulnerability. You can add fields such as `reason` so that you later can understand why you whitelisted a vulnerability. 274 | 275 | Any `id` that is whitelisted will be squelched from the results, and not cause a failure. 276 | 277 | ## Alternative output formats 278 | 279 | `auditjs` can output directly as `json` or as `xml` specifically formatted for JUnit test cases. 280 | 281 | JSON: 282 | 283 | ``` 284 | auditjs ossi --json > file.json 285 | ``` 286 | 287 | XML: 288 | 289 | ``` 290 | auditjs ossi --xml > file.xml 291 | ``` 292 | 293 | We chose to allow output directly to the stdout, so that the user can decide what they want to do with it. If you'd like it to be written to a file by `auditjs` itself, pop in to [this issue](https://github.com/sonatype-nexus-community/auditjs/issues/115) and let us know your thoughts! 294 | 295 | ## Limitations 296 | 297 | As this program depends on the OSS Index database, network access is 298 | required. Connection problems with OSS Index will result in an exception. 299 | 300 | ## How to Fix Vulnerabilities 301 | 302 | Or, "Patient: Hey Doc, it hurts when I do this. Doctor: Then don't do that." 303 | 304 | So you've found a vulnerability. Now what? The best case is to upgrade the vulnerable component to a newer/non-vulnerable 305 | version. However, it is likely the vulnerable component is not a direct dependency, but instead is a transitive dependency 306 | (a dependency of a dependency, of a dependency, wash-rinse-repeat). In such a case, the first step is to figure out which 307 | direct dependency (and sub-dependencies) depend on the vulnerable component. The `npm ls ` 308 | command will print a dependency tree that can lead you through this dependency forest. 309 | 310 | If your project uses yarn, the `yarn why ` command can provide a similar trail of breadcrumbs. 311 | 312 | As an example, suppose we've learned that component `hosted-git-info`, version 2.8.8 is vulnerable (CVE-2021-23362). Use 313 | the command below to find which components depend on this vulnerable component. 314 | ```shell 315 | $ npm ls hosted-git-info 316 | auditjs@4.0.25 /Users/bhamail/sonatype/community/auditjs/auditjs 317 | └─┬ read-installed@4.0.3 318 | └─┬ read-package-json@2.1.2 319 | └─┬ normalize-package-data@2.5.0 320 | └── hosted-git-info@2.8.8 321 | ``` 322 | Now we know the `read-installed@4.0.3` component has a transitive dependency on the vulnerable component `hosted-git-info@2.8.8`. 323 | The best solution would be to upgrade `read-installed` to a newer version that uses a non-vulnerable version of `hosted-git-info`. 324 | As of this writing, however, no such version of `read-installed` exists. The next step is to file an issue with the 325 | `read-installed` project for them to update the vulnerable sub-dependencies. Be sure to read and follow any vulnerability 326 | reporting instructions published by the project: Look for a `SECURITY.md` file, or other instructions on how to report 327 | vulnerabilities. Some projects may prefer you not report the vulnerability publicly. Here's our bug report for this case: 328 | [bug #53](https://github.com/npm/read-installed/issues/53) 329 | 330 | To fix this particular vulnerability in our project, we need some way to force the transitive dependency to a newer version. 331 | This would be relatively easy if we were using yarn (see [yarn's selective dependency resolutions](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/)). 332 | Since we are not using yarn, we will use [npm-force-resolutions](https://github.com/rogeriochaves/npm-force-resolutions). 333 | See the [excellent npm-force-resolutions docs](https://github.com/rogeriochaves/npm-force-resolutions#npm-force-resolutions) 334 | for details on how this works. 335 | 336 | After updating our `package.json` file as described by `npm-force-resolutions`, 337 | ```json 338 | ... 339 | "resolutions": { 340 | "hosted-git-info": "^3.0.8" 341 | }, 342 | "scripts": { 343 | "preinstall": "npx npm-force-resolutions", 344 | ... 345 | ``` 346 | we run `npm install`, and verify 347 | our transitive dependency is updated to a new version. 348 | ```shell 349 | $ rm -rf node_modules && npm install 350 | $ npm ls hosted-git-info 351 | auditjs@4.0.25 /Users/bhamail/sonatype/community/auditjs/auditjs 352 | └─┬ read-installed@4.0.3 353 | └─┬ read-package-json@2.1.1 354 | └─┬ normalize-package-data@2.5.0 355 | └── hosted-git-info@3.0.8 invalid 356 | 357 | npm ERR! invalid: hosted-git-info@3.0.8 /Users/bhamail/sonatype/community/auditjs/auditjs/node_modules/normalize-package-data/node_modules/hosted-git-info 358 | ``` 359 | After updating the transitive dependency, we need to make sure the tests still pass: 360 | ```shell 361 | npm run test 362 | ... 363 | 29 passing (84ms) 364 | ``` 365 | Victory! Commit the changes, and we're done. 366 | 367 | You could also upgrade a higher level transitive dependency: `read-package-json` , like so: 368 | ```shell 369 | "resolutions": { 370 | "read-package-json": "^3.0.1" 371 | }, 372 | ``` 373 | 374 | 375 | ## Credit 376 | 377 | --- 378 | 379 | Thank you to everybody who has contributed to this project, both with 380 | [code contributions](https://github.com/OSSIndex/auditjs/pulls?q=is%3Apr+is%3Aclosed) 381 | and also suggestions, testing help, and notifying us of new and/or missing 382 | vulnerabilities. 383 | 384 | ## Contributing 385 | 386 | We care a lot about making the world a safer place, and that's why we continue to work on this and other plugins for Sonatype OSS Index. If you as well want to speed up the pace of software development by working on this project, jump on in! Before you start work, create a new issue, or comment on an existing issue, to let others know you are! 387 | 388 | ## Releasing 389 | 390 | We use [semantic-release](https://github.com/semantic-release/semantic-release) to generate releases 391 | from commits to the `main` branch. 392 | 393 | For example, to perform a "patch" release, add a commit to `main` with a comment like: 394 | 395 | ``` 396 | fix: Adds insecure flag, implements (#213) 397 | ``` 398 | 399 | ## The Fine Print 400 | 401 | Remember: 402 | 403 | It is worth noting that this is **NOT SUPPORTED** by Sonatype, and is a contribution of ours to the open source 404 | community (read: you!) 405 | 406 | * Use this contribution at the risk tolerance that you have 407 | * Do NOT file Sonatype support tickets related to `ossindex-lib` 408 | * DO file issues here on GitHub, so that the community can pitch in 409 | 410 | Phew, that was easier than I thought. Last but not least of all - have fun! 411 | 412 | ## Getting help 413 | 414 | Looking to contribute to our code but need some help? There's a few ways to get information: 415 | 416 | - Chat with us on the [AuditJS Gitter](https://gitter.im/sonatype-nexus-community/auditjs) or the [Nexus-Developers Gitter](https://gitter.im/sonatype/nexus-developers) 417 | 418 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | # Reporting Security Vulnerabilities 10 | 11 | ## When to report 12 | 13 | First check 14 | [Important advisories of known security vulnerabilities in Sonatype products](https://support.sonatype.com/hc/en-us/sections/203012668-Security-Advisories) 15 | to see if this has been previously reported. 16 | 17 | ## How to report 18 | 19 | Please email reports regarding security related issues you find to [mailto:security@sonatype.com](security@sonatype.com). 20 | 21 | Use our public key below to keep your message safe. 22 | 23 | ## What to include 24 | 25 | Please use a descriptive subject line in your email report. 26 | 27 | Your name and/or affiliation. 28 | 29 | A detailed technical description of the vulnerability, attack scenario and where 30 | possible, how we can reproduce your findings. 31 | 32 | Provide us with a secure way to respond. 33 | 34 | ## What to expect 35 | 36 | Your email will be acknowledged within 1 - 2 business days, and you'll receive a 37 | more detailed response to your email within 7 business days. 38 | 39 | We ask that everyone please follow responsible disclosure practices and allow 40 | time for us to release a fix prior to public release. 41 | 42 | Once an issue is reported, Sonatype uses the following disclosure process: 43 | 44 | When a report is received, we confirm the issue and determine its severity. 45 | 46 | If third-party services or software require mitigation before publication, those 47 | projects will be notified. 48 | 49 | ## Our public key 50 | 51 | ```console 52 | -----BEGIN PUBLIC KEY BLOCK----- 53 | mQENBFF+a9ABCADQWSAAU7w9i71Zn3TQ6k7lT9x57cRdtX7V709oeN/c/1it+gCw 54 | onmmCyf4ypor6XcPSOasp/x0s3hVuf6YfMbI0tSwJUWWihrmoPGIXtmiSOotQE0Q 55 | Sav41xs3YyI9LzQB4ngZR/nhp4YhioD1dVorD6LGXk08rvl2ikoqHwTagbEXZJY7 56 | 3VYhW6JHbZTLwCsfyg6uaSYF1qXfUxHPOiHYKNbhK/tM3giX+9ld/7xi+9f4zEFQ 57 | eX9wcRTdgdDOAqDOK7MV30KXagSqvW0MgEYtKX6q4KjjRzBYjkiTdFW/yMXub/Bs 58 | 5UckxHTCuAmvpr5J0HIUeLtXi1QCkijyn8HJABEBAAG0KVNvbmF0eXBlIFNlY3Vy 59 | aXR5IDxzZWN1cml0eUBzb25hdHlwZS5jb20+iQE4BBMBAgAiBQJRfmvQAhsDBgsJ 60 | CAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAgkmxsNtgwfUzbCACLtCgieq1kJOqo 61 | 2i136ND5ZOj31zIzNENLn8dhSg5zQwTHOcntWAtS8uCNq4fSlslwvlbPYWTLD7fE 62 | iJn1z7BCU8gBk+pkAJJFWEPweMVt+9bYQ4HfKceGbJeuwBBhS34SK9ZIp9gfxxfA 63 | oTm0aGYwKR5wH3sqL/mrhwKhPt9wXR4qwlE635STEX8wzJ5SBqf3ArJUtCp1rzgR 64 | Dx+DiZed5HE1pOI2Kyb6O80bm485WThPXxpvp3bfzTNYoGzeLi/F7WkmgggkXxsT 65 | Pyd0sSx0B/MO4lJtQvEBlIHDFno9mXa30fKl+rzp2geG5UxNHJUjaC5JhfWLEXEX 66 | wV0ErBsmuQENBFF+a9ABCADXj04+GLIz8VCaZH554nUHEhaKoiIXH3Tj7UiMZDqy 67 | o4WIw2RFaCQNA8T0R5Q0yxINU146JQMbA2SN59AGcGYZcajyEvTR7tLG0meMO6S0 68 | JWpkX7s3xaC0s+5SJ/ba00oHGzW0aotgzG9BWA5OniNHK7zZKMVu7M80M/wB1RvK 69 | x775hAeJ+8F9MDJ+ijydBtaOfDdkbg+0kU1xR6Io+vVLPk38ghlWU8QFP4/B0oWi 70 | jK4xiDqK6cG7kyH9kC9nau+ckH8MrJ/RzEpsc4GRwqS4IEnvHWe7XbgydWS1bCp6 71 | 8uP5ma3d02elQmSEa+PABIPKnZcAf1YKLr9O/+IzEdOhABEBAAGJAR8EGAECAAkF 72 | AlF+a9ACGwwACgkQIJJsbDbYMH3WzAf/XOm4YQZFOgG2h9d03m8me8d1vrYico+0 73 | pBYU9iCozLgamM4er9Efb+XzfLvNVKuqyR0cgvGszukIPQYeX58DMrZ07C+E0wDZ 74 | bG+ZAYXT5GqsHkSVnMCVIfyJNLjR4sbVzykyVtnccBL6bP3jxbCP1jJdT7bwiKre 75 | 1jQjvyoL0yIegdiN/oEdmx52Fqjt4NkQsp4sk625UBFTVISr22bnf60ZIGgrRbAP 76 | DU1XMdIrmqmhEEQcXMp4CeflDMksOmaIeAUkZY7eddnXMwQDJTnz5ziCal+1r0R3 77 | dh0XISRG0NkiLEXeGkrs7Sn7BAAsTsaH/1zU6YbvoWlMlHYT6EarFQ== =sFGt 78 | -----END PUBLIC KEY BLOCK----- 79 | ``` 80 | -------------------------------------------------------------------------------- /assets/images/auditjs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sonatype-nexus-community/auditjs/d18ff4cddc6aab0fe59464e4a338f0e9236bf727/assets/images/auditjs.png -------------------------------------------------------------------------------- /assets/images/auditjsnew.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sonatype-nexus-community/auditjs/d18ff4cddc6aab0fe59464e4a338f0e9236bf727/assets/images/auditjsnew.png -------------------------------------------------------------------------------- /dev-auditjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "ignore": [ 3 | ] 4 | } 5 | -------------------------------------------------------------------------------- /header.txt: -------------------------------------------------------------------------------- 1 | Copyright 2019-Present Sonatype Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /license-excludes.xml: -------------------------------------------------------------------------------- 1 | 2 | src/.circleci/circleci-readme.md 3 | src/.github/** 4 | src/.vscode/** 5 | src/bin/** 6 | src/node_modules/** 7 | src/.eslintrc.js 8 | src/.npmignore 9 | src/.nycrc 10 | src/.prettierrc.js 11 | src/.releaserc 12 | src/CHANGELOG.md 13 | src/CONTRIBUTORS.md 14 | src/NOTICE 15 | src/tsconfig.development.json 16 | src/tsconfig.json 17 | src/package.json 18 | src/package-lock.json 19 | src/**/index.d.ts 20 | src/src/CycloneDX/**/*.ts 21 | src/SECURITY.md 22 | 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auditjs", 3 | "version": "4.0.46", 4 | "description": "Audit dependencies to identify known vulnerabilities and maintenance problems", 5 | "main": "./bin/index.js", 6 | "bin": { 7 | "auditjs": "./bin/index.js" 8 | }, 9 | "files": [ 10 | "bin/**/*" 11 | ], 12 | "preferGlobal": true, 13 | "engines": { 14 | "node": ">=8.0.0" 15 | }, 16 | "resolutions": { 17 | "braces": "3.0.3", 18 | "hosted-git-info": "^3.0.8", 19 | "y18n": "^5.0.8", 20 | "minimatch": ">=3.0.5", 21 | "semver": "^7.5.2", 22 | "read-package-json": ">=7.0.0", 23 | "glob": ">=9.3.5", 24 | "cross-spawn": ">=7.0.5" 25 | }, 26 | "scripts": { 27 | "test": "mocha -r ts-node/register src/**/*.spec.ts", 28 | "build": "tsc -p tsconfig.json", 29 | "build-dev": "tsc -p tsconfig.development.json", 30 | "coverage": "nyc mocha -r ts-node/register src/**/*.spec.ts", 31 | "generate-coverage-report": "nyc report --reporter=text-lcov > lcov.info", 32 | "test-ci": "MOCHA_FILE=./reports/test-results.xml mocha -r ts-node/register src/**/*.spec.ts --reporter mocha-junit-reporter", 33 | "lint": "eslint src/**/*.ts", 34 | "start": "node ./bin/index.js", 35 | "prepare": "yarn build", 36 | "prepublishOnly": "yarn test", 37 | "iq-scan": "npx auditjs@latest iq -a auditjs" 38 | }, 39 | "keywords": [ 40 | "Audit", 41 | "Scan", 42 | "Vulnerability", 43 | "CPE", 44 | "CVE", 45 | "CWE", 46 | "OSSIndex", 47 | "Artie", 48 | "Nexus", 49 | "Sonatype", 50 | "SCA", 51 | "SBOM", 52 | "Security", 53 | "Advisories" 54 | ], 55 | "author": "Sonatype Community", 56 | "license": "Apache-2.0", 57 | "repository": { 58 | "type": "git", 59 | "url": "https://github.com/sonatype-nexus-community/auditjs.git" 60 | }, 61 | "devDependencies": { 62 | "@types/chai": "4.2.0", 63 | "@types/chai-as-promised": "7.1.1", 64 | "@types/figlet": "^1.2.0", 65 | "@types/js-yaml": "^3.12.2", 66 | "@types/mocha": "5.2.7", 67 | "@types/mock-fs": "^4.10.0", 68 | "@types/node": "^12.12.27", 69 | "@types/node-fetch": "^2.5.4", 70 | "@types/node-persist": "^3.0.0", 71 | "@types/sinon": "^7.5.1", 72 | "@types/ssri": "^6.0.1", 73 | "@types/uuid": "^9.0.7", 74 | "@types/yargs": "^13.0.8", 75 | "@types/yarnpkg__lockfile": "^1.1.3", 76 | "@typescript-eslint/eslint-plugin": "^6.13.2", 77 | "@typescript-eslint/parser": "^6.13.2", 78 | "@yarnpkg/lockfile": "^1.1.0", 79 | "chai": "4.2.0", 80 | "chai-as-promised": "7.1.1", 81 | "eslint": "^7.1.0", 82 | "eslint-config-prettier": "^6.10.0", 83 | "eslint-plugin-prettier": "^3.1.2", 84 | "mocha": "^8.3.1", 85 | "mocha-junit-reporter": "^1.23.3", 86 | "mock-fs": "^5.4.1", 87 | "nock": "11.7.0", 88 | "nyc": "^15.0.0", 89 | "prettier": "^1.19.1", 90 | "rimraf": "^4.0.0", 91 | "sinon": "^8.0.2", 92 | "ts-node": "^8.5.4", 93 | "typescript": "^5.3.3" 94 | }, 95 | "dependencies": { 96 | "@xmldom/xmldom": "^0.8.5", 97 | "chalk": "^3.0.0", 98 | "colors": "1.4.0", 99 | "figlet": "^1.2.4", 100 | "https-proxy-agent": "^5.0.0", 101 | "js-yaml": "3.13.1", 102 | "log4js": "^6.4.0", 103 | "node-fetch": "^2.6.8", 104 | "node-persist": "^3.1.0", 105 | "ora": "^4.0.3", 106 | "read-installed": "~4.0.3", 107 | "spdx-license-ids": "^3.0.5", 108 | "ssri": "^8.0.1", 109 | "uuid": "^9.0.1", 110 | "xmlbuilder": "^13.0.2", 111 | "yargs": "^16.1.0" 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/Application/Application.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect from '../Tests/TestHelper'; 18 | import { Application } from './Application'; 19 | import sinon, { SinonStub } from 'sinon'; 20 | import { OssIndexRequestService } from '../Services/OssIndexRequestService'; 21 | import { OssIndexServerConfig } from '../Config/OssIndexServerConfig'; 22 | import { TextFormatter } from '../Audit/Formatters/TextFormatter'; 23 | 24 | describe('Application', () => { 25 | afterEach(() => { 26 | sinon.restore(); 27 | }); 28 | 29 | it('merges both CLI and config options for auditWithOSSIndex, with CLI taking precedence', async () => { 30 | const app = new Application(false, true); 31 | const yargs = { 32 | _: ['ossi'], 33 | user: '', 34 | password: 'cli-password', 35 | cache: '', 36 | }; 37 | 38 | sinon.stub(TextFormatter.prototype, 'printAuditResults'); 39 | sinon.stub(OssIndexServerConfig.prototype, 'getConfigFromFile'); 40 | sinon.stub(OssIndexServerConfig.prototype, 'getUsername').returns('config-user'); 41 | sinon.stub(OssIndexServerConfig.prototype, 'getToken').returns('config-password'); 42 | sinon.stub(OssIndexServerConfig.prototype, 'getCacheLocation').returns('config-cache-location'); 43 | let ossIndexRequestService: any = null; 44 | sinon 45 | .stub(OssIndexRequestService.prototype, 'callOSSIndexOrGetFromCache') 46 | .callsFake(async function(this: any): Promise { 47 | // eslint-disable-next-line @typescript-eslint/no-this-alias 48 | ossIndexRequestService = this; 49 | return [ 50 | { 51 | coordinates: '', 52 | reference: '', 53 | vulnerabilities: [], 54 | }, 55 | ]; 56 | }); 57 | await app.startApplication(yargs); 58 | sinon.assert.calledOnce(OssIndexRequestService.prototype.callOSSIndexOrGetFromCache as SinonStub); 59 | expect(ossIndexRequestService).is.instanceOf(OssIndexRequestService); 60 | if (ossIndexRequestService instanceof OssIndexRequestService) { 61 | expect(ossIndexRequestService.user).to.equal('config-user'); 62 | expect(ossIndexRequestService.password).to.equal('cli-password'); 63 | expect(ossIndexRequestService.cacheLocation).to.equal('config-cache-location'); 64 | } 65 | }); 66 | }); 67 | -------------------------------------------------------------------------------- /src/Application/Application.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { textSync } from 'figlet'; 18 | 19 | import { IqRequestService } from '../Services/IqRequestService'; 20 | import { NpmList } from '../Munchers/NpmList'; 21 | import { Coordinates } from '../Types/Coordinates'; 22 | import { Muncher } from '../Munchers/Muncher'; 23 | import { OssIndexRequestService } from '../Services/OssIndexRequestService'; 24 | import { AuditIQServer } from '../Audit/AuditIQServer'; 25 | import { AuditOSSIndex } from '../Audit/AuditOSSIndex'; 26 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 27 | import { ReportStatus } from '../Types/ReportStatus'; 28 | import { Bower } from '../Munchers/Bower'; 29 | import { DEBUG, ERROR, logMessage, createAppLogger, shutDownLoggerAndExit } from './Logger/Logger'; 30 | import { Spinner } from './Spinner/Spinner'; 31 | import { filterVulnerabilities } from '../Whitelist/VulnerabilityExcluder'; 32 | import { IqServerConfig } from '../Config/IqServerConfig'; 33 | import { OssIndexServerConfig } from '../Config/OssIndexServerConfig'; 34 | import { visuallySeperateText } from '../Visual/VisualHelper'; 35 | const pj = require('../../package.json'); 36 | 37 | export class Application { 38 | private results: Array = []; 39 | private sbom = ''; 40 | private muncher: Muncher; 41 | private spinner: Spinner; 42 | 43 | constructor( 44 | readonly devDependency: boolean = false, 45 | readonly silent: boolean = false, 46 | readonly artie: boolean = false, 47 | readonly allen: boolean = false, 48 | readonly scanBower: boolean = false, 49 | ) { 50 | const npmList = new NpmList(devDependency); 51 | const bower = new Bower(devDependency); 52 | 53 | this.printHeader(); 54 | this.spinner = new Spinner(silent); 55 | createAppLogger(); 56 | 57 | if (npmList.isValid() && !this.scanBower) { 58 | logMessage('Setting Muncher to npm list', DEBUG); 59 | this.muncher = npmList; 60 | } else if (bower.isValid()) { 61 | logMessage('Setting Muncher to bower', DEBUG); 62 | this.muncher = bower; 63 | } else { 64 | logMessage( 65 | 'Failed project directory validation. Are you in a (built) node, yarn, or bower project directory?', 66 | 'error', 67 | ); 68 | throw new Error('Could not instantiate muncher'); 69 | } 70 | } 71 | 72 | public async startApplication(args: any): Promise { 73 | if (args._[0] == 'iq') { 74 | logMessage('Attempting to start application', DEBUG); 75 | logMessage('Getting coordinates for Sonatype IQ', DEBUG); 76 | this.spinner.maybeCreateMessageForSpinner('Getting coordinates for Sonatype IQ'); 77 | await this.populateCoordinatesForIQ(); 78 | logMessage(`Coordinates obtained`, DEBUG, this.sbom); 79 | 80 | this.spinner.maybeSucceed(); 81 | logMessage(`Auditing application`, DEBUG, args.application); 82 | this.spinner.maybeCreateMessageForSpinner('Auditing your application with Sonatype IQ'); 83 | await this.auditWithIQ(args); 84 | } else if (args._[0] == 'ossi') { 85 | logMessage('Attempting to start application', DEBUG); 86 | 87 | logMessage('Getting coordinates for Sonatype OSS Index', DEBUG); 88 | this.spinner.maybeCreateMessageForSpinner('Getting coordinates for Sonatype OSS Index'); 89 | await this.populateCoordinates(); 90 | logMessage(`Coordinates obtained`, DEBUG, this.results); 91 | 92 | this.spinner.maybeSucceed(); 93 | logMessage('Auditing your application with Sonatype OSS Index', DEBUG); 94 | this.spinner.maybeCreateMessageForSpinner('Auditing your application with Sonatype OSS Index'); 95 | await this.auditWithOSSIndex(args); 96 | } else if (args._[0] == 'sbom') { 97 | await this.populateCoordinatesForIQ(); 98 | console.log(this.sbom); 99 | } else { 100 | shutDownLoggerAndExit(1); 101 | } 102 | } 103 | 104 | private printHeader(): void { 105 | if (this.silent) { 106 | return; 107 | } else if (this.artie) { 108 | this.doPrintHeader('ArtieJS', 'Ghost'); 109 | } else if (this.allen) { 110 | this.doPrintHeader('AllenJS', 'Ghost'); 111 | } else { 112 | this.doPrintHeader(); 113 | } 114 | } 115 | 116 | private doPrintHeader(title = 'AuditJS', font: figlet.Fonts = '3D-ASCII'): void { 117 | console.log(textSync(title, { font: font, horizontalLayout: 'fitted' })); 118 | console.log(textSync('By Sonatype & Friends', { font: 'Pepper' })); 119 | visuallySeperateText(false, [`${title} version: ${pj.version}`]); 120 | } 121 | 122 | private async populateCoordinates(): Promise { 123 | try { 124 | logMessage('Trying to get dependencies from Muncher', DEBUG); 125 | this.results = await this.muncher.getDepList(); 126 | logMessage('Successfully got dependencies from Muncher', DEBUG); 127 | } catch (e) { 128 | logMessage(`An error was encountered while gathering your dependencies.`, ERROR, { 129 | title: e.message, 130 | stack: e.stack, 131 | }); 132 | shutDownLoggerAndExit(1); 133 | } 134 | } 135 | 136 | private async populateCoordinatesForIQ(): Promise { 137 | try { 138 | logMessage('Trying to get sbom from cyclonedx/bom', DEBUG); 139 | this.sbom = await this.muncher.getSbomFromCommand(); 140 | logMessage('Successfully got sbom from cyclonedx/bom', DEBUG); 141 | } catch (e) { 142 | logMessage(`An error was encountered while gathering your dependencies into an SBOM`, ERROR, { 143 | title: e.message, 144 | stack: e.stack, 145 | }); 146 | shutDownLoggerAndExit(1); 147 | } 148 | } 149 | 150 | private async auditWithOSSIndex(args: any): Promise { 151 | logMessage('Instantiating OSS Index Request Service', DEBUG); 152 | const requestService = this.getOssIndexRequestService(args); 153 | this.spinner.maybeSucceed(); 154 | 155 | logMessage('Submitting coordinates to Sonatype OSS Index', DEBUG); 156 | this.spinner.maybeCreateMessageForSpinner('Submitting coordinates to Sonatype OSS Index'); 157 | 158 | const format = this.muncher instanceof Bower ? 'bower' : 'npm'; 159 | logMessage('Format to query OSS Index picked', DEBUG, { format: format }); 160 | try { 161 | logMessage('Attempting to query OSS Index or use Cache', DEBUG); 162 | const res = await requestService.callOSSIndexOrGetFromCache(this.results, format); 163 | logMessage('Success from OSS Index', DEBUG, res); 164 | this.spinner.maybeSucceed(); 165 | 166 | this.spinner.maybeCreateMessageForSpinner('Reticulating splines'); 167 | logMessage('Turning response into Array', DEBUG); 168 | let ossIndexResults: Array = res.map((y: any) => { 169 | return new OssIndexServerResult(y); 170 | }); 171 | logMessage('Response morphed into Array', DEBUG, { 172 | ossIndexServerResults: ossIndexResults, 173 | }); 174 | this.spinner.maybeSucceed(); 175 | 176 | this.spinner.maybeCreateMessageForSpinner('Removing whitelisted vulnerabilities'); 177 | logMessage('Response being ran against whitelist', DEBUG, { ossIndexServerResults: ossIndexResults }); 178 | ossIndexResults = await filterVulnerabilities(ossIndexResults, args.whitelist); 179 | logMessage('Response has been whitelisted', DEBUG, { ossIndexServerResults: ossIndexResults }); 180 | this.spinner.maybeSucceed(); 181 | 182 | this.spinner.maybeCreateMessageForSpinner('Auditing your results from Sonatype OSS Index'); 183 | logMessage('Instantiating OSS Index Request Service, with quiet option', DEBUG, { quiet: args.quiet }); 184 | const auditOSSIndex = new AuditOSSIndex( 185 | args.quiet ? true : false, 186 | args.json ? true : false, 187 | args.xml ? true : false, 188 | ); 189 | this.spinner.maybeStop(); 190 | 191 | logMessage('Attempting to audit results', DEBUG); 192 | const failed = auditOSSIndex.auditResults(ossIndexResults); 193 | 194 | logMessage('Results audited', DEBUG, { failureCode: failed }); 195 | failed ? shutDownLoggerAndExit(1) : shutDownLoggerAndExit(0); 196 | } catch (e) { 197 | this.spinner.maybeStop(); 198 | logMessage('There was an error auditing with Sonatype OSS Index', ERROR, { title: e.message, stack: e.stack }); 199 | shutDownLoggerAndExit(1); 200 | } 201 | } 202 | 203 | private async auditWithIQ(args: any): Promise { 204 | try { 205 | this.spinner.maybeSucceed(); 206 | this.spinner.maybeCreateMessageForSpinner('Authenticating with Sonatype IQ'); 207 | logMessage('Attempting to connect to Sonatype IQ', DEBUG, args.application); 208 | const requestService = this.getIqRequestService(args); 209 | 210 | this.spinner.maybeSucceed(); 211 | this.spinner.maybeCreateMessageForSpinner('Submitting your dependencies'); 212 | logMessage('Submitting SBOM to Sonatype IQ', DEBUG, this.sbom); 213 | const resultUrl = await requestService.submitToThirdPartyAPI(this.sbom); 214 | 215 | this.spinner.maybeSucceed(); 216 | this.spinner.maybeCreateMessageForSpinner('Checking for results (this could take a minute)'); 217 | logMessage('Polling IQ for report results', DEBUG, resultUrl); 218 | 219 | requestService.asyncPollForResults( 220 | `${resultUrl}`, 221 | (e) => { 222 | this.spinner.maybeFail(); 223 | logMessage('There was an issue auditing your application!', ERROR, { title: e.message, stack: e.stack }); 224 | shutDownLoggerAndExit(1); 225 | }, 226 | (x) => { 227 | this.spinner.maybeSucceed(); 228 | this.spinner.maybeCreateMessageForSpinner('Auditing your results'); 229 | const results: ReportStatus = Object.assign(new ReportStatus(), x); 230 | logMessage('Sonatype IQ results obtained!', DEBUG, results); 231 | 232 | results.reportHtmlUrl = new URL(results.reportHtmlUrl!, requestService.host).href; 233 | 234 | const auditResults = new AuditIQServer(); 235 | 236 | this.spinner.maybeStop(); 237 | logMessage('Auditing results', DEBUG, results); 238 | const failure = auditResults.auditThirdPartyResults(results); 239 | logMessage('Audit finished', DEBUG, { failure: failure }); 240 | 241 | failure ? shutDownLoggerAndExit(1) : shutDownLoggerAndExit(0); 242 | }, 243 | ); 244 | } catch (e) { 245 | this.spinner.maybeFail(); 246 | logMessage('There was an issue auditing your application!', ERROR, { title: e.message, stack: e.stack }); 247 | shutDownLoggerAndExit(1); 248 | } 249 | } 250 | 251 | private getOssIndexRequestService(args: any): OssIndexRequestService { 252 | let config; 253 | try { 254 | config = new OssIndexServerConfig(); 255 | config.getConfigFromFile(); 256 | } catch (e) { 257 | // Ignore config load failure 258 | } 259 | return new OssIndexRequestService( 260 | args?.user || config?.getUsername(), 261 | args?.password || config?.getToken(), 262 | args?.cache || config?.getCacheLocation(), 263 | ); 264 | } 265 | 266 | private getIqRequestService(args: any): IqRequestService { 267 | const config = new IqServerConfig(); 268 | //config.getConfigFromFile(); 269 | if (!config.exists() && !(args.user && args.password && args.server)) 270 | throw new Error( 271 | 'No config file is defined and you are missing one of the -h (host), -u (user), or -p (password) parameters.', 272 | ); 273 | 274 | return new IqRequestService( 275 | args.user !== undefined ? (args.user as string) : config.getUsername(), 276 | args.password !== undefined ? (args.password as string) : config.getToken(), 277 | args.server !== undefined ? (args.server as string) : config.getHost(), 278 | args.application as string, 279 | args.stage as string, 280 | args.timeout as number, 281 | args.insecure as boolean, 282 | ); 283 | } 284 | } 285 | -------------------------------------------------------------------------------- /src/Application/Logger/Logger.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { configure, getLogger, shutdown, addLayout } from 'log4js'; 18 | import { homedir } from 'os'; 19 | import { existsSync, mkdirSync } from 'fs'; 20 | import { join } from 'path'; 21 | 22 | export const DEBUG = 'debug'; 23 | export const ERROR = 'error'; 24 | 25 | const logPath = join(homedir(), '.ossindex'); 26 | 27 | const logPathFile = join(logPath, '.auditjs.combined.log'); 28 | 29 | addLayout('json', function(config) { 30 | return function(logEvent): string { 31 | return JSON.stringify(logEvent) + config.separator; 32 | }; 33 | }); 34 | 35 | configure({ 36 | appenders: { 37 | auditjs: { 38 | type: 'file', 39 | maxLogSize: 2 * 1024 * 1024, 40 | layout: { 41 | type: 'json', 42 | separator: ',', 43 | }, 44 | filename: logPathFile, 45 | }, 46 | out: { type: 'stdout' }, 47 | errors: { type: 'logLevelFilter', appender: 'out', level: 'error', maxLevel: 'error' }, 48 | }, 49 | categories: { 50 | default: { 51 | appenders: ['errors', 'auditjs'], 52 | level: 'error', 53 | }, 54 | }, 55 | }); 56 | 57 | const logger = getLogger('auditjs'); 58 | logger.level = DEBUG; 59 | 60 | export const createAppLogger = (): void => { 61 | if (!existsSync(logPath)) { 62 | mkdirSync(logPath); 63 | } 64 | }; 65 | 66 | const cleanupStack = (message: string): string => { 67 | return message.replace(/^(Error: )+/, 'Error: '); 68 | }; 69 | 70 | export const logMessage = (message: string, level: string, ...meta: any): void => { 71 | if (level == DEBUG) { 72 | logger.debug(message, ...meta); 73 | } else if (level == ERROR) { 74 | if (meta && meta[0] && meta[0].stack) { 75 | logger.error(message, cleanupStack(meta[0].stack)); 76 | } else { 77 | logger.error(message, ...meta); 78 | } 79 | } 80 | }; 81 | 82 | export const shutDownLoggerAndExit = (code: number): void => { 83 | shutdown((err) => { 84 | if (err) { 85 | console.error(err); 86 | } 87 | process.exitCode = code; 88 | }); 89 | }; 90 | -------------------------------------------------------------------------------- /src/Application/Spinner/Spinner.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import ora from 'ora'; 18 | 19 | export class Spinner { 20 | private spinner?: ora.Ora; 21 | 22 | constructor(readonly silent: boolean = false) { 23 | if (!silent) { 24 | this.spinner = ora("Starting application").start(); 25 | this.spinner.succeed(); 26 | } 27 | } 28 | 29 | public maybeCreateMessageForSpinner(message: string) { 30 | if (!this.silent) { 31 | this.spinner?.start(message); 32 | } 33 | } 34 | 35 | public maybeSucceed() { 36 | if (!this.silent) { 37 | this.spinner?.succeed(); 38 | } 39 | } 40 | 41 | public maybeStop() { 42 | if (!this.silent) { 43 | this.spinner?.stop(); 44 | } 45 | } 46 | 47 | public maybeFail() { 48 | if (!this.silent) { 49 | this.spinner?.fail(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Audit/AuditIQServer.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect from '../Tests/TestHelper'; 18 | import { AuditIQServer } from './AuditIQServer'; 19 | import { ReportStatus } from '../Types/ReportStatus'; 20 | import sinon from 'sinon'; 21 | 22 | describe('AuditIQServer', () => { 23 | before(() => { 24 | sinon.stub(console, 'log'); 25 | sinon.stub(console, 'error'); 26 | }); 27 | 28 | after(() => { 29 | sinon.restore(); 30 | }); 31 | 32 | it('should provide a true value if IQ Server Results have policy violations', () => { 33 | const auditIqServer = new AuditIQServer(); 34 | const results = new ReportStatus(); 35 | results.policyAction = 'Failure'; 36 | results.reportHtmlUrl = ''; 37 | const result = auditIqServer.auditThirdPartyResults(results); 38 | expect(result).to.equal(true); 39 | }); 40 | 41 | it('should provide a true value if IQ Server Results have an isError value', () => { 42 | const auditIqServer = new AuditIQServer(); 43 | const results = new ReportStatus(); 44 | results.isError = true; 45 | results.reportHtmlUrl = ''; 46 | const result = auditIqServer.auditThirdPartyResults(results); 47 | expect(result).to.equal(true); 48 | }); 49 | 50 | it('should provide a false value if IQ Server Results have no policy violations', () => { 51 | const auditIqServer = new AuditIQServer(); 52 | const results = new ReportStatus(); 53 | results.policyAction = 'None'; 54 | results.reportHtmlUrl = ''; 55 | const result = auditIqServer.auditThirdPartyResults(results); 56 | expect(result).to.equal(false); 57 | }); 58 | }); 59 | -------------------------------------------------------------------------------- /src/Audit/AuditIQServer.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ReportStatus } from '../Types/ReportStatus'; 18 | import chalk = require('chalk'); 19 | import { visuallySeperateText } from '../Visual/VisualHelper'; 20 | 21 | export class AuditIQServer { 22 | public auditThirdPartyResults(results: ReportStatus): boolean { 23 | if (results.isError) { 24 | visuallySeperateText(true, [results.errorMessage]); 25 | return true; 26 | } 27 | if (results.policyAction === 'Failure') { 28 | visuallySeperateText(true, [ 29 | `Sonabot here, you have some build-breaking policy violations to clean up!`, 30 | chalk.keyword('orange').bold(`Report URL: ${results.reportHtmlUrl}`), 31 | ]); 32 | return true; 33 | } 34 | visuallySeperateText(false, [ 35 | `Wonderbar! No build-breaking violations for this stage. You may still have non-breaking policy violations in the report.`, 36 | chalk.keyword('green').bold(`Report URL: ${results.reportHtmlUrl}`), 37 | ]); 38 | return false; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Audit/AuditOSSIndex.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect, { ossIndexObject, ossIndexObjectNoVulnerabilities } from '../Tests/TestHelper'; 18 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 19 | import { AuditOSSIndex } from './AuditOSSIndex'; 20 | 21 | let auditOSSIndex: AuditOSSIndex; 22 | 23 | const write = (): boolean => { 24 | // NO-OP 25 | return true; 26 | }; 27 | 28 | const oldWrite = process.stdout.write; 29 | 30 | const doAuditOSSIndex = (results: OssIndexServerResult[]): boolean => { 31 | process.stdout.write = write; 32 | const auditResult = auditOSSIndex.auditResults(results); 33 | process.stdout.write = oldWrite; 34 | return auditResult; 35 | }; 36 | 37 | describe('AuditOSSIndex', () => { 38 | beforeEach(() => { 39 | auditOSSIndex = new AuditOSSIndex(); 40 | }); 41 | 42 | it('should return true if OSS Index results have vulnerabilities', () => { 43 | const results = new Array(); 44 | results.push(ossIndexObject); 45 | 46 | const result = doAuditOSSIndex(results); 47 | 48 | expect(result).to.equal(true); 49 | }); 50 | 51 | it('should return true if OSS Index results have vulnerabilities, and json print is chosen', () => { 52 | auditOSSIndex = new AuditOSSIndex(false, true); 53 | const results = new Array(); 54 | results.push(ossIndexObject); 55 | 56 | const result = doAuditOSSIndex(results); 57 | 58 | expect(result).to.equal(true); 59 | }); 60 | 61 | it('should return false if OSS Index results have no vulnerabilities', () => { 62 | const results = new Array(); 63 | results.push(ossIndexObjectNoVulnerabilities); 64 | 65 | const result = doAuditOSSIndex(results); 66 | 67 | expect(result).to.equal(false); 68 | }); 69 | 70 | it('should return false if OSS Index results have no vulnerabilities, and json print is chosen', () => { 71 | auditOSSIndex = new AuditOSSIndex(false, true); 72 | const results = new Array(); 73 | results.push(ossIndexObjectNoVulnerabilities); 74 | 75 | const result = doAuditOSSIndex(results); 76 | 77 | expect(result).to.equal(false); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /src/Audit/AuditOSSIndex.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 18 | import { Formatter, getNumberOfVulnerablePackagesFromResults } from './Formatters/Formatter'; 19 | import { JsonFormatter } from './Formatters/JsonFormatter'; 20 | import { TextFormatter } from './Formatters/TextFormatter'; 21 | import { XmlFormatter } from './Formatters/XmlFormatter'; 22 | 23 | export class AuditOSSIndex { 24 | private formatter: Formatter; 25 | 26 | constructor(readonly quiet: boolean = false, readonly json: boolean = false, readonly xml: boolean = false) { 27 | if (json) { 28 | this.formatter = new JsonFormatter(); 29 | } else if (xml) { 30 | this.formatter = new XmlFormatter(); 31 | } else { 32 | this.formatter = new TextFormatter(quiet); 33 | } 34 | } 35 | 36 | public auditResults(results: Array): boolean { 37 | if (this.quiet) { 38 | results = results.filter((x) => { 39 | return x.vulnerabilities && x.vulnerabilities?.length > 0; 40 | }); 41 | } 42 | 43 | this.formatter.printAuditResults(results); 44 | 45 | return getNumberOfVulnerablePackagesFromResults(results) > 0; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Audit/Formatters/Formatter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { OssIndexServerResult } from '../../Types/OssIndexServerResult'; 18 | 19 | export interface Formatter { 20 | printAuditResults(list: Array): void; 21 | } 22 | 23 | export const getNumberOfVulnerablePackagesFromResults = (results: Array): number => { 24 | return results.filter((x) => { 25 | return x.vulnerabilities && x.vulnerabilities?.length > 0; 26 | }).length; 27 | }; 28 | -------------------------------------------------------------------------------- /src/Audit/Formatters/JsonFormatter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Formatter } from './Formatter'; 18 | import { OssIndexServerResult } from '../../Types/OssIndexServerResult'; 19 | 20 | export class JsonFormatter implements Formatter { 21 | public printAuditResults(list: Array) { 22 | console.log(JSON.stringify(list, null, 2)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Audit/Formatters/TextFormatter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Formatter } from './Formatter'; 18 | import { OssIndexServerResult, Vulnerability } from '../../Types/OssIndexServerResult'; 19 | import chalk = require('chalk'); 20 | 21 | export class TextFormatter implements Formatter { 22 | constructor(readonly quiet: boolean = false) {} 23 | 24 | public printAuditResults(list: Array) { 25 | const total = list.length; 26 | list = list.sort((a, b) => { 27 | return a.coordinates < b.coordinates ? -1 : 1; 28 | }); 29 | 30 | console.log(); 31 | console.group(); 32 | this.printLine('Sonabot here, beep boop beep boop, here are your Sonatype OSS Index results:'); 33 | this.suggestIncludeDevDeps(total); 34 | console.groupEnd(); 35 | console.log(); 36 | 37 | this.printLine('-'.repeat(process.stdout.columns)); 38 | 39 | list.forEach((x: OssIndexServerResult, i: number) => { 40 | if (x.vulnerabilities && x.vulnerabilities.length > 0) { 41 | this.printVulnerability(i, total, x); 42 | } else { 43 | this.printLine(chalk.keyword('green')(`[${i + 1}/${total}] - ${x.toAuditLog()}`)); 44 | } 45 | }); 46 | 47 | this.printLine('-'.repeat(process.stdout.columns)); 48 | } 49 | 50 | private getColorFromMaxScore(maxScore: number, defaultColor = 'chartreuse'): string { 51 | if (maxScore > 8) { 52 | defaultColor = 'red'; 53 | } else if (maxScore > 6) { 54 | defaultColor = 'orange'; 55 | } else if (maxScore > 4) { 56 | defaultColor = 'yellow'; 57 | } 58 | return defaultColor; 59 | } 60 | 61 | private printVulnerability(i: number, total: number, result: OssIndexServerResult): void { 62 | if (!result.vulnerabilities) { 63 | return; 64 | } 65 | const maxScore: number = Math.max( 66 | ...result.vulnerabilities.map((x: Vulnerability) => { 67 | return +x.cvssScore; 68 | }), 69 | ); 70 | const printVuln = (x: Array): void => { 71 | x.forEach((y: Vulnerability) => { 72 | const color: string = this.getColorFromMaxScore(+y.cvssScore); 73 | console.group(); 74 | this.printVulnField(color, `Vulnerability Title: `, y.title); 75 | this.printVulnField(color, `ID: `, y.id); 76 | this.printVulnField(color, `Description: `, y.description); 77 | this.printVulnField(color, `CVSS Score: `, y.cvssScore); 78 | this.printVulnField(color, `CVSS Vector: `, y.cvssVector); 79 | this.printVulnField(color, `CVE: `, y.cve); 80 | this.printVulnField(color, `Reference: `, y.reference); 81 | console.log(); 82 | console.groupEnd(); 83 | }); 84 | }; 85 | 86 | console.log( 87 | chalk.keyword(this.getColorFromMaxScore(maxScore)).bold(`[${i + 1}/${total}] - ${result.toAuditLog()}`), 88 | ); 89 | console.log(); 90 | result.vulnerabilities && 91 | printVuln( 92 | result.vulnerabilities.sort((x, y) => { 93 | return +y.cvssScore - +x.cvssScore; 94 | }), 95 | ); 96 | } 97 | 98 | private printLine(line: any): void { 99 | if (!this.quiet) { 100 | console.log(line); 101 | } 102 | } 103 | 104 | private printVulnField(color: string, title: string, field: string) { 105 | if (typeof field !== 'undefined') { 106 | console.log(chalk.keyword(color)(title), field); 107 | } 108 | } 109 | 110 | private suggestIncludeDevDeps(total: number) { 111 | this.printLine(`Total dependencies audited: ${total}`); 112 | if (total == 0) { 113 | this.printLine( 114 | `We noticed you had 0 dependencies, we exclude devDependencies by default, try running with --dev if you want to include those as well`, 115 | ); 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/Audit/Formatters/XmlFormatter.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as builder from 'xmlbuilder'; 18 | 19 | import { Formatter, getNumberOfVulnerablePackagesFromResults } from './Formatter'; 20 | import { OssIndexServerResult, Vulnerability } from '../../Types/OssIndexServerResult'; 21 | 22 | export class XmlFormatter implements Formatter { 23 | public printAuditResults(list: Array) { 24 | const testsuite = builder.create('testsuite'); 25 | testsuite.att('tests', list.length); 26 | testsuite.att('timestamp', new Date().toISOString()); 27 | testsuite.att('failures', getNumberOfVulnerablePackagesFromResults(list)); 28 | 29 | for (let i = 0; i < list.length; i++) { 30 | const testcase = testsuite.ele('testcase', { classname: list[i].coordinates, name: list[i].coordinates }); 31 | const vulns = list[i].vulnerabilities; 32 | 33 | if (vulns) { 34 | if (vulns.length > 0) { 35 | const failure = testcase.ele('failure'); 36 | let failureText = ''; 37 | for (let j = 0; j < vulns.length; j++) { 38 | failureText += this.getVulnerabilityForXmlBlock(vulns[j]) + '\n'; 39 | } 40 | failure.text(failureText); 41 | failure.att('type', 'Vulnerability detected'); 42 | } 43 | } 44 | } 45 | 46 | const xml = testsuite.end({ pretty: true }); 47 | 48 | console.log(xml); 49 | } 50 | 51 | private getVulnerabilityForXmlBlock(vuln: Vulnerability): string { 52 | let vulnBlock = ''; 53 | vulnBlock += `Vulnerability Title: ${vuln.title}\n`; 54 | vulnBlock += `ID: ${vuln.id}\n`; 55 | vulnBlock += `Description: ${vuln.description}\n`; 56 | vulnBlock += `CVSS Score: ${vuln.cvssScore}\n`; 57 | vulnBlock += `CVSS Vector: ${vuln.cvssVector}\n`; 58 | vulnBlock += `CVE: ${vuln.cve}\n`; 59 | vulnBlock += `Reference: ${vuln.reference}\n`; 60 | 61 | return vulnBlock; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Config/AppConfig.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import readline from 'readline'; 18 | import { OssIndexServerConfig } from './OssIndexServerConfig'; 19 | import { IqServerConfig } from './IqServerConfig'; 20 | import { ConfigPersist } from './ConfigPersist'; 21 | import { join } from 'path'; 22 | import { homedir } from 'os'; 23 | 24 | export class AppConfig { 25 | private rl: readline.Interface; 26 | 27 | constructor() { 28 | this.rl = readline.createInterface({ 29 | input: process.stdin, 30 | output: process.stdout, 31 | }); 32 | } 33 | 34 | public async getConfigFromCommandLine(): Promise { 35 | let username = ''; 36 | let token = ''; 37 | let type = ''; 38 | 39 | type = await this.setVariable( 40 | 'Do you want to set config for Nexus IQ Server or OSS Index? Hit enter for OSS Index, iq for Nexus IQ Server? ', 41 | ); 42 | 43 | if (type == 'iq') { 44 | username = 'admin'; 45 | token = 'admin123'; 46 | 47 | let host = 'http://localhost:8070'; 48 | 49 | username = await this.setVariable(`What is your username (default: ${username})? `, username); 50 | 51 | token = await this.setVariable( 52 | `What is your password/token (pretty please do not save your password to the filesystem, USE A TOKEN) (default: ${token})? `, 53 | token, 54 | ); 55 | 56 | host = await this.setVariable(`What is your IQ Server address (default: ${host})? `, host); 57 | 58 | this.rl.close(); 59 | 60 | const iqConfig = new ConfigPersist(username, token, host.endsWith('/') ? host.slice(0, host.length - 1) : host); 61 | 62 | const config = new IqServerConfig(); 63 | 64 | return config.saveFile(iqConfig); 65 | } else { 66 | let cacheLocation = join(homedir(), '.ossindex', 'auditjs'); 67 | username = await this.setVariable('What is your username? '); 68 | 69 | token = await this.setVariable('What is your token? '); 70 | 71 | cacheLocation = await this.setVariable( 72 | `Where would you like your OSS Index cache saved to (default: ${cacheLocation})? `, 73 | cacheLocation, 74 | ); 75 | 76 | this.rl.close(); 77 | 78 | const ossIndexConfig = new ConfigPersist(username, token, undefined, cacheLocation); 79 | 80 | const config = new OssIndexServerConfig(); 81 | 82 | return config.saveFile(ossIndexConfig); 83 | } 84 | } 85 | 86 | private setVariable(message: string, defaultValue = ''): Promise { 87 | return new Promise((resolve) => { 88 | this.rl.question(message, (answer) => { 89 | resolve(answer || defaultValue); 90 | }); 91 | }); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/Config/Config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import path from 'path'; 18 | import { homedir } from 'os'; 19 | import { mkdirSync, existsSync } from 'fs'; 20 | import { writeFileSync } from 'fs'; 21 | import { safeDump } from 'js-yaml'; 22 | 23 | import { ConfigPersist } from './ConfigPersist'; 24 | 25 | export abstract class Config { 26 | private directoryName = '.ossindex'; 27 | private fileName = '.oss-index-config'; 28 | private configLocation: string; 29 | constructor(protected type: string, protected username: string, protected token: string) { 30 | if (this.type == 'iq') { 31 | this.directoryName = '.iqserver'; 32 | this.fileName = '.iq-server-config'; 33 | } 34 | this.configLocation = path.join(homedir(), this.directoryName, this.fileName); 35 | } 36 | 37 | protected getConfigLocation(): string { 38 | this.tryCreateDirectory(); 39 | return this.configLocation; 40 | } 41 | 42 | private tryCreateDirectory(): void { 43 | if (!existsSync(path.join(homedir(), this.directoryName))) { 44 | mkdirSync(path.join(homedir(), this.directoryName)); 45 | } 46 | return; 47 | } 48 | 49 | public saveFile(objectToSave: ConfigPersist): boolean { 50 | writeFileSync(this.getConfigLocation(), safeDump(objectToSave, { skipInvalid: true })); 51 | this.getConfigFromFile(); 52 | return true; 53 | } 54 | 55 | public exists(): boolean { 56 | return existsSync(this.configLocation); 57 | } 58 | 59 | abstract getConfigFromFile(saveLocation?: string): Config; 60 | } 61 | -------------------------------------------------------------------------------- /src/Config/ConfigPersist.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class ConfigPersist { 18 | constructor( 19 | readonly Username: string, 20 | readonly Token: string, 21 | readonly Server?: string, 22 | readonly CacheLocation?: string, 23 | ) {} 24 | } 25 | -------------------------------------------------------------------------------- /src/Config/IqServerConfig.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect from '../Tests/TestHelper'; 18 | import { IqServerConfig } from './IqServerConfig'; 19 | import mock from 'mock-fs'; 20 | import sinon from 'sinon'; 21 | import os from 'os'; 22 | import { ConfigPersist } from './ConfigPersist'; 23 | 24 | describe('IqServerConfig', async () => { 25 | afterEach(() => { 26 | sinon.restore(); 27 | mock.restore(); 28 | }); 29 | 30 | it('should return true when it is able to save a config file', async () => { 31 | sinon.stub(os, 'homedir').returns('/nonsense'); 32 | mock({ '/nonsense': {} }); 33 | 34 | const config = new IqServerConfig(); 35 | const configPersist = new ConfigPersist('username', 'password', 'http://localhost:8070'); 36 | expect(config.saveFile(configPersist)).to.equal(true); 37 | 38 | const conf = config.getConfigFromFile('/nonsense/.iqserver/.iq-server-config'); 39 | 40 | expect(conf.getUsername()).to.equal('username'); 41 | expect(conf.getToken()).to.equal('password'); 42 | expect(conf.getHost()).to.equal('http://localhost:8070'); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /src/Config/IqServerConfig.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Config } from './Config'; 18 | import { readFileSync } from 'fs'; 19 | import { safeLoad } from 'js-yaml'; 20 | 21 | export class IqServerConfig extends Config { 22 | constructor( 23 | // TODO: Decide if we want to put default values here or leave them blank.. regardless empty strings are not easy to handle 24 | protected username: string = '', 25 | protected token: string = '', 26 | private host: string = '', 27 | ) { 28 | super('iq', username, token); 29 | if (this.exists()) { 30 | this.getConfigFromFile(); 31 | } 32 | } 33 | 34 | public getUsername(): string { 35 | return this.username; 36 | } 37 | 38 | public getToken(): string { 39 | return this.token; 40 | } 41 | 42 | public getHost(): string { 43 | return this.host; 44 | } 45 | 46 | public getConfigFromFile(saveLocation: string = this.getConfigLocation()): IqServerConfig { 47 | const doc = safeLoad(readFileSync(saveLocation, 'utf8')) as IqServerConfigOnDisk; 48 | if (doc && doc.Username && doc.Token && doc.Server) { 49 | super.username = doc.Username; 50 | super.token = doc.Token; 51 | this.host = doc.Server; 52 | } 53 | 54 | return this; 55 | } 56 | } 57 | 58 | interface IqServerConfigOnDisk { 59 | Username?: string; 60 | Token?: string; 61 | Server?: string; 62 | } 63 | -------------------------------------------------------------------------------- /src/Config/OssIndexServerConfig.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect from '../Tests/TestHelper'; 18 | import { OssIndexServerConfig } from './OssIndexServerConfig'; 19 | import mock from 'mock-fs'; 20 | import sinon from 'sinon'; 21 | import os from 'os'; 22 | import { ConfigPersist } from './ConfigPersist'; 23 | 24 | describe('OssIndexServerConfig', async () => { 25 | it('should return true when it is able to save a config file', async () => { 26 | sinon.stub(os, 'homedir').returns('/nonsense'); 27 | mock({ '/nonsense': {} }); 28 | 29 | const config = new OssIndexServerConfig(); 30 | const configPersist = new ConfigPersist('username', 'password', undefined, '/tmp/value'); 31 | expect(config.saveFile(configPersist)).to.equal(true); 32 | 33 | const conf = config.getConfigFromFile('/nonsense/.ossindex/.oss-index-config'); 34 | 35 | expect(conf.getUsername()).to.equal('username'); 36 | expect(conf.getToken()).to.equal('password'); 37 | expect(conf.getCacheLocation()).to.equal('/tmp/value'); 38 | mock.restore(); 39 | sinon.restore(); 40 | }); 41 | 42 | it('should return undefined when property does not exist', async () => { 43 | sinon.stub(os, 'homedir').returns('/nonsense'); 44 | mock({ '/nonsense': {} }); 45 | 46 | const conf = new OssIndexServerConfig(); 47 | 48 | expect(conf.getUsername()).to.equal(undefined); 49 | expect(conf.getToken()).to.equal(undefined); 50 | expect(conf.getCacheLocation()).to.equal(undefined); 51 | 52 | mock.restore(); 53 | sinon.restore(); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /src/Config/OssIndexServerConfig.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Config } from './Config'; 18 | import { readFileSync } from 'fs'; 19 | import { safeLoad } from 'js-yaml'; 20 | import storage from 'node-persist'; 21 | 22 | export class OssIndexServerConfig extends Config { 23 | constructor(protected username: string = '', protected token: string = '', protected cacheLocation: string = '') { 24 | super('ossi', username, token); 25 | if (this.exists()) { 26 | this.getConfigFromFile(); 27 | } 28 | } 29 | 30 | public getUsername(): string | undefined { 31 | if (this.username != '') { 32 | return this.username; 33 | } 34 | return undefined; 35 | } 36 | 37 | public getToken(): string | undefined { 38 | if (this.token != '') { 39 | return this.token; 40 | } 41 | return undefined; 42 | } 43 | 44 | public getCacheLocation(): string | undefined { 45 | if (this.cacheLocation != '') { 46 | return this.cacheLocation; 47 | } 48 | return undefined; 49 | } 50 | 51 | public async clearCache(): Promise { 52 | try { 53 | await storage.init({ dir: this.cacheLocation }); 54 | await storage.clear(); 55 | return true; 56 | } catch (error) { 57 | // It's likely an error would only ever occur if there was a permission based issue, so log it and move on 58 | console.log(error); 59 | return false; 60 | } 61 | } 62 | 63 | public getConfigFromFile(saveLocation: string = this.getConfigLocation()): OssIndexServerConfig { 64 | const doc = safeLoad(readFileSync(saveLocation, 'utf8')) as OssIndexServerConfigOnDisk; 65 | if (doc && doc.Username) { 66 | this.username = doc.Username; 67 | } 68 | if (doc && doc.Token) { 69 | this.token = doc.Token; 70 | } 71 | if (doc && doc.CacheLocation) { 72 | this.cacheLocation = doc.CacheLocation; 73 | } 74 | 75 | return this; 76 | } 77 | } 78 | 79 | interface OssIndexServerConfigOnDisk { 80 | Username?: string; 81 | Token?: string; 82 | CacheLocation?: string; 83 | } 84 | -------------------------------------------------------------------------------- /src/CycloneDX/CycloneDXSbomCreator.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { CycloneDXSbomCreator } from './CycloneDXSbomCreator'; 18 | import expect from '../Tests/TestHelper'; 19 | 20 | // Test object with circular dependency, scoped dependency, dependency with dependency 21 | const object = { 22 | name: 'testproject', 23 | version: '1.0.0', 24 | description: 'Test Description', 25 | dependencies: { 26 | testdependency: { 27 | name: 'testdependency', 28 | version: '1.0.1', 29 | bugs: { 30 | url: 'git+ssh://git@github.com/slackhq/csp-html-webpack-plugin.git', 31 | }, 32 | dependencies: { 33 | testdependency: { 34 | name: 'testdependency', 35 | version: '1.0.1', 36 | }, 37 | }, 38 | }, 39 | testdependency2: { 40 | name: 'testdependency2', 41 | version: '1.0.2', 42 | repository: { 43 | url: 'git@slack-github.com:anuj/csp-html-webpack-plugin.git', 44 | }, 45 | dependencies: { 46 | testdependency: { 47 | name: 'testdependency', 48 | version: '1.0.0', 49 | }, 50 | }, 51 | }, 52 | '@scope/testdependency3': { 53 | name: '@scope/testdependency3', 54 | version: '1.0.2', 55 | }, 56 | }, 57 | }; 58 | 59 | const expectedResponse = `testdependency1.0.1pkg:npm/testdependency@1.0.1git+ssh://git@github.com/slackhq/csp-html-webpack-plugin.gittestdependency21.0.2pkg:npm/testdependency2@1.0.2testdependency1.0.0pkg:npm/testdependency@1.0.0@scopetestdependency31.0.2pkg:npm/%40scope/testdependency3@1.0.2`; 60 | 61 | const expectedSpartanResponse = `testdependency1.0.1pkg:npm/testdependency@1.0.1testdependency21.0.2pkg:npm/testdependency2@1.0.2testdependency1.0.0pkg:npm/testdependency@1.0.0@scopetestdependency31.0.2pkg:npm/%40scope/testdependency3@1.0.2`; 62 | 63 | describe('CycloneDXSbomCreator', async () => { 64 | it('should create an sbom string given a minimal valid object', async () => { 65 | const sbomCreator = new CycloneDXSbomCreator(process.cwd()); 66 | 67 | const string = await sbomCreator.createBom(object); 68 | 69 | expect(string).to.eq(expectedResponse); 70 | }); 71 | 72 | it('should create a spartan sbom string given a minimal valid object', async () => { 73 | const sbomCreator = new CycloneDXSbomCreator(process.cwd(), { spartan: true }); 74 | 75 | const string = await sbomCreator.createBom(object); 76 | 77 | expect(string).to.eq(expectedSpartanResponse); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /src/CycloneDX/CycloneDXSbomCreator.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /// 18 | /// 19 | 20 | import { Options } from './Options'; 21 | import { v4 as uuidv4 } from 'uuid'; 22 | import builder from 'xmlbuilder'; 23 | import readInstalled from 'read-installed'; 24 | import * as ssri from 'ssri'; 25 | import * as fs from 'fs'; 26 | import { LicenseContent } from './Types/LicenseContent'; 27 | import { Component, GenericDescription } from './Types/Component'; 28 | import { ExternalReference } from './Types/ExternalReference'; 29 | import { Hash } from './Types/Hash'; 30 | import spdxLicensesNonDeprecated = require('spdx-license-ids'); 31 | import spdxLicensesDeprecated = require('spdx-license-ids/deprecated'); 32 | import { toPurl } from './Helpers/Helpers'; 33 | import { logMessage, DEBUG } from '../Application/Logger/Logger'; 34 | 35 | export class CycloneDXSbomCreator { 36 | readonly licenseFilenames: Array = [ 37 | 'LICENSE', 38 | 'License', 39 | 'license', 40 | 'LICENCE', 41 | 'Licence', 42 | 'licence', 43 | 'NOTICE', 44 | 'Notice', 45 | 'notice', 46 | ]; 47 | 48 | readonly licenseContentTypes = [ 49 | { licenseContentType: 'text/plain', fileExtension: '' }, 50 | { licenseContentType: 'text/txt', fileExtension: '.txt' }, 51 | { licenseContentType: 'text/markdown', fileExtension: '.md' }, 52 | { licenseContentType: 'text/xml', fileExtension: '.xml' }, 53 | ]; 54 | 55 | readonly SBOMSCHEMA: string = 'http://cyclonedx.org/schema/bom/1.1'; 56 | 57 | constructor(readonly path: string, readonly options?: Options) {} 58 | 59 | public async createBom(pkgInfo: any): Promise { 60 | const bom = builder.create('bom', { encoding: 'utf-8', separateArrayItems: true }).att('xmlns', this.SBOMSCHEMA); 61 | 62 | if (this.options && this.options.includeBomSerialNumber) { 63 | bom.att('serialNumber', 'urn:uuid:' + uuidv4()); 64 | } 65 | 66 | bom.att('version', 1); 67 | 68 | const componentsNode = bom.ele('components'); 69 | const components = this.listComponents(pkgInfo); 70 | 71 | if (components.length > 0) { 72 | componentsNode.ele(components); 73 | } 74 | 75 | const bomString = bom.end({ 76 | width: 0, 77 | allowEmpty: false, 78 | spaceBeforeSlash: '', 79 | }); 80 | 81 | return bomString; 82 | } 83 | 84 | public getPackageInfoFromReadInstalled(path: string = this.path): Promise { 85 | return new Promise((resolve, reject) => { 86 | readInstalled( 87 | path, 88 | { 89 | dev: this.options && this.options.devDependencies ? this.options.devDependencies : false, 90 | }, 91 | async (err: any, data: any) => { 92 | if (err) { 93 | reject(err); 94 | } 95 | 96 | resolve(data); 97 | }, 98 | ); 99 | }); 100 | } 101 | 102 | private listComponents(pkg: any): Array { 103 | const list: any = {}; 104 | const isRootPkg = true; 105 | this.addComponent(pkg, list, isRootPkg); 106 | return Object.keys(list).map((k) => ({ component: list[k] })); 107 | } 108 | 109 | private addComponent(pkg: any, list: any, isRootPkg = false): void { 110 | const spartan = this.options?.spartan ? this.options.spartan : false; 111 | //read-installed with default options marks devDependencies as extraneous 112 | //if a package is marked as extraneous, do not include it as a component 113 | if (pkg.extraneous) { 114 | return; 115 | } 116 | if (!isRootPkg) { 117 | const pkgIdentifier = this.parsePackageJsonName(pkg.name); 118 | const group: string = pkgIdentifier.scope == undefined ? '' : `@${pkgIdentifier.scope}`; 119 | const name: string = pkgIdentifier.fullName as string; 120 | const version: string = pkg.version as string; 121 | const purl: string = toPurl(name, version, group); 122 | const component: Component = { 123 | '@type': this.determinePackageType(pkg), 124 | '@bom-ref': purl, 125 | group: group, 126 | name: name, 127 | version: version, 128 | purl: purl, 129 | }; 130 | 131 | if (component.group === '') { 132 | delete component.group; 133 | } 134 | 135 | if (!spartan) { 136 | const description: GenericDescription = { '#cdata': pkg.description }; 137 | 138 | component.description = description; 139 | component.hashes = []; 140 | component.licenses = []; 141 | component.externalReferences = this.addExternalReferences(pkg); 142 | 143 | if (this.options && this.options.includeLicenseData) { 144 | component.licenses = this.getLicenses(pkg); 145 | } else { 146 | delete component.licenses; 147 | } 148 | 149 | if (component.externalReferences === undefined || component.externalReferences.length === 0) { 150 | delete component.externalReferences; 151 | } 152 | 153 | this.processHashes(pkg, component); 154 | } 155 | 156 | if (list[component.purl]) return; //remove cycles 157 | list[component.purl] = component; 158 | } 159 | if (pkg.dependencies) { 160 | Object.keys(pkg.dependencies) 161 | .map((x) => pkg.dependencies[x]) 162 | .filter((x) => typeof x !== 'string') //remove cycles 163 | .map((x) => this.addComponent(x, list)); 164 | } 165 | } 166 | 167 | /** 168 | * If the author has described the module as a 'framework', the take their 169 | * word for it, otherwise, identify the module as a 'library'. 170 | */ 171 | private determinePackageType(pkg: any): string { 172 | if (pkg.hasOwnProperty('keywords')) { 173 | for (const keyword of pkg.keywords) { 174 | if (keyword.toLowerCase() === 'framework') { 175 | return 'framework'; 176 | } 177 | } 178 | } 179 | return 'library'; 180 | } 181 | 182 | /** 183 | * Uses the SHA1 shasum (if Present) otherwise utilizes Subresource Integrity 184 | * of the package with support for multiple hashing algorithms. 185 | */ 186 | private processHashes(pkg: any, component: Component): void { 187 | component.hashes = new Array(); 188 | if (pkg._shasum) { 189 | component.hashes.push({ hash: { '@alg': 'SHA-1', '#text': pkg._shasum } }); 190 | } else if (pkg._integrity) { 191 | const integrity = ssri.parse(pkg._integrity); 192 | // Components may have multiple hashes with various lengths. Check each one 193 | // that is supported by the CycloneDX specification. 194 | if (integrity.hasOwnProperty('sha512')) { 195 | component.hashes.push(this.addComponentHash('SHA-512', integrity.sha512[0].digest)); 196 | } 197 | if (integrity.hasOwnProperty('sha384')) { 198 | component.hashes.push(this.addComponentHash('SHA-384', integrity.sha384[0].digest)); 199 | } 200 | if (integrity.hasOwnProperty('sha256')) { 201 | component.hashes.push(this.addComponentHash('SHA-256', integrity.sha256[0].digest)); 202 | } 203 | if (integrity.hasOwnProperty('sha1')) { 204 | component.hashes.push(this.addComponentHash('SHA-1', integrity.sha1[0].digest)); 205 | } 206 | } 207 | if (component.hashes.length === 0) { 208 | delete component.hashes; // If no hashes exist, delete the hashes node (it's optional) 209 | } 210 | } 211 | 212 | /** 213 | * Adds a hash to component. 214 | */ 215 | private addComponentHash(alg: string, digest: string): Hash { 216 | const hash = Buffer.from(digest, 'base64').toString('hex'); 217 | return { hash: { '@alg': alg, '#text': hash } }; 218 | } 219 | 220 | /** 221 | * Adds external references supported by the package format. 222 | */ 223 | private addExternalReferences(pkg: any): Array { 224 | const externalReferences: Array = []; 225 | if (pkg.homepage) { 226 | this.pushURLToExternalReferences('website', pkg.homepage, externalReferences); 227 | } 228 | if (pkg.bugs && pkg.bugs.url) { 229 | this.pushURLToExternalReferences('issue-tracker', pkg.bugs.url, externalReferences); 230 | } 231 | if (pkg.repository && pkg.repository.url) { 232 | this.pushURLToExternalReferences('vcs', pkg.repository.url, externalReferences); 233 | } 234 | return externalReferences; 235 | } 236 | 237 | private pushURLToExternalReferences( 238 | typeOfURL: string, 239 | url: string, 240 | externalReferences: Array, 241 | ): void { 242 | try { 243 | const uri = new URL(url); 244 | externalReferences.push({ reference: { '@type': typeOfURL, url: uri.toString() } }); 245 | } catch (e) { 246 | logMessage('Encountered an invalid URL', DEBUG, { title: e.message, stack: e.stack }); 247 | } 248 | } 249 | 250 | /** 251 | * Performs a lookup + validation of the license specified in the 252 | * package. If the license is a valid SPDX license ID, set the 'id' 253 | * of the license object, otherwise, set the 'name' of the license 254 | * object. 255 | */ 256 | private getLicenses(pkg: any): any { 257 | const spdxLicenses = [...spdxLicensesNonDeprecated, ...spdxLicensesDeprecated]; 258 | let license = pkg.license && (pkg.license.type || pkg.license); 259 | if (license) { 260 | if (!Array.isArray(license)) { 261 | license = [license]; 262 | } 263 | return license 264 | .map((l: string) => { 265 | const licenseContent: LicenseContent = {}; 266 | 267 | if ( 268 | spdxLicenses.some((v: string) => { 269 | return l === v; 270 | }) 271 | ) { 272 | licenseContent.id = l; 273 | } else { 274 | licenseContent.name = l; 275 | } 276 | if (this.options && this.options.includeLicenseText) { 277 | licenseContent.text = this.addLicenseText(pkg, l); 278 | } 279 | return licenseContent; 280 | }) 281 | .map((l: any) => ({ license: l })); 282 | } 283 | return undefined; 284 | } 285 | 286 | /** 287 | * Tries to find a file containing the license text based on commonly 288 | * used naming and content types. If a candidate file is found, add 289 | * the text to the license text object and stop. 290 | */ 291 | private addLicenseText(pkg: any, licenseName: string): GenericDescription | undefined { 292 | for (const licenseFilename of this.licenseFilenames) { 293 | for (const { licenseContentType, fileExtension } of this.licenseContentTypes) { 294 | let licenseFilepath = `${pkg.realPath}/${licenseFilename}${licenseName}${fileExtension}`; 295 | if (fs.existsSync(licenseFilepath)) { 296 | return this.readLicenseText(licenseFilepath, licenseContentType); 297 | } 298 | 299 | licenseFilepath = `${pkg.realPath}/${licenseFilename}${fileExtension}`; 300 | if (fs.existsSync(licenseFilepath)) { 301 | return this.readLicenseText(licenseFilepath, licenseContentType); 302 | } 303 | } 304 | } 305 | } 306 | 307 | /** 308 | * Read the file from the given path to the license text object and includes 309 | * content-type attribute, if not default. Returns the license text object. 310 | */ 311 | private readLicenseText(licenseFilepath: string, licenseContentType: string): GenericDescription | undefined { 312 | const licenseText = fs.readFileSync(licenseFilepath, 'utf8'); 313 | if (licenseText) { 314 | const licenseContentText: GenericDescription = { '#cdata': licenseText }; 315 | if (licenseContentType !== 'text/plain') { 316 | licenseContentText['@content-type'] = licenseContentType; 317 | } 318 | return licenseContentText; 319 | } 320 | return undefined; 321 | } 322 | 323 | private parsePackageJsonName(name: string): Result { 324 | const result: Result = { 325 | scope: undefined, 326 | fullName: '', 327 | projectName: '', 328 | moduleName: '', 329 | }; 330 | 331 | const regexp = new RegExp(/^(?:@([^/]+)\/)?(([^\.]+)(?:\.(.*))?)$/); 332 | 333 | const matches = name.match(regexp); 334 | if (matches) { 335 | result.scope = matches[1] || undefined; 336 | result.fullName = matches[2] || matches[0]; 337 | result.projectName = matches[3] === matches[2] ? undefined : matches[3]; 338 | result.moduleName = matches[4] || matches[2] || undefined; 339 | } 340 | return result; 341 | } 342 | } 343 | 344 | interface Result { 345 | scope?: string; 346 | fullName: string; 347 | projectName?: string; 348 | moduleName?: string; 349 | } 350 | -------------------------------------------------------------------------------- /src/CycloneDX/Helpers/Helpers.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export const toPurl = (name: string, version: string, group = ''): string => { 18 | if (group != '') { 19 | return `pkg:npm/${encodeURIComponent(group)}/${name}@${version}`; 20 | } 21 | return `pkg:npm/${name}@${version}`; 22 | }; 23 | -------------------------------------------------------------------------------- /src/CycloneDX/Options.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export interface Options { 18 | devDependencies?: boolean; 19 | includeBomSerialNumber?: boolean; 20 | includeLicenseData?: boolean; 21 | includeLicenseText?: boolean; 22 | spartan?: boolean; 23 | } 24 | -------------------------------------------------------------------------------- /src/CycloneDX/Types/Component.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ExternalReference } from './ExternalReference'; 18 | import { Hash } from './Hash'; 19 | 20 | export interface Component { 21 | '@type': string; 22 | '@bom-ref': string; 23 | group?: string; 24 | name: string; 25 | version: string; 26 | description?: Object; 27 | hashes?: Array; 28 | licenses?: Array; 29 | purl: string; 30 | externalReferences?: Array; 31 | } 32 | 33 | export interface GenericDescription { 34 | '#cdata': string; 35 | '@content-type'?: string; 36 | } 37 | -------------------------------------------------------------------------------- /src/CycloneDX/Types/ExternalReference.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export interface ExternalReference { 18 | reference: Reference, 19 | } 20 | 21 | export interface Reference { 22 | '@type': string, 23 | url: string 24 | } 25 | -------------------------------------------------------------------------------- /src/CycloneDX/Types/Hash.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export interface Hash { 18 | hash: HashDetails 19 | } 20 | 21 | export interface HashDetails { 22 | '@alg': string, 23 | '#text': string, 24 | } 25 | -------------------------------------------------------------------------------- /src/CycloneDX/Types/LicenseContent.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020-Present Erlend Oftedal, Steve Springett, Sonatype, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { GenericDescription } from "./Component"; 18 | 19 | export interface LicenseContent { 20 | id?: string, 21 | name?: string, 22 | text?: GenericDescription, 23 | } 24 | -------------------------------------------------------------------------------- /src/CycloneDX/typings/parse-packagejson-name/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'parse-packagejson-name'; 2 | -------------------------------------------------------------------------------- /src/CycloneDX/typings/read-installed/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'read-installed'; 2 | -------------------------------------------------------------------------------- /src/CycloneDX/typings/spdx-license-ids/index.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'spdx-license-ids'; 2 | declare module 'spdx-license-ids/deprecated'; 3 | -------------------------------------------------------------------------------- /src/Munchers/Bower.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Muncher } from './Muncher'; 18 | import { Coordinates } from '../Types/Coordinates'; 19 | import path from 'path'; 20 | import fs from 'fs'; 21 | 22 | export class Bower implements Muncher { 23 | constructor(readonly devDependencies: boolean = false) {} 24 | 25 | getSbomFromCommand(): Promise { 26 | throw new Error('Method not implemented.'); 27 | } 28 | 29 | public isValid(): boolean { 30 | const tempPath = path.join(process.cwd(), 'bower.json'); 31 | return fs.existsSync(tempPath); 32 | } 33 | 34 | public async getDepList(): Promise { 35 | return await this.getInstalledDeps(); 36 | } 37 | 38 | public async getInstalledDeps(): Promise { 39 | const depsArray: Array = []; 40 | const file = fs.readFileSync(path.join(process.cwd(), 'bower.json')); 41 | const json = JSON.parse(file.toString()); 42 | 43 | Object.keys(json.dependencies).map((x: string) => { 44 | const version: string = json.dependencies[x]; 45 | depsArray.push(new Coordinates(x, version.replace('~', ''), '')); 46 | }); 47 | 48 | if (this.devDependencies) { 49 | Object.keys(json.devDependencies).map((x: string) => { 50 | const version: string = json.devDependencies[x]; 51 | depsArray.push(new Coordinates(x, version.replace('~', ''), '')); 52 | }); 53 | } 54 | 55 | return depsArray; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Munchers/Muncher.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Coordinates } from '../Types/Coordinates'; 18 | 19 | export interface Muncher { 20 | getDepList(): Promise>; 21 | getSbomFromCommand(): Promise; 22 | getInstalledDeps(): Promise; 23 | isValid(): boolean; 24 | } 25 | -------------------------------------------------------------------------------- /src/Munchers/NpmList.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Muncher } from './Muncher'; 18 | import path from 'path'; 19 | import fs from 'fs'; 20 | import { Coordinates } from '../Types/Coordinates'; 21 | import { CycloneDXSbomCreator } from '../CycloneDX/CycloneDXSbomCreator'; 22 | 23 | export class NpmList implements Muncher { 24 | private depsArray: Array = []; 25 | 26 | constructor(readonly devDependencies: boolean = false) {} 27 | 28 | public async getDepList(): Promise { 29 | return await this.getInstalledDeps(); 30 | } 31 | 32 | public isValid(): boolean { 33 | const nodeModulesPath = path.join(process.cwd(), 'node_modules'); 34 | return fs.existsSync(nodeModulesPath); 35 | } 36 | 37 | public async getSbomFromCommand(): Promise { 38 | const sbomCreator = new CycloneDXSbomCreator(process.cwd(), { 39 | devDependencies: this.devDependencies, 40 | includeLicenseData: false, 41 | includeBomSerialNumber: true, 42 | spartan: true, 43 | }); 44 | 45 | const pkgInfo = await sbomCreator.getPackageInfoFromReadInstalled(); 46 | 47 | const result = await sbomCreator.createBom(pkgInfo); 48 | 49 | return result; 50 | } 51 | 52 | // turns object tree from read-installed into an array of coordinates represented node-managed deps 53 | public async getInstalledDeps(): Promise> { 54 | const sbomCreator = new CycloneDXSbomCreator(process.cwd(), { 55 | devDependencies: this.devDependencies, 56 | includeLicenseData: false, 57 | includeBomSerialNumber: true, 58 | }); 59 | 60 | const data = await sbomCreator.getPackageInfoFromReadInstalled(); 61 | 62 | this.recurseObjectTree(data, this.depsArray, true); 63 | 64 | return this.depsArray; 65 | } 66 | 67 | // recursive unit that traverses tree and terminates when object has no dependencies 68 | private recurseObjectTree(objectTree: any, list: Array, isRootPkg = false): any { 69 | if (objectTree.extraneous && !this.devDependencies) { 70 | return; 71 | } 72 | if (!isRootPkg) { 73 | if (this.maybePushNewCoordinate(objectTree, list)) { 74 | // NO OP 75 | } else { 76 | return; 77 | } 78 | } 79 | if (objectTree.dependencies) { 80 | Object.keys(objectTree.dependencies) 81 | .map((x) => objectTree.dependencies[x]) 82 | .filter((x) => typeof x !== 'string') 83 | .map((dep) => { 84 | if ( 85 | this.toPurlObjTree(dep) == '' || 86 | list.find((x) => { 87 | return x.toPurl() == this.toPurlObjTree(dep); 88 | }) 89 | ) { 90 | return; 91 | } 92 | this.recurseObjectTree(dep, list, false); 93 | }); 94 | } 95 | return; 96 | } 97 | 98 | private maybePushNewCoordinate(pkg: any, list: Array): boolean { 99 | if (pkg.name && pkg.name.includes('/')) { 100 | const name = pkg.name.split('/'); 101 | if ( 102 | list.find((x) => { 103 | return x.name == name[1] && x.version == pkg.version && x.group == name[0]; 104 | }) 105 | ) { 106 | return false; 107 | } 108 | list.push(new Coordinates(name[1], pkg.version, name[0])); 109 | return true; 110 | } else if (pkg.name) { 111 | if ( 112 | list.find((x) => { 113 | return x.name == pkg.name && x.version == pkg.version && x.group == ''; 114 | }) 115 | ) { 116 | return false; 117 | } 118 | list.push(new Coordinates(pkg.name, pkg.version, '')); 119 | return true; 120 | } 121 | return false; 122 | } 123 | 124 | private toPurlObjTree(objectTree: any): string { 125 | if (objectTree.name && objectTree.name.includes('/')) { 126 | const name = objectTree.name.split('/'); 127 | return this.toPurl(name[1], objectTree.version, name[0]); 128 | } else if (objectTree.name) { 129 | return this.toPurl(objectTree.name, objectTree.version); 130 | } else { 131 | return ''; 132 | } 133 | } 134 | 135 | private toPurl(name: string, version: string, group = ''): string { 136 | if (group != '') { 137 | return `${group}/${name}/${version}`; 138 | } 139 | return `${name}/${version}`; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/Munchers/NpmShrinkwrap.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { Muncher } from './Muncher'; 18 | import { Coordinates } from '../Types/Coordinates'; 19 | 20 | export class NpmShrinkwrap implements Muncher { 21 | getInstalledDeps(): Promise { 22 | throw new Error('Method not implemented.'); 23 | } 24 | getSbomFromCommand(): Promise { 25 | throw new Error('Method not implemented.'); 26 | } 27 | public getDepList(): Promise> { 28 | throw new Error('Method not implemented.'); 29 | } 30 | 31 | public isValid(): boolean { 32 | throw new Error('Method not implemented.'); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Services/IqRequestService.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect, { applicationInternalIdResponse } from '../Tests/TestHelper'; 18 | import { Coordinates } from '../Types/Coordinates'; 19 | import nock from 'nock'; 20 | import { IqRequestService } from './IqRequestService'; 21 | 22 | describe('IQRequestService', () => { 23 | it("should have it's third party API request rejected when the IQ Server is down", async () => { 24 | const internalId = '123456'; 25 | const stage = 'build'; 26 | nock('http://testlocation:8070') 27 | .post(`/api/v2/scan/applications/${internalId}/sources/auditjs?stageId=${stage}`) 28 | .replyWithError('you messed up!') 29 | .get(`/api/v2/applications?publicId=testapp`) 30 | .reply(404, applicationInternalIdResponse.body); 31 | 32 | const requestService = new IqRequestService( 33 | 'admin', 34 | 'admin123', 35 | 'http://testlocation:8070', 36 | 'testapp', 37 | stage, 38 | 300, 39 | false, 40 | ); 41 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 42 | 43 | return expect(requestService.submitToThirdPartyAPI(coords)).to.eventually.be.rejected; 44 | }); 45 | 46 | it('should respond with an error if the response for an ID is bad', async () => { 47 | const stage = 'build'; 48 | 49 | nock('http://testlocation:8070') 50 | .get(`/api/v2/applications?publicId=testapp`) 51 | .reply(applicationInternalIdResponse.statusCode, { thereisnoid: 'none' }); 52 | 53 | const requestService = new IqRequestService( 54 | 'admin', 55 | 'admin123', 56 | 'http://testlocation:8070', 57 | 'testapp', 58 | stage, 59 | 300, 60 | false, 61 | ); 62 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 63 | 64 | return expect(requestService.submitToThirdPartyAPI(coords)).to.eventually.be.rejectedWith( 65 | 'No valid ID on response from Nexus IQ, potentially check the public application ID you are using', 66 | ); 67 | }); 68 | 69 | it("should have it's third party API request accepted when the IQ Server is up", async () => { 70 | const internalId = '4bb67dcfc86344e3a483832f8c496419'; 71 | const stage = 'build'; 72 | const response = { 73 | statusCode: 202, 74 | body: { 75 | statusUrl: 'api/v2/scan/applications/a20bc16e83944595a94c2e36c1cd228e/status/9cee2b6366fc4d328edc318eae46b2cb', 76 | }, 77 | }; 78 | 79 | nock('http://testlocation:8070') 80 | .post(`/api/v2/scan/applications/${internalId}/sources/auditjs?stageId=${stage}`) 81 | .reply(response.statusCode, response.body) 82 | .get(`/api/v2/applications?publicId=testapp`) 83 | .reply(applicationInternalIdResponse.statusCode, applicationInternalIdResponse.body); 84 | 85 | const requestService = new IqRequestService( 86 | 'admin', 87 | 'admin123', 88 | 'http://testlocation:8070', 89 | 'testapp', 90 | stage, 91 | 300, 92 | false, 93 | ); 94 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 95 | 96 | return expect(requestService.submitToThirdPartyAPI(coords)).to.eventually.equal( 97 | 'api/v2/scan/applications/a20bc16e83944595a94c2e36c1cd228e/status/9cee2b6366fc4d328edc318eae46b2cb', 98 | ); 99 | }); 100 | 101 | it("should have it's third party API request rejected when IQ Server is up but API gives bad response", async () => { 102 | const internalId = '4bb67dcfc86344e3a483832f8c496419'; 103 | const stage = 'build'; 104 | const response = { 105 | statusCode: 202, 106 | body: { 107 | statusUrl: 'api/v2/scan/applications/a20bc16e83944595a94c2e36c1cd228e/status/9cee2b6366fc4d328edc318eae46b2cb', 108 | }, 109 | }; 110 | 111 | nock('http://testlocation:8070') 112 | .post(`/api/v2/scan/applications/${internalId}/sources/auditjs?stageId=${stage}`) 113 | .reply(404, response.body) 114 | .get(`/api/v2/applications?publicId=testapp`) 115 | .reply(applicationInternalIdResponse.statusCode, applicationInternalIdResponse.body); 116 | 117 | const requestService = new IqRequestService( 118 | 'admin', 119 | 'admin123', 120 | 'http://testlocation:8070', 121 | 'testapp', 122 | stage, 123 | 300, 124 | false, 125 | ); 126 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 127 | 128 | return expect(requestService.submitToThirdPartyAPI(coords)).to.eventually.be.rejectedWith( 129 | 'Unable to submit to Third Party API', 130 | ); 131 | }); 132 | 133 | it('should have return a proper result when polling IQ Server and the request is eventually valid', async () => { 134 | const response = { 135 | statusCode: 200, 136 | body: { 137 | policyAction: 'None', 138 | reportHtmlUrl: 'http://localhost:8070/ui/links/application/test-app/report/95c4c14e', 139 | isError: false, 140 | }, 141 | }; 142 | 143 | const stage = 'build'; 144 | nock('http://testlocation:8070') 145 | .get(`/api/v2/scan/applications/a20bc16e83944595a94c2e36c1cd228e/status/9cee2b6366fc4d328edc318eae46b2cb`) 146 | .reply(response.statusCode, response.body); 147 | 148 | const requestService = new IqRequestService( 149 | 'admin', 150 | 'admin123', 151 | 'http://testlocation:8070', 152 | 'testapp', 153 | stage, 154 | 300, 155 | false, 156 | ); 157 | 158 | requestService.asyncPollForResults( 159 | 'api/v2/scan/applications/a20bc16e83944595a94c2e36c1cd228e/status/9cee2b6366fc4d328edc318eae46b2cb', 160 | () => { 161 | return false; 162 | }, 163 | (x) => { 164 | return expect(x.reportHtmlUrl).to.equal('http://localhost:8070/ui/links/application/test-app/report/95c4c14e'); 165 | }, 166 | ); 167 | }); 168 | }); 169 | -------------------------------------------------------------------------------- /src/Services/IqRequestService.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import fetch from 'node-fetch'; 18 | import { RequestHelpers } from './RequestHelpers'; 19 | import { logMessage, DEBUG } from '../Application/Logger/Logger'; 20 | import { URL } from 'url'; 21 | 22 | const APPLICATION_INTERNAL_ID_ENDPOINT = '/api/v2/applications?publicId='; 23 | 24 | export class IqRequestService { 25 | private internalId = ''; 26 | private isInitialized = false; 27 | 28 | constructor( 29 | readonly user: string, 30 | readonly password: string, 31 | readonly host: string, 32 | readonly application: string, 33 | readonly stage: string, 34 | readonly timeout: number, 35 | readonly insecure: boolean, 36 | ) {} 37 | 38 | private async init(): Promise { 39 | try { 40 | this.internalId = await this.getApplicationInternalId(); 41 | this.isInitialized = true; 42 | } catch (e) { 43 | throw new Error(e); 44 | } 45 | } 46 | 47 | private timeoutAttempts = 0; 48 | 49 | private async getApplicationInternalId(): Promise { 50 | const response = await fetch(`${this.host}${APPLICATION_INTERNAL_ID_ENDPOINT}${this.application}`, { 51 | method: 'get', 52 | headers: [this.getBasicAuth(), RequestHelpers.getUserAgent()], 53 | agent: RequestHelpers.getAgent(this.insecure), 54 | }); 55 | if (response.ok) { 56 | const res = await response.json(); 57 | try { 58 | return res.applications[0].id; 59 | } catch (e) { 60 | throw new Error( 61 | `No valid ID on response from Nexus IQ, potentially check the public application ID you are using`, 62 | ); 63 | } 64 | } else { 65 | throw new Error( 66 | 'Unable to connect to IQ Server with http status ' + 67 | response.status + 68 | '. Check your credentials and network connectivity by hitting Nexus IQ at ' + 69 | this.host + 70 | ' in your browser.', 71 | ); 72 | } 73 | } 74 | 75 | public async submitToThirdPartyAPI(data: any): Promise { 76 | if (!this.isInitialized) { 77 | await this.init(); 78 | } 79 | logMessage('Internal ID', DEBUG, { internalId: this.internalId }); 80 | 81 | const response = await fetch( 82 | `${this.host}/api/v2/scan/applications/${this.internalId}/sources/auditjs?stageId=${this.stage}`, 83 | { 84 | method: 'post', 85 | headers: [this.getBasicAuth(), RequestHelpers.getUserAgent(), ['Content-Type', 'application/xml']], 86 | body: data, 87 | agent: RequestHelpers.getAgent(this.insecure), 88 | }, 89 | ); 90 | if (response.ok) { 91 | const json = await response.json(); 92 | return json.statusUrl as string; 93 | } else { 94 | const body = await response.text(); 95 | logMessage('Response from third party API', DEBUG, { response: body }); 96 | throw new Error(`Unable to submit to Third Party API`); 97 | } 98 | } 99 | 100 | public async asyncPollForResults( 101 | url: string, 102 | errorHandler: (error: any) => any, 103 | pollingFinished: (body: any) => any, 104 | ): Promise { 105 | logMessage(url, DEBUG); 106 | let mergeUrl: URL; 107 | try { 108 | mergeUrl = this.getURLOrMerge(url); 109 | 110 | // https://www.youtube.com/watch?v=Pubd-spHN-0 111 | const response = await fetch(mergeUrl.href, { 112 | method: 'get', 113 | headers: [this.getBasicAuth(), RequestHelpers.getUserAgent()], 114 | agent: RequestHelpers.getAgent(this.insecure), 115 | }); 116 | 117 | const body = response.ok; 118 | // TODO: right now I think we cover 500s and 400s the same and we'd continue polling as a result. We should likely switch 119 | // to checking explicitly for a 404 and if we get a 500/401 or other throw an error 120 | if (!body) { 121 | this.timeoutAttempts += 1; 122 | if (this.timeoutAttempts > this.timeout) { 123 | errorHandler({ 124 | message: 125 | 'Polling attempts exceeded, please either provide a higher limit via the command line using the timeout flag, or re-examine your project and logs to see if another error happened', 126 | }); 127 | } 128 | setTimeout(() => this.asyncPollForResults(url, errorHandler, pollingFinished), 1000); 129 | } else { 130 | const json = await response.json(); 131 | pollingFinished(json); 132 | } 133 | } catch (e) { 134 | errorHandler({ title: e.message }); 135 | } 136 | } 137 | 138 | private getURLOrMerge(url: string): URL { 139 | try { 140 | return new URL(url); 141 | } catch (e) { 142 | logMessage(e.title, DEBUG, { message: e.message }); 143 | if (this.host.endsWith('/')) { 144 | return new URL(this.host.concat(url)); 145 | } 146 | return new URL(this.host.concat('/' + url)); 147 | } 148 | } 149 | 150 | private getBasicAuth(): string[] { 151 | return ['Authorization', 'Basic ' + Buffer.from(this.user + ':' + this.password).toString('base64')]; 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/Services/OssIndexRequestService.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { OssIndexRequestService } from './OssIndexRequestService'; 18 | import expect from '../Tests/TestHelper'; 19 | import { Coordinates } from '../Types/Coordinates'; 20 | import nock from 'nock'; 21 | import rimraf from 'rimraf'; 22 | 23 | // This will only work on Linux/OS X, find a better Windows friendly path 24 | const CACHE_LOCATION = '/tmp/.ossindex'; 25 | 26 | const OSS_INDEX_BASE_URL = 'http://ossindex.sonatype.org/'; 27 | 28 | describe('OssIndexRequestService', () => { 29 | it('should have its request rejected when the OSS Index server is down', async () => { 30 | rimraf.sync(CACHE_LOCATION); 31 | nock(OSS_INDEX_BASE_URL) 32 | .post('/api/v3/component-report') 33 | .replyWithError('you messed up!'); 34 | const requestService = new OssIndexRequestService(undefined, undefined, CACHE_LOCATION, OSS_INDEX_BASE_URL); 35 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 36 | return expect(requestService.callOSSIndexOrGetFromCache(coords)).to.eventually.be.rejected; 37 | }); 38 | 39 | it('should return a valid response when given a valid component request', async () => { 40 | rimraf.sync(CACHE_LOCATION); 41 | const expectedOutput = [ 42 | { 43 | coordinates: 'pkg:npm/%40types/commander@2.12.2', 44 | reference: 'https://ossindex.sonatype.org/blahblahblah', 45 | vulnerabilities: [], 46 | }, 47 | ]; 48 | nock(OSS_INDEX_BASE_URL) 49 | .post('/api/v3/component-report') 50 | .reply(200, expectedOutput); 51 | const requestService = new OssIndexRequestService(undefined, undefined, CACHE_LOCATION, OSS_INDEX_BASE_URL); 52 | const coords = [new Coordinates('commander', '2.12.2', '@types')]; 53 | return expect(requestService.callOSSIndexOrGetFromCache(coords)).to.eventually.deep.equal(expectedOutput); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /src/Services/OssIndexRequestService.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { OssIndexCoordinates } from '../Types/OssIndexCoordinates'; 18 | import { Coordinates } from '../Types/Coordinates'; 19 | import fetch from 'node-fetch'; 20 | import { Response } from 'node-fetch'; 21 | import NodePersist from 'node-persist'; 22 | import path from 'path'; 23 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 24 | import { homedir } from 'os'; 25 | import { RequestHelpers } from './RequestHelpers'; 26 | 27 | const OSS_INDEX_BASE_URL = 'https://ossindex.sonatype.org/'; 28 | 29 | const COMPONENT_REPORT_ENDPOINT = 'api/v3/component-report'; 30 | 31 | const MAX_COORDINATES = 128; 32 | 33 | const PATH = path.join(homedir(), '.ossindex', 'auditjs'); 34 | 35 | const TWELVE_HOURS = 12 * 60 * 60 * 1000; 36 | 37 | export class OssIndexRequestService { 38 | constructor( 39 | readonly user?: string, 40 | readonly password?: string, 41 | readonly cacheLocation: string = PATH, 42 | private baseURL: string = OSS_INDEX_BASE_URL, 43 | ) {} 44 | 45 | private checkStatus(res: Response): Response { 46 | if (res.ok) { 47 | return res; 48 | } 49 | throw new Error(`${res.statusText}`); 50 | } 51 | 52 | private getHeaders(): string[][] { 53 | if (this.user && this.password) { 54 | return [['Content-Type', 'application/json'], this.getBasicAuth(), RequestHelpers.getUserAgent()]; 55 | } 56 | return [['Content-Type', 'application/json'], RequestHelpers.getUserAgent()]; 57 | } 58 | 59 | private getResultsFromOSSIndex(data: OssIndexCoordinates): Promise { 60 | const response = fetch(`${this.baseURL}${COMPONENT_REPORT_ENDPOINT}`, { 61 | method: 'post', 62 | body: JSON.stringify(data), 63 | headers: this.getHeaders(), 64 | agent: RequestHelpers.getHttpAgent(), 65 | }) 66 | .then(this.checkStatus) 67 | .then((res) => res.json()) 68 | .catch((err) => { 69 | throw new Error(`There was an error making the request: ${err}`); 70 | }); 71 | return response; 72 | } 73 | 74 | private chunkData(data: Coordinates[]): Array> { 75 | const chunks = []; 76 | while (data.length > 0) { 77 | chunks.push(data.splice(0, MAX_COORDINATES)); 78 | } 79 | return chunks; 80 | } 81 | 82 | private combineResponseChunks(data: [][]): Array { 83 | return [].concat.apply([], data); 84 | } 85 | 86 | private combineCacheAndResponses( 87 | combinedChunks: Array, 88 | dataInCache: Array, 89 | ): Array { 90 | return combinedChunks.concat(dataInCache); 91 | } 92 | 93 | private async insertResponsesIntoCache(response: Array): Promise> { 94 | // console.debug(`Preparing to cache ${response.length} coordinate responses`); 95 | 96 | for (let i = 0; i < response.length; i++) { 97 | await NodePersist.setItem(response[i].coordinates, response[i]); 98 | } 99 | 100 | // console.debug(`Done caching`); 101 | return response; 102 | } 103 | 104 | private async checkIfResultsAreInCache(data: Coordinates[], format = 'npm'): Promise { 105 | const inCache = new Array(); 106 | const notInCache = new Array(); 107 | 108 | for (let i = 0; i < data.length; i++) { 109 | const coord = data[i]; 110 | const dataInCache = await NodePersist.getItem(coord.toPurl(format)); 111 | if (dataInCache) { 112 | inCache.push(dataInCache); 113 | } else { 114 | notInCache.push(coord); 115 | } 116 | } 117 | 118 | return new PurlContainer(inCache, notInCache); 119 | } 120 | 121 | /** 122 | * Posts to OSS Index {@link COMPONENT_REPORT_ENDPOINT}, returns Promise of json object of response 123 | * @param data - {@link Coordinates} Array 124 | * @returns a {@link Promise} of all Responses 125 | */ 126 | public async callOSSIndexOrGetFromCache(data: Coordinates[], format = 'npm'): Promise { 127 | await NodePersist.init({ dir: this.cacheLocation, ttl: TWELVE_HOURS }); 128 | const responses = new Array(); 129 | // console.debug(`Purls received, total purls before chunk: ${data.length}`); 130 | const results = await this.checkIfResultsAreInCache(data, format); 131 | const chunkedPurls = this.chunkData(results.notInCache); 132 | 133 | for (const chunk of chunkedPurls) { 134 | try { 135 | const res = this.getResultsFromOSSIndex(new OssIndexCoordinates(chunk.map((x) => x.toPurl(format)))); 136 | responses.push(res); 137 | } catch (e) { 138 | throw new Error(e); 139 | } 140 | } 141 | 142 | return Promise.all(responses) 143 | .then((resolvedResponses) => this.combineResponseChunks(resolvedResponses)) 144 | .then((combinedResponses) => this.insertResponsesIntoCache(combinedResponses)) 145 | .then((combinedResponses) => this.combineCacheAndResponses(combinedResponses, results.inCache)) 146 | .catch((err) => { 147 | throw err; 148 | }); 149 | } 150 | 151 | private getBasicAuth(): string[] { 152 | return ['Authorization', 'Basic ' + Buffer.from(this.user + ':' + this.password).toString('base64')]; 153 | } 154 | } 155 | 156 | class PurlContainer { 157 | constructor(readonly inCache: OssIndexServerResult[], readonly notInCache: Coordinates[]) {} 158 | } 159 | -------------------------------------------------------------------------------- /src/Services/RequestHelpers.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect from '../Tests/TestHelper'; 18 | import { RequestHelpers } from './RequestHelpers'; 19 | import os from 'os'; 20 | 21 | const pack = require('../../package.json'); 22 | 23 | describe('RequestHelpers', () => { 24 | it('should return a valid user agent from getUserAgent ', () => { 25 | const nodeVersion = process.versions; 26 | const environment = 'NodeJS'; 27 | const environmentVersion = nodeVersion.node; 28 | const system = `${os.type()} ${os.release()}`; 29 | const res = RequestHelpers.getUserAgent(); 30 | const expected = ['User-Agent', `AuditJS/${pack.version} (${environment} ${environmentVersion}; ${system})`]; 31 | 32 | expect(res).to.include.members(expected); 33 | }); 34 | 35 | it('getAgent() should return undefined when no env variable is set', () => { 36 | process.env.http_proxy = 'no-proxy'; 37 | 38 | const res = RequestHelpers.getAgent(); 39 | expect(res).to.be.undefined; 40 | }); 41 | 42 | it('getAgent() should return a proxy httpAgent when env variable is set', () => { 43 | process.env.http_proxy = 'http://test.local:8080'; 44 | const res = RequestHelpers.getAgent(); 45 | expect(res).not.to.be.undefined; 46 | if (res) { 47 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 48 | // @ts-ignore 49 | expect(res.proxy.host).to.equal('test.local'); 50 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 51 | // @ts-ignore 52 | expect(res.proxy.port).to.equal(8080); 53 | } 54 | }); 55 | 56 | it('getAgent() should return an insecure httpAgent', () => { 57 | const res = RequestHelpers.getAgent(true); 58 | expect(res).not.to.be.undefined; 59 | if (res) { 60 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 61 | // @ts-ignore 62 | expect(res.options.rejectUnauthorized).to.equal(false); 63 | } 64 | }); 65 | 66 | // TODO: This may indicate a problem. In the case of insecure, the proxy setting is ignored 67 | // see: https://github.com/sonatype-nexus-community/auditjs/pull/213#discussion_r545617666 68 | /* 69 | it('getAgent() should return an insecure proxy httpAgent when env variable is set', () => { 70 | // eslint-disable-next-line @typescript-eslint/camelcase 71 | process.env.http_proxy = 'http://test.local:8080'; 72 | const res = RequestHelpers.getAgent(true); 73 | expect(res).not.to.be.undefined; 74 | if (res) { 75 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 76 | // @ts-ignore 77 | expect(res.options.rejectUnauthorized).to.equal(false); 78 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 79 | // @ts-ignore 80 | expect(res.proxy.host).to.equal('test.local'); 81 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 82 | // @ts-ignore 83 | expect(res.proxy.port).to.equal(8080); 84 | } 85 | }); 86 | */ 87 | 88 | it('should return an httpAgent when env variable is set', () => { 89 | process.env.http_proxy = 'http://test.local:8080'; 90 | const res = RequestHelpers.getHttpAgent(); 91 | expect(res).not.to.be.undefined; 92 | if (res) { 93 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 94 | // @ts-ignore 95 | expect(res.proxy.host).to.equal('test.local'); 96 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 97 | // @ts-ignore 98 | expect(res.proxy.port).to.equal(8080); 99 | } 100 | }); 101 | 102 | it('should return undefined when no env variable is set', () => { 103 | process.env.http_proxy = 'no-proxy'; 104 | 105 | const res = RequestHelpers.getHttpAgent(); 106 | expect(res).to.be.undefined; 107 | }); 108 | }); 109 | -------------------------------------------------------------------------------- /src/Services/RequestHelpers.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import os from 'os'; 18 | import { Agent } from 'http'; 19 | import { Agent as HttpsAgent } from 'https'; 20 | import { HttpsProxyAgent } from 'https-proxy-agent'; 21 | const pack = require('../../package.json'); 22 | 23 | export class RequestHelpers { 24 | public static getUserAgent(): string[] { 25 | const nodeVersion = process.versions; 26 | const environment = 'NodeJS'; 27 | const environmentVersion = nodeVersion.node; 28 | const system = `${os.type()} ${os.release()}`; 29 | 30 | return ['User-Agent', `AuditJS/${pack.version} (${environment} ${environmentVersion}; ${system})`]; 31 | } 32 | 33 | public static getAgent(insecure = false): Agent | undefined { 34 | if (insecure) { 35 | return new HttpsAgent({ 36 | rejectUnauthorized: false, 37 | }); 38 | } 39 | 40 | return this.getHttpAgent(); 41 | } 42 | 43 | public static getHttpAgent(): Agent | undefined { 44 | const proxyUrl = process.env.http_proxy || process.env.https_proxy; 45 | if (proxyUrl !== undefined && proxyUrl !== 'no-proxy') { 46 | return new HttpsProxyAgent(proxyUrl); 47 | } 48 | return undefined; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Tests/TestHelper.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import chai from 'chai'; 18 | import chaiAsPromised from 'chai-as-promised'; 19 | import 'mocha'; 20 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 21 | 22 | chai.use(chaiAsPromised); 23 | const expect = chai.expect; 24 | 25 | export const ossIndexObject: OssIndexServerResult = new OssIndexServerResult({ 26 | coordinates: 'Test', 27 | reference: 'reference', 28 | vulnerabilities: [ 29 | { 30 | id: 'test_id', 31 | title: 'title', 32 | cvssScore: '9.8', 33 | reference: 'reference', 34 | description: '', 35 | cvssVector: '', 36 | cve: '9.8', 37 | }, 38 | { 39 | id: 'test_id2', 40 | title: 'title', 41 | cvssScore: '9.8', 42 | reference: 'reference', 43 | description: '', 44 | cvssVector: '', 45 | cve: '9.8', 46 | }, 47 | ], 48 | }); 49 | 50 | export const ossIndexObjectNoVulnerabilities: OssIndexServerResult = new OssIndexServerResult({ 51 | coordinates: 'Test', 52 | reference: 'reference', 53 | vulnerabilities: [], 54 | }); 55 | 56 | export const applicationInternalIdResponse = { 57 | statusCode: 200, 58 | body: { 59 | applications: [ 60 | { 61 | id: '4bb67dcfc86344e3a483832f8c496419', 62 | publicId: 'testapp', 63 | name: 'TestApp', 64 | organizationId: 'bb41817bd3e2403a8a52fe8bcd8fe25a', 65 | contactUserName: 'NewAppContact', 66 | applicationTags: [ 67 | { 68 | id: '9beee80c6fc148dfa51e8b0359ee4d4e', 69 | tagId: 'cfea8fa79df64283bd64e5b6b624ba48', 70 | applicationId: '4bb67dcfc86344e3a483832f8c496419', 71 | }, 72 | ], 73 | }, 74 | ], 75 | }, 76 | }; 77 | 78 | export const ossIndexServerResults = [ossIndexObjectNoVulnerabilities, ossIndexObject]; 79 | 80 | export default expect; 81 | -------------------------------------------------------------------------------- /src/Types/Coordinates.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class Coordinates { 18 | constructor(readonly name: string, readonly version: string, readonly group?: string) {} 19 | 20 | public toPurl(ecosystem = 'npm'): string { 21 | if (this.group) { 22 | // TODO: IQ does not need the @ sign replaced with %40, probably want to figure out someway to handle this correctly 23 | return `pkg:${ecosystem}/${this.group.replace('@', '%40')}/${this.name}@${this.version}`; 24 | } 25 | return `pkg:${ecosystem}/${this.name}@${this.version}`; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Types/IqServerResult.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class IqServerResult { 18 | readonly component: Component; 19 | readonly matchState: string; 20 | readonly catalogDate: string; 21 | readonly licenseData: LicenseData; 22 | readonly securityData: SecurityData; 23 | readonly policyData: PolicyData; 24 | 25 | constructor(result: any) { 26 | this.component = new Component(result.component); 27 | this.matchState = result.matchState; 28 | this.catalogDate = result.catalogDate; 29 | this.licenseData = new LicenseData(result.licenseData); 30 | this.securityData = new SecurityData(result.securityData); 31 | this.policyData = new PolicyData(result.policyData); 32 | } 33 | 34 | public toAuditLog(): string { 35 | return `${this.component.packageUrl} - ${this.component.hash}`; 36 | } 37 | } 38 | 39 | class Component { 40 | readonly packageUrl: string; 41 | readonly hash: string; 42 | // eslint-disable-next-line 43 | readonly componentIdentifier: {}; 44 | readonly proprietary: boolean; 45 | 46 | constructor(component: any) { 47 | this.packageUrl = component.packageUrl; 48 | this.hash = component.hash; 49 | this.componentIdentifier = new ComponentIdentifier(component.componentIdentifier); 50 | this.proprietary = component.proprietary; 51 | } 52 | } 53 | 54 | class ComponentIdentifier { 55 | readonly format: string; 56 | readonly coordinates: Record; 57 | 58 | constructor(componentIdentifier: any) { 59 | this.format = componentIdentifier.format; 60 | this.coordinates = componentIdentifier.coordinates; 61 | } 62 | } 63 | 64 | class LicenseData { 65 | // eslint-disable-next-line 66 | readonly declaredLicenses: {}; 67 | // eslint-disable-next-line 68 | readonly observedLicenses: {}; 69 | // eslint-disable-next-line 70 | readonly overriddenLicenses: {}; 71 | readonly status: string; 72 | 73 | constructor(licenseData: any) { 74 | this.declaredLicenses = licenseData.declaredLicenses; 75 | this.observedLicenses = licenseData.observedLicenses; 76 | this.overriddenLicenses = licenseData.overriddenLicenses; 77 | this.status = licenseData.status; 78 | } 79 | } 80 | 81 | class SecurityData { 82 | constructor(readonly securityData: any) {} 83 | } 84 | 85 | class PolicyData { 86 | constructor(readonly policyData: any) {} 87 | } 88 | -------------------------------------------------------------------------------- /src/Types/OssIndexCoordinates.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class OssIndexCoordinates { 18 | constructor(readonly coordinates: string[]) {} 19 | } 20 | -------------------------------------------------------------------------------- /src/Types/OssIndexServerResult.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class OssIndexServerResult { 18 | readonly coordinates: string; 19 | readonly description?: string; 20 | readonly reference: string; 21 | readonly vulnerabilities?: Array; 22 | 23 | constructor(result: any) { 24 | this.coordinates = result.coordinates; 25 | this.description = result.description; 26 | this.reference = result.reference; 27 | this.vulnerabilities = result.vulnerabilities.map((x: any) => { 28 | return new Vulnerability(x); 29 | }); 30 | } 31 | 32 | public toAuditLog(): string { 33 | return `${this.coordinates.replace('%40', '@')} - ${this.vulnerabilityMessage()}`; 34 | } 35 | 36 | private vulnerabilityMessage(): string { 37 | if (this.vulnerabilities && this.vulnerabilities?.length > 1) { 38 | return `${this.vulnerabilities.length} vulnerabilities found!`; 39 | } else if (this.vulnerabilities && this.vulnerabilities?.length === 1) { 40 | return `${this.vulnerabilities.length} vulnerability found!`; 41 | } else { 42 | return `No vulnerabilities found!`; 43 | } 44 | } 45 | } 46 | 47 | export class Vulnerability { 48 | readonly id: string; 49 | readonly title: string; 50 | readonly description: string; 51 | readonly cvssScore: string; 52 | readonly cvssVector: string; 53 | readonly cve: string; 54 | readonly reference: string; 55 | constructor(vulnerability: any) { 56 | this.id = vulnerability.id; 57 | this.title = vulnerability.title; 58 | this.description = vulnerability.description; 59 | this.cvssScore = vulnerability.cvssScore; 60 | this.cvssVector = vulnerability.cvssVector; 61 | this.cve = vulnerability.cve; 62 | this.reference = vulnerability.reference; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Types/ReportStatus.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class ReportStatus { 18 | policyAction?: string; 19 | reportHtmlUrl?: string; 20 | errorMessage?: string; 21 | isError = false; 22 | } 23 | -------------------------------------------------------------------------------- /src/Visual/VisualHelper.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export const visuallySeperateText = (error: boolean, text: any[]): void => { 18 | console.log(); 19 | console.group(); 20 | text.forEach((val) => { 21 | error ? console.error(val) : console.log(val); 22 | }); 23 | console.groupEnd(); 24 | console.log(); 25 | }; 26 | -------------------------------------------------------------------------------- /src/Whitelist/VulnerabilityExcluder.spec.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import expect, { ossIndexServerResults } from '../Tests/TestHelper'; 18 | import { filterVulnerabilities } from './VulnerabilityExcluder'; 19 | import mock from 'mock-fs'; 20 | 21 | const jsonWithOnlyOneMatch = `{ 22 | "ignore": [ 23 | { 24 | "id": "test_id" 25 | } 26 | ] 27 | }`; 28 | 29 | const json = `{ 30 | "ignore": [ 31 | { 32 | "id": "test_id" 33 | }, 34 | { 35 | "id": "test_id2" 36 | } 37 | ] 38 | }`; 39 | 40 | const jsonWithNonApplicableId = `{ 41 | "ignore": [ { 42 | "id": "qwepquepoqwe" 43 | } 44 | ] 45 | }`; 46 | 47 | const nonSensicalJson = `{ 48 | "ignore": [ { 49 | ] 50 | }`; 51 | 52 | describe('VulnerabilityExcluder', () => { 53 | it('should filter vulnerabilities given a valid auditjs.json', async () => { 54 | mock({ 55 | '/nonsensical': { 56 | 'auditjs.json': json, 57 | }, 58 | }); 59 | const results = await filterVulnerabilities(ossIndexServerResults, '/nonsensical/auditjs.json'); 60 | expect(results[1].vulnerabilities?.length).to.equal(0); 61 | mock.restore(); 62 | }); 63 | 64 | it('should filter some vulnerabilities given a valid auditjs.json', async () => { 65 | mock({ 66 | '/nonsensical': { 67 | 'auditjs.json': jsonWithOnlyOneMatch, 68 | }, 69 | }); 70 | const results = await filterVulnerabilities(ossIndexServerResults, '/nonsensical/auditjs.json'); 71 | expect(results[1].vulnerabilities?.length).to.equal(1); 72 | mock.restore(); 73 | }); 74 | 75 | it('should not filter vulnerabilities given a valid auditjs.json with an id that does not match', async () => { 76 | mock({ 77 | '/nonsensical': { 78 | 'auditjs.json': jsonWithNonApplicableId, 79 | }, 80 | }); 81 | const results = await filterVulnerabilities(ossIndexServerResults, '/nonsensical/auditjs.json'); 82 | expect(results[1].vulnerabilities?.length).to.equal(2); 83 | mock.restore(); 84 | }); 85 | 86 | it('should just return the original results and not barf all over itself if the auditjs.json file is malformed', async () => { 87 | mock({ 88 | '/nonsensical': { 89 | 'auditjs.json': nonSensicalJson, 90 | }, 91 | }); 92 | 93 | expect(filterVulnerabilities(ossIndexServerResults, '/nonsensical/auditjs.json')).to.eventually.be.rejected; 94 | mock.restore(); 95 | }); 96 | 97 | it('should return original results if no auditjs.json exists ', async () => { 98 | mock({ '/nonsensical': {} }); 99 | 100 | const results = await filterVulnerabilities(ossIndexServerResults, '/nonsensical/auditjs.json'); 101 | expect(results).to.deep.equal(ossIndexServerResults); 102 | mock.restore(); 103 | }); 104 | }); 105 | -------------------------------------------------------------------------------- /src/Whitelist/VulnerabilityExcluder.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-Present Sonatype Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { readFileSync } from 'fs'; 18 | import path from 'path'; 19 | 20 | import { OssIndexServerResult } from '../Types/OssIndexServerResult'; 21 | 22 | const whitelistFilePathPwd = path.join(process.cwd(), 'auditjs.json'); 23 | 24 | export const filterVulnerabilities = async ( 25 | results: Array, 26 | whitelistFilePath: string = whitelistFilePathPwd, 27 | ): Promise> => { 28 | let json: Buffer; 29 | try { 30 | json = readFileSync(whitelistFilePath, { flag: 'r+' }); 31 | } catch (e) { 32 | return results; 33 | } 34 | 35 | try { 36 | const whitelist = JSON.parse(json.toString()); 37 | 38 | const whiteListSet = new Set(whitelist.ignore.map((exclusion: any) => exclusion.id)); 39 | 40 | const newResults = results.map((result) => { 41 | if (result.vulnerabilities && result.vulnerabilities.length) { 42 | const vulns = result.vulnerabilities.filter((vuln) => !whiteListSet.has(vuln.id)); 43 | 44 | return new OssIndexServerResult({ 45 | ...result, 46 | vulnerabilities: vulns, 47 | }); 48 | } 49 | return result; 50 | }); 51 | return newResults; 52 | } catch (e) { 53 | throw new Error( 54 | `There was an issue excluding vulnerabilities likely based on your whitelist, please check ${whitelistFilePath}, to ensure it is valid JSON, and review stack trace for more information, stack trace: ${e.stack}`, 55 | ); 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | * Copyright 2019-Present Sonatype Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import yargs from 'yargs'; 19 | import {Argv} from 'yargs'; 20 | import {Application} from './Application/Application'; 21 | import {AppConfig} from './Config/AppConfig'; 22 | import {OssIndexServerConfig} from './Config/OssIndexServerConfig'; 23 | 24 | // TODO: Flesh out the remaining set of args that NEED to be moved over, look at them with a fine toothed comb and lots of skepticism 25 | const normalizeHostAddress = (address: string) => { 26 | if (address.endsWith('/')) { 27 | return address.slice(0, address.length - 1); 28 | } 29 | return address; 30 | }; 31 | 32 | let argv = yargs 33 | .help() 34 | .scriptName('auditjs') 35 | .command('iq [options]', 'Audit this application using Nexus IQ Server', (y: Argv) => { 36 | return y.options({ 37 | application: { 38 | alias: 'a', 39 | type: 'string', 40 | demandOption: true, 41 | description: 'Specify IQ application public ID', 42 | }, 43 | stage: { 44 | alias: 's', 45 | choices: ['develop', 'build', 'stage-release', 'release'] as const, 46 | demandOption: false, 47 | default: 'develop', 48 | description: 'Specify IQ app stage', 49 | }, 50 | server: { 51 | alias: 'h', 52 | type: 'string', 53 | description: 'Specify IQ server url/port', 54 | demandOption: false, 55 | }, 56 | timeout: { 57 | alias: 't', 58 | type: 'number', 59 | description: 'Specify an optional timeout in seconds for IQ Server Polling', 60 | default: 300, 61 | demandOption: false, 62 | }, 63 | user: { 64 | alias: 'u', 65 | type: 'string', 66 | description: 'Specify username for request', 67 | demandOption: false, 68 | }, 69 | password: { 70 | alias: 'p', 71 | type: 'string', 72 | description: 'Specify password for request', 73 | demandOption: false, 74 | }, 75 | artie: { 76 | alias: 'x', 77 | type: 'boolean', 78 | description: 'Artie', 79 | demandOption: false, 80 | }, 81 | allen: { 82 | alias: 'w', 83 | type: 'boolean', 84 | description: 'Allen', 85 | demandOption: false, 86 | }, 87 | dev: { 88 | alias: 'd', 89 | type: 'boolean', 90 | description: 'Include Development Dependencies', 91 | demandOption: false, 92 | }, 93 | insecure: { 94 | type: 'boolean', 95 | description: 'Allow insecure connections', 96 | demandOption: false, 97 | }, 98 | }); 99 | }) 100 | .command('config', 'Set config for OSS Index or Nexus IQ Server') 101 | .command('ossi [options]', 'Audit this application using Sonatype OSS Index', (y: Argv) => { 102 | return y.options({ 103 | user: { 104 | alias: 'u', 105 | type: 'string', 106 | description: 'Specify OSS Index username', 107 | demandOption: false, 108 | }, 109 | password: { 110 | alias: 'p', 111 | type: 'string', 112 | description: 'Specify OSS Index password or token', 113 | demandOption: false, 114 | }, 115 | cache: { 116 | alias: 'c', 117 | type: 'string', 118 | description: 'Specify path to use as a cache location', 119 | demandOption: false, 120 | }, 121 | quiet: { 122 | alias: 'q', 123 | type: 'boolean', 124 | description: 'Only print out vulnerable dependencies', 125 | demandOption: false, 126 | }, 127 | json: { 128 | alias: 'j', 129 | type: 'boolean', 130 | description: 'Set output to JSON', 131 | demandOption: false, 132 | }, 133 | xml: { 134 | alias: 'x', 135 | type: 'boolean', 136 | description: 'Set output to JUnit XML format', 137 | demandOption: false, 138 | }, 139 | whitelist: { 140 | alias: 'w', 141 | type: 'string', 142 | description: 'Set path to whitelist file', 143 | demandOption: false, 144 | }, 145 | clear: { 146 | description: 'Clears cache location if it has been set in config', 147 | type: 'boolean', 148 | demandOption: false, 149 | }, 150 | bower: { 151 | description: 'Force the application to explicitly scan for Bower', 152 | type: 'boolean', 153 | demandOption: false, 154 | }, 155 | }) 156 | .command('sbom', 'Output the purl only CycloneDx sbom to std_out'); 157 | }).argv; 158 | 159 | if (argv) { 160 | if (argv._[0] == 'config') { 161 | let config = new AppConfig(); 162 | 163 | config 164 | .getConfigFromCommandLine() 165 | .then((val) => { 166 | val ? process.exit(0) : process.exit(1); 167 | }) 168 | .catch((e) => { 169 | throw new Error(e); 170 | }); 171 | } else if (argv.clear) { 172 | let config = new OssIndexServerConfig(); 173 | if (config.exists()) { 174 | config.getConfigFromFile(); 175 | 176 | console.log('Cache location:', config.getCacheLocation()); 177 | 178 | config.clearCache().then((success) => { 179 | if (success) { 180 | console.log('Cache cleared'); 181 | process.exit(0); 182 | } else { 183 | console.log( 184 | 'There was an error clearing the cache, the cache location must only contain AuditJS cache files.', 185 | ); 186 | process.exit(1); 187 | } 188 | }); 189 | } else { 190 | console.error( 191 | 'Attempted to clear cache but no config file Present, run `auditjs config` to set a cache location.', 192 | ); 193 | } 194 | } else if (argv._[0] == 'iq' || argv._[0] == 'ossi' || argv._[0] == 'sbom') { 195 | // silence all output if quiet or if sending file to std_out 196 | let silence = argv.json || argv.quiet || argv.xml || argv._[0] == 'sbom' ? true : false; 197 | let artie = argv.artie ? true : false; 198 | let allen = argv.allen ? true : false; 199 | let bower = argv.bower ? true : false; 200 | 201 | if (argv.server) { 202 | argv.server = normalizeHostAddress(argv.server as string); 203 | } 204 | 205 | let app: Application; 206 | try { 207 | if (argv.dev) { 208 | app = new Application(argv.dev as boolean, silence, artie, allen, bower); 209 | } else { 210 | app = new Application(false, silence, artie, allen, bower); 211 | } 212 | app.startApplication(argv); 213 | } catch (error) { 214 | console.error(error); 215 | process.exit(1); 216 | } 217 | } else { 218 | yargs.showHelp(); 219 | process.exit(0); 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /tsconfig.development.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "watch": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module":"commonjs", 4 | "target": "es6", 5 | "lib": ["es6", "dom"], 6 | "types": ["node"], 7 | "strict": true, 8 | "esModuleInterop": true, 9 | "outDir": "./bin", 10 | "sourceMap": true, 11 | "declaration": true, 12 | "resolveJsonModule": true, 13 | "useUnknownInCatchVariables": false, 14 | }, 15 | "include": [ 16 | "src/**/*.d.ts", 17 | "src/**/*.ts" 18 | ], 19 | "exclude": [ 20 | "node_modules" 21 | ] 22 | } 23 | --------------------------------------------------------------------------------