summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/tuf-js/dist/updater.js
blob: 7f8b6bedeedd3e23432a20125392ac21d7bf9882 (plain)
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Updater = void 0;
const models_1 = require("@tufjs/models");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_1 = require("./config");
const error_1 = require("./error");
const fetcher_1 = require("./fetcher");
const store_1 = require("./store");
class Updater {
    constructor(options) {
        const { metadataDir, metadataBaseUrl, targetDir, targetBaseUrl, fetcher, config, } = options;
        this.dir = metadataDir;
        this.metadataBaseUrl = metadataBaseUrl;
        this.targetDir = targetDir;
        this.targetBaseUrl = targetBaseUrl;
        const data = this.loadLocalMetadata(models_1.MetadataKind.Root);
        this.trustedSet = new store_1.TrustedMetadataStore(data);
        this.config = { ...config_1.defaultConfig, ...config };
        this.fetcher =
            fetcher ||
                new fetcher_1.DefaultFetcher({
                    timeout: this.config.fetchTimeout,
                    retries: this.config.fetchRetries,
                });
    }
    async refresh() {
        await this.loadRoot();
        await this.loadTimestamp();
        await this.loadSnapshot();
        await this.loadTargets(models_1.MetadataKind.Targets, models_1.MetadataKind.Root);
    }
    // Returns the TargetFile instance with information for the given target path.
    //
    // Implicitly calls refresh if it hasn't already been called.
    async getTargetInfo(targetPath) {
        if (!this.trustedSet.targets) {
            await this.refresh();
        }
        return this.preorderDepthFirstWalk(targetPath);
    }
    async downloadTarget(targetInfo, filePath, targetBaseUrl) {
        const targetPath = filePath || this.generateTargetPath(targetInfo);
        if (!targetBaseUrl) {
            if (!this.targetBaseUrl) {
                throw new error_1.ValueError('Target base URL not set');
            }
            targetBaseUrl = this.targetBaseUrl;
        }
        let targetFilePath = targetInfo.path;
        const consistentSnapshot = this.trustedSet.root.signed.consistentSnapshot;
        if (consistentSnapshot && this.config.prefixTargetsWithHash) {
            const hashes = Object.values(targetInfo.hashes);
            const basename = path.basename(targetFilePath);
            targetFilePath = `${hashes[0]}.${basename}`;
        }
        const url = path.join(targetBaseUrl, targetFilePath);
        // Client workflow 5.7.3: download target file
        await this.fetcher.downloadFile(url, targetInfo.length, async (fileName) => {
            // Verify hashes and length of downloaded file
            await targetInfo.verify(fs.createReadStream(fileName));
            // Copy file to target path
            fs.copyFileSync(fileName, targetPath);
        });
        return targetPath;
    }
    async findCachedTarget(targetInfo, filePath) {
        if (!filePath) {
            filePath = this.generateTargetPath(targetInfo);
        }
        try {
            if (fs.existsSync(filePath)) {
                targetInfo.verify(fs.createReadStream(filePath));
                return filePath;
            }
        }
        catch (error) {
            return; // File not found
        }
        return; // File not found
    }
    loadLocalMetadata(fileName) {
        const filePath = path.join(this.dir, `${fileName}.json`);
        return fs.readFileSync(filePath);
    }
    // Sequentially load and persist on local disk every newer root metadata
    // version available on the remote.
    // Client workflow 5.3: update root role
    async loadRoot() {
        // Client workflow 5.3.2: version of trusted root metadata file
        const rootVersion = this.trustedSet.root.signed.version;
        const lowerBound = rootVersion + 1;
        const upperBound = lowerBound + this.config.maxRootRotations;
        for (let version = lowerBound; version <= upperBound; version++) {
            const url = path.join(this.metadataBaseUrl, `${version}.root.json`);
            try {
                // Client workflow 5.3.3: download new root metadata file
                const bytesData = await this.fetcher.downloadBytes(url, this.config.rootMaxLength);
                // Client workflow 5.3.4 - 5.4.7
                this.trustedSet.updateRoot(bytesData);
                // Client workflow 5.3.8: persist root metadata file
                this.persistMetadata(models_1.MetadataKind.Root, bytesData);
            }
            catch (error) {
                break;
            }
        }
    }
    // Load local and remote timestamp metadata.
    // Client workflow 5.4: update timestamp role
    async loadTimestamp() {
        // Load local and remote timestamp metadata
        try {
            const data = this.loadLocalMetadata(models_1.MetadataKind.Timestamp);
            this.trustedSet.updateTimestamp(data);
        }
        catch (error) {
            // continue
        }
        //Load from remote (whether local load succeeded or not)
        const url = path.join(this.metadataBaseUrl, `timestamp.json`);
        // Client workflow 5.4.1: download timestamp metadata file
        const bytesData = await this.fetcher.downloadBytes(url, this.config.timestampMaxLength);
        try {
            // Client workflow 5.4.2 - 5.4.4
            this.trustedSet.updateTimestamp(bytesData);
        }
        catch (error) {
            // If new timestamp version is same as current, discardd the new one.
            // This is normal and should NOT raise an error.
            if (error instanceof error_1.EqualVersionError) {
                return;
            }
            // Re-raise any other error
            throw error;
        }
        // Client workflow 5.4.5: persist timestamp metadata
        this.persistMetadata(models_1.MetadataKind.Timestamp, bytesData);
    }
    // Load local and remote snapshot metadata.
    // Client workflow 5.5: update snapshot role
    async loadSnapshot() {
        //Load local (and if needed remote) snapshot metadata
        try {
            const data = this.loadLocalMetadata(models_1.MetadataKind.Snapshot);
            this.trustedSet.updateSnapshot(data, true);
        }
        catch (error) {
            if (!this.trustedSet.timestamp) {
                throw new ReferenceError('No timestamp metadata');
            }
            const snapshotMeta = this.trustedSet.timestamp.signed.snapshotMeta;
            const maxLength = snapshotMeta.length || this.config.snapshotMaxLength;
            const version = this.trustedSet.root.signed.consistentSnapshot
                ? snapshotMeta.version
                : undefined;
            const url = path.join(this.metadataBaseUrl, version ? `${version}.snapshot.json` : `snapshot.json`);
            try {
                // Client workflow 5.5.1: download snapshot metadata file
                const bytesData = await this.fetcher.downloadBytes(url, maxLength);
                // Client workflow 5.5.2 - 5.5.6
                this.trustedSet.updateSnapshot(bytesData);
                // Client workflow 5.5.7: persist snapshot metadata file
                this.persistMetadata(models_1.MetadataKind.Snapshot, bytesData);
            }
            catch (error) {
                throw new error_1.RuntimeError(`Unable to load snapshot metadata error ${error}`);
            }
        }
    }
    // Load local and remote targets metadata.
    // Client workflow 5.6: update targets role
    async loadTargets(role, parentRole) {
        if (this.trustedSet.getRole(role)) {
            return this.trustedSet.getRole(role);
        }
        try {
            const buffer = this.loadLocalMetadata(role);
            this.trustedSet.updateDelegatedTargets(buffer, role, parentRole);
        }
        catch (error) {
            // Local 'role' does not exist or is invalid: update from remote
            if (!this.trustedSet.snapshot) {
                throw new ReferenceError('No snapshot metadata');
            }
            const metaInfo = this.trustedSet.snapshot.signed.meta[`${role}.json`];
            // TODO: use length for fetching
            const maxLength = metaInfo.length || this.config.targetsMaxLength;
            const version = this.trustedSet.root.signed.consistentSnapshot
                ? metaInfo.version
                : undefined;
            const url = path.join(this.metadataBaseUrl, version ? `${version}.${role}.json` : `${role}.json`);
            try {
                // Client workflow 5.6.1: download targets metadata file
                const bytesData = await this.fetcher.downloadBytes(url, maxLength);
                // Client workflow 5.6.2 - 5.6.6
                this.trustedSet.updateDelegatedTargets(bytesData, role, parentRole);
                // Client workflow 5.6.7: persist targets metadata file
                this.persistMetadata(role, bytesData);
            }
            catch (error) {
                throw new error_1.RuntimeError(`Unable to load targets error ${error}`);
            }
        }
        return this.trustedSet.getRole(role);
    }
    async preorderDepthFirstWalk(targetPath) {
        // Interrogates the tree of target delegations in order of appearance
        // (which implicitly order trustworthiness), and returns the matching
        // target found in the most trusted role.
        // List of delegations to be interrogated. A (role, parent role) pair
        // is needed to load and verify the delegated targets metadata.
        const delegationsToVisit = [
            {
                roleName: models_1.MetadataKind.Targets,
                parentRoleName: models_1.MetadataKind.Root,
            },
        ];
        const visitedRoleNames = new Set();
        // Client workflow 5.6.7: preorder depth-first traversal of the graph of
        // target delegations
        while (visitedRoleNames.size <= this.config.maxDelegations &&
            delegationsToVisit.length > 0) {
            //  Pop the role name from the top of the stack.
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            const { roleName, parentRoleName } = delegationsToVisit.pop();
            // Skip any visited current role to prevent cycles.
            // Client workflow 5.6.7.1: skip already-visited roles
            if (visitedRoleNames.has(roleName)) {
                continue;
            }
            // The metadata for 'role_name' must be downloaded/updated before
            // its targets, delegations, and child roles can be inspected.
            const targets = (await this.loadTargets(roleName, parentRoleName))
                ?.signed;
            if (!targets) {
                continue;
            }
            const target = targets.targets?.[targetPath];
            if (target) {
                return target;
            }
            // After preorder check, add current role to set of visited roles.
            visitedRoleNames.add(roleName);
            if (targets.delegations) {
                const childRolesToVisit = [];
                // NOTE: This may be a slow operation if there are many delegated roles.
                const rolesForTarget = targets.delegations.rolesForTarget(targetPath);
                for (const { role: childName, terminating } of rolesForTarget) {
                    childRolesToVisit.push({
                        roleName: childName,
                        parentRoleName: roleName,
                    });
                    // Client workflow 5.6.7.2.1
                    if (terminating) {
                        delegationsToVisit.splice(0); // empty the array
                        break;
                    }
                }
                childRolesToVisit.reverse();
                delegationsToVisit.push(...childRolesToVisit);
            }
        }
        return; // no matching target found
    }
    generateTargetPath(targetInfo) {
        if (!this.targetDir) {
            throw new error_1.ValueError('Target directory not set');
        }
        return path.join(this.targetDir, targetInfo.path);
    }
    async persistMetadata(metaDataName, bytesData) {
        try {
            const filePath = path.join(this.dir, `${metaDataName}.json`);
            fs.writeFileSync(filePath, bytesData.toString('utf8'));
        }
        catch (error) {
            throw new error_1.PersistError(`Failed to persist metadata ${metaDataName} error: ${error}`);
        }
    }
}
exports.Updater = Updater;