All files / src installer.ts

38.41% Statements 63/164
100% Branches 6/6
37.5% Functions 3/8
38.41% Lines 63/164

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 1651x 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 2x 1x                             1x 1x 3x 3x 1x                                 1x 1x 4x 4x 4x 4x 4x 4x 2x 4x 4x 4x 1x                                                                   1x 1x                                                              
import { ensureError } from "./util/misc.js";
import { EitherAsync, Maybe } from "purify-ts";
import path from "node:path";
import os from "node:os";
import { createLogger } from "./util/log.js";
import { name } from "./info.js";
import * as yup from "yup";
import { buildRequestInit, downloadFile, fetchJson } from "./util/net.js";
import { cleanDir, resolveFile, unzipFileIntoDirectory } from "./util/fs.js";
 
const log = createLogger(`${name} Installation`);
 
const NAME_RE = /^dependency-check-\d+\.\d+\.\d+-release\.zip$/;
const LATEST_RELEASE_URL =
  "https://api.github.com/repos/dependency-check/DependencyCheck/releases/latest";
const TAG_RELEASE_URL =
  "https://api.github.com/repos/dependency-check/DependencyCheck/releases/tags/";
const IS_WIN = os.platform() === "win32";
 
function findOwaspExecutable(installDir: string) {
  return resolveFile(
    installDir,
    "dependency-check",
    "bin",
    `dependency-check.${IS_WIN ? "bat" : "sh"}`,
  );
}
 
const githubReleaseSchema = yup.object({
  tag_name: yup.string().required(),
  assets: yup
    .array()
    .of(
      yup.object({
        name: yup.string().required(),
        browser_download_url: yup.string().url().required(),
      }),
    )
    .required(),
});
 
type GithubRelease = yup.InferType<typeof githubReleaseSchema>;
 
export function castGithubRelease(
  data: unknown,
): EitherAsync<Error, GithubRelease> {
  return EitherAsync(() =>
    githubReleaseSchema.validate(data, { strict: true }),
  ).mapLeft(ensureError);
}
 
function findReleaseInfo(
  odcVersion: Maybe<string>,
  proxyUrl: Maybe<URL>,
  githubToken: Maybe<string>,
) {
  const url = odcVersion.mapOrDefault(value => {
    return TAG_RELEASE_URL + value;
  }, LATEST_RELEASE_URL);
  return fetchJson(url, createRequestInit(proxyUrl, githubToken))
    .chain(data => castGithubRelease(data))
    .ifRight(() => {
      log.info(`Fetched release information from ${url}`);
    });
}
 
export function findDownloadAsset(release: GithubRelease) {
  return Maybe.fromNullable(release.assets.find(a => NAME_RE.test(a.name)));
}
 
function downloadRelease(
  url: string,
  name: string,
  installDir: string,
  proxyUrl: Maybe<URL>,
) {
  return downloadFile(
    url,
    createRequestInit(proxyUrl, Maybe.empty()),
    path.resolve(installDir, name),
  )
    .ifRight(() => {
      log.info(`Downloaded dependency check from ${url}`);
    })
    .mapLeft(() => Error(`Download failed from ${url}`));
}
 
export function createRequestInit(
  proxyUrl: Maybe<URL>,
  githubToken: Maybe<string>,
) {
  return buildRequestInit(
    proxyUrl,
    githubToken.map(token => {
      return { Authorization: `Bearer ${token}` };
    }),
  );
}
 
function installRelease(
  release: GithubRelease,
  installDir: string,
  proxyUrl: Maybe<URL>,
) {
  log.info(`Installing dependency check ${release.tag_name}...`);
  cleanDir(installDir, log);

  return EitherAsync.liftEither(
    findDownloadAsset(release).toEither(
      Error(`Could not find asset for version ${release.tag_name}`),
    ),
  )
    .chain(asset =>
      downloadRelease(
        asset.browser_download_url,
        asset.name,
        installDir,
        proxyUrl,
      ),
    )
    .chain(filePath => unzipFileIntoDirectory(filePath, installDir, true, log))
    .mapLeft(() => Error("Could not unzip files"))
    .chain(() =>
      EitherAsync.liftEither(
        findOwaspExecutable(installDir).toEither(
          Error(
            `Could not find Dependency-Check Core executable in ${installDir}`,
          ),
        ),
      ),
    );
}
 
export async function installDependencyCheck(
  binDir: string,
  odcVersion: Maybe<string>,
  proxyUrl: Maybe<URL>,
  githubToken: Maybe<string>,
  forceInstall: boolean,
  keepOldVersions: boolean,
) {
  const release = (
    await findReleaseInfo(odcVersion, proxyUrl, githubToken).mapLeft(error =>
      Error(`Could not fetch release from GitHub. Reason: ${error.message}`),
    )
  ).unsafeCoerce();
  log.info(`Found release ${release.tag_name} on GitHub.`);

  const installDir = path.resolve(binDir, release.tag_name);
  const executable = findOwaspExecutable(installDir).filter(
    () => !forceInstall,
  );
  if (executable.isJust()) {
    log.info(
      `Using already installed dependency check at "${executable.unsafeCoerce()}".`,
    );
    return executable.unsafeCoerce();
  }

  if (!keepOldVersions) {
    cleanDir(binDir, log);
  }
  return (await installRelease(release, installDir, proxyUrl)).unsafeCoerce();
}