1const fs = require('node:fs');
2const path = require('node:path');
3const crypto = require('node:crypto');
4
5module.exports = function restore(root, added, deleted) {
6 root = fs.realpathSync(root);
7 function destination(relative) {
8 const parts = relative.split('/');
9 if (parts.some(p => !p || p === '.' || p === '..') || relative.includes('\\')) {
10 throw new Error('Invalid cached path');
11 }
12 let parent = root;
13 for (const part of parts.slice(0, -1)) {
14 parent = path.join(parent, part);
15 try { fs.mkdirSync(parent); } catch (error) { if (error.code !== 'EEXIST') throw error; }
16 if (!fs.lstatSync(parent).isDirectory() || fs.realpathSync(parent) !== parent) {
17 throw new Error('Cached path follows a symlink');
18 }
19 }
20 return path.join(parent, parts.at(-1));
21 }
22 for (const relative of deleted) fs.rmSync(destination(relative), {force: true});
23 for (const [relative, source, mode] of added) {
24 const dest = destination(relative);
25 const temporary = dest + '.project-' + crypto.randomUUID();
26 const fd = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
27 try {
28 if (!fs.fstatSync(fd).isFile()) throw new Error('Cache entry is not a regular file');
29 const expected = path.basename(path.dirname(source)) + path.basename(source).replace(/-exec$/, '');
30 const hash = crypto.createHash('sha512');
31 const buffer = Buffer.alloc(65536);
32 let length;
33 while ((length = fs.readSync(fd, buffer)) > 0) hash.update(buffer.subarray(0, length));
34 if (!/^[a-f0-9]{128}$/.test(expected) || hash.digest('hex') !== expected) {
35 throw new Error('Cached file failed integrity verification');
36 }
37 fs.copyFileSync('/proc/self/fd/' + fd, temporary, fs.constants.COPYFILE_FICLONE_FORCE);
38 fs.chmodSync(temporary, mode & 0o777);
39 fs.renameSync(temporary, dest);
40 } finally {
41 fs.closeSync(fd);
42 fs.rmSync(temporary, {force: true});
43 }
44 }
45};