All files / src cli.ts

68.72% Statements 156/227
75% Branches 3/4
28.57% Functions 2/7
68.72% Lines 156/227

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 2281x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                 1x             1x 1x 1x 1x 1x 1x 1x 1x                                                                       1x                           1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x  
import {
  program,
  Option,
  InvalidArgumentError,
} from "@commander-js/extra-typings";
import path from "node:path";
import os from "node:os";
import fs from "node:fs";
import { Maybe } from "purify-ts";
import { ensureError } from "./util/misc.js";
import { description, name, version } from "./info.js";
import { createLogger } from "./util/log.js";
import { parseUrl } from "./util/net.js";
import { resolveFile } from "./util/fs.js";
 
const log = createLogger(name);
 
const command = program
  .configureOutput({
    writeErr(str: string) {
      log.error(str);
    },
  })
  .allowUnknownOption()
  .name(name)
  .description(description)
  .argument(
    "[args...]",
    "additional arguments that will be passed to the dependency-check-cli",
  )
  .optionsGroup("Installation options:")
  .option(
    "--bin <binary>",
    "the directory the dependency-check-cli will be installed into",
    "dependency-check-bin",
  )
  .option(
    "--force-install",
    "install the dependency-check-cli even if the version is already present (will be overwritten)",
  )
  .option(
    "--keep-old-versions",
    "do not remove old versions of the dependency-check-cli",
  )
  .option(
    "--odc-version <version>",
    "the version of the dependency-check-cli to install in the format: v1.2.3",
  )
  .addOption(
    new Option(
      "--github-token <token>",
      "GitHub token to authenticate against API",
    ).env("GITHUB_TOKEN"),
  )
  .optionsGroup("Execution options:")
  .addOption(
    new Option(
      "--owasp-bin <binary>",
      `the path to a preinstalled dependency-check-cli binary (.sh or .bat file)`,
    )
      .env("OWASP_BIN")
      .argParser(parseFile),
  )
  .option(
    "--hide-owasp-output",
    "do not display the output of the dependency-check-cli binary",
  )
  .option("--ignore-errors", "always exit with code 0")
  .addOption(
    new Option("--java-bin <binary>", "the path to the Java binary")
      .env("JAVACMD")
      .argParser(parseFile),
  )
  .optionsGroup("Network options:")
  .option(
    "-p, --proxy <url>",
    "the URL of a proxy server in the format: http(s)://[user]:[password]@<server>:[port]",
    parseProxyUrl,
  )
  .optionsGroup("OWASP dependency-check-cli options:")
  .option(
    "-o, --out <directory>",
    "the directory the generated reports will be written into",
    "dependency-check-reports",
  )
  .option(
    "-d, --data <directory>",
    "the location of the data directory used to store persistent data",
    path.join(os.tmpdir(), "dependency-check-data"),
  )
  .option(
    "-s, --scan <file...>",
    "the lock files of package managers to scan",
    [],
  )
  .option("-f, --format <format...>", "the formats of the report to generate", [
    "HTML",
    "JSON",
  ])
  .addOption(
    new Option(
      "--nvdApiKey <key>",
      "NVD API key to authenticate against API",
    ).env("NVD_API_KEY"),
  )
  .addOption(
    new Option("--project <name>", "the name of the project to be scanned").env(
      "PROJECT_NAME",
    ),
  )
  .optionsGroup("General information:")
  .version(version, undefined, `print the version of ${name}`)
  .helpOption("-h, --help", "display this help information")
  .addHelpText(
    "afterAll",
    `
You can also use any arguments supported by the dependency-check-cli, see: https://jeremylong.github.io/DependencyCheck/dependency-check-cli/arguments.html
 
Some defaults are provided:
- project    Default: "name" from package.json in working directory
- data       Default: dependency-check-data directory in system temp folder
- format     Default: HTML and JSON
- scan       Default: package managers' lock files in working directory (package-lock.json, yarn.lock, pnpm-lock.yaml) 
 
The following environment variables are supported:
- OWASP_BIN: path to a local installation of the dependency-check-cli
- NVD_API_KET: personal NVD API key to authenticate against API
- GITHUB_TOKEN: personal GitHub token to authenticate against API
- PROJECT_NAME: the name of the project being scanned
- JAVACMD: path to a Java binary`,
  );
 
export function parseCli() {
  command.parse();
  return {
    hideOwaspOutput: !!command.opts().hideOwaspOutput,
    owaspBinary: Maybe.fromNullable(command.opts().owaspBin),
    proxyUrl: Maybe.fromNullable(command.opts().proxy),
    githubToken: Maybe.fromNullable(command.opts().githubToken),
    outDir: command.opts().out,
    forceInstall: !!command.opts().forceInstall,
    odcVersion: Maybe.fromNullable(command.opts().odcVersion),
    binDir: path.resolve(command.opts().bin),
    cmdArguments: buildCmdArguments(),
    ignoreErrors: !!command.opts().ignoreErrors,
    keepOldVersions: !!command.opts().keepOldVersions,
    javaBinary: Maybe.fromNullable(command.opts().javaBin),
  };
}
 
function addScanArgument(args: string[], lockFile: string) {
  resolveFile(lockFile).ifJust(value => {
    log.info(`Found "${value}" and adding it to --scan argument.`);
    args.push("--scan", value);
  });
}
 
const LOCK_FILES = [
  "package-lock.json",
  "npm-shrinkwrap.json",
  "yarn.lock",
  "pnpm-lock.yaml",
];
 
function buildCmdArguments() {
  const args = [
    "--out",
    command.opts().out,
    "--data",
    command.opts().data,
    ...command.args,
  ];

  Maybe.fromNullable(command.opts().nvdApiKey).ifJust(key => {
    args.push("--nvdApiKey", key);
  });

  const scan = command.opts().scan;
  if (scan.length > 0) {
    scan.forEach(scan => {
      args.push("--scan", scan);
    });
  } else {
    LOCK_FILES.forEach(file => {
      addScanArgument(args, file);
    });
  }

  args.push(
    "--project",
    command.opts().project ?? getProjectNameFromPackageJson(),
  );

  command.opts().format.forEach(format => {
    args.push("--format", format);
  });

  return args;
}
 
function getProjectNameFromPackageJson() {
  let projectName = "Unknown Project";
  try {
    const packageJson = fs.readFileSync("package.json").toString();
    const parsedJson = JSON.parse(packageJson) as { name: string };
    projectName = parsedJson.name;
    log.info(`Found project name "${projectName}" in package.json`);
  } catch (e) {
    const error = ensureError(e);
    log.warn(error.message);
  }
  return projectName;
}
 
export function parseProxyUrl(value: string) {
  return parseUrl(value)
    .filter(url => url.protocol === "http:" || url.protocol === "https:")
    .toEither(new InvalidArgumentError("The proxy URL is invalid."))
    .unsafeCoerce();
}
 
export function parseFile(path: string) {
  const filePath = resolveFile(path);
  return filePath
    .toEither(new InvalidArgumentError(`The file "${path}" does not exist.`))
    .unsafeCoerce();
}