| 1 |
"use strict"; |
| 2 |
var __importDefault = (this && this.__importDefault) || function (mod) { |
| 3 |
return (mod && mod.__esModule) ? mod : { "default": mod }; |
| 4 |
}; |
| 5 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 6 |
exports.readTarget = readTarget; |
| 7 |
/* |
| 8 |
Copyright 2023 The Sigstore Authors. |
| 9 |
|
| 10 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 |
you may not use this file except in compliance with the License. |
| 12 |
You may obtain a copy of the License at |
| 13 |
|
| 14 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 15 |
|
| 16 |
Unless required by applicable law or agreed to in writing, software |
| 17 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 18 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 |
See the License for the specific language governing permissions and |
| 20 |
limitations under the License. |
| 21 |
*/ |
| 22 |
const fs_1 = __importDefault(require("fs")); |
| 23 |
const error_1 = require("./error"); |
| 24 |
// Downloads and returns the specified target from the provided TUF Updater. |
| 25 |
async function readTarget(tuf, targetPath) { |
| 26 |
const path = await getTargetPath(tuf, targetPath); |
| 27 |
return new Promise((resolve, reject) => { |
| 28 |
fs_1.default.readFile(path, 'utf-8', (err, data) => { |
| 29 |
if (err) { |
| 30 |
reject(new error_1.TUFError({ |
| 31 |
code: 'TUF_READ_TARGET_ERROR', |
| 32 |
message: `error reading target ${path}`, |
| 33 |
cause: err, |
| 34 |
})); |
| 35 |
} |
| 36 |
else { |
| 37 |
resolve(data); |
| 38 |
} |
| 39 |
}); |
| 40 |
}); |
| 41 |
} |
| 42 |
// Returns the local path to the specified target. If the target is not yet |
| 43 |
// cached locally, the provided TUF Updater will be used to download and |
| 44 |
// cache the target. |
| 45 |
async function getTargetPath(tuf, target) { |
| 46 |
let targetInfo; |
| 47 |
try { |
| 48 |
targetInfo = await tuf.getTargetInfo(target); |
| 49 |
} |
| 50 |
catch (err) { |
| 51 |
throw new error_1.TUFError({ |
| 52 |
code: 'TUF_REFRESH_METADATA_ERROR', |
| 53 |
message: 'error refreshing TUF metadata', |
| 54 |
cause: err, |
| 55 |
}); |
| 56 |
} |
| 57 |
if (!targetInfo) { |
| 58 |
throw new error_1.TUFError({ |
| 59 |
code: 'TUF_FIND_TARGET_ERROR', |
| 60 |
message: `target ${target} not found`, |
| 61 |
}); |
| 62 |
} |
| 63 |
let path = await tuf.findCachedTarget(targetInfo); |
| 64 |
// An empty path here means the target has not been cached locally, or is |
| 65 |
// out of date. In either case, we need to download it. |
| 66 |
if (!path) { |
| 67 |
try { |
| 68 |
path = await tuf.downloadTarget(targetInfo); |
| 69 |
} |
| 70 |
catch (err) { |
| 71 |
throw new error_1.TUFError({ |
| 72 |
code: 'TUF_DOWNLOAD_TARGET_ERROR', |
| 73 |
message: `error downloading target ${path}`, |
| 74 |
cause: err, |
| 75 |
}); |
| 76 |
} |
| 77 |
} |
| 78 |
return path; |
| 79 |
} |