1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3    return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.TUFClient = void 0;
7/*
8Copyright 2023 The Sigstore Authors.
9
10Licensed under the Apache License, Version 2.0 (the "License");
11you may not use this file except in compliance with the License.
12You may obtain a copy of the License at
13
14    http://www.apache.org/licenses/LICENSE-2.0
15
16Unless required by applicable law or agreed to in writing, software
17distributed under the License is distributed on an "AS IS" BASIS,
18WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19See the License for the specific language governing permissions and
20limitations under the License.
21*/
22const fs_1 = __importDefault(require("fs"));
23const path_1 = __importDefault(require("path"));
24const tuf_js_1 = require("tuf-js");
25const _1 = require(".");
26const target_1 = require("./target");
27const TARGETS_DIR_NAME = 'targets';
28class TUFClient {
29    constructor(options) {
30        const url = new URL(options.mirrorURL);
31        const repoName = encodeURIComponent(url.host + url.pathname.replace(/\/$/, ''));
32        const cachePath = path_1.default.join(options.cachePath, repoName);
33        initTufCache(cachePath);
34        seedCache({
35            cachePath,
36            mirrorURL: options.mirrorURL,
37            tufRootPath: options.rootPath,
38            forceInit: options.forceInit,
39        });
40        this.updater = initClient({
41            mirrorURL: options.mirrorURL,
42            cachePath,
43            forceCache: options.forceCache,
44            retry: options.retry,
45            timeout: options.timeout,
46        });
47    }
48    async refresh() {
49        return this.updater.refresh();
50    }
51    getTarget(targetName) {
52        return (0, target_1.readTarget)(this.updater, targetName);
53    }
54}
55exports.TUFClient = TUFClient;
56// Initializes the TUF cache directory structure including the initial
57// root.json file. If the cache directory does not exist, it will be
58// created. If the targets directory does not exist, it will be created.
59// If the root.json file does not exist, it will be copied from the
60// rootPath argument.
61function initTufCache(cachePath) {
62    const targetsPath = path_1.default.join(cachePath, TARGETS_DIR_NAME);
63    if (!fs_1.default.existsSync(cachePath)) {
64        fs_1.default.mkdirSync(cachePath, { recursive: true });
65    }
66    if (!fs_1.default.existsSync(targetsPath)) {
67        fs_1.default.mkdirSync(targetsPath);
68    }
69}
70// Populates the TUF cache with the initial root.json file. If the root.json
71// file does not exist (or we're forcing re-initialization), copy it from either
72// the rootPath argument or from one of the repo seeds.
73function seedCache({ cachePath, mirrorURL, tufRootPath, forceInit, }) {
74    const cachedRootPath = path_1.default.join(cachePath, 'root.json');
75    // If the root.json file does not exist (or we're forcing re-initialization),
76    // populate it either from the supplied rootPath or from one of the repo seeds.
77    if (!fs_1.default.existsSync(cachedRootPath) || forceInit) {
78        if (tufRootPath) {
79            fs_1.default.copyFileSync(tufRootPath, cachedRootPath);
80        }
81        else {
82            /* eslint-disable @typescript-eslint/no-var-requires */
83            const seeds = require('../seeds.json');
84            const repoSeed = seeds[mirrorURL];
85            if (!repoSeed) {
86                throw new _1.TUFError({
87                    code: 'TUF_INIT_CACHE_ERROR',
88                    message: `No root.json found for mirror: ${mirrorURL}`,
89                });
90            }
91            fs_1.default.writeFileSync(cachedRootPath, Buffer.from(repoSeed['root.json'], 'base64'));
92            // Copy any seed targets into the cache
93            Object.entries(repoSeed.targets).forEach(([targetName, target]) => {
94                fs_1.default.writeFileSync(path_1.default.join(cachePath, TARGETS_DIR_NAME, targetName), Buffer.from(target, 'base64'));
95            });
96        }
97    }
98}
99function initClient(options) {
100    const config = {
101        fetchTimeout: options.timeout,
102        fetchRetry: options.retry,
103    };
104    return new tuf_js_1.Updater({
105        metadataBaseUrl: options.mirrorURL,
106        targetBaseUrl: `${options.mirrorURL}/targets`,
107        metadataDir: options.cachePath,
108        targetDir: path_1.default.join(options.cachePath, TARGETS_DIR_NAME),
109        forceCache: options.forceCache,
110        config,
111    });
112}
113