1const assert = require('node:assert/strict');
2const fs = require('node:fs');
3const os = require('node:os');
4const path = require('node:path');
5const crypto = require('node:crypto');
6const restore = require('./restore.cjs');
7
8const root = fs.mkdtempSync(path.join(os.tmpdir(), 'project-restore-'));
9try {
10 const bytes = process.env.PROJECT_RESTORE_SOURCE ? fs.readFileSync(process.env.PROJECT_RESTORE_SOURCE) : Buffer.from('cached native artifact');
11 const digest = crypto.createHash('sha512').update(bytes).digest('hex');
12 const source = process.env.PROJECT_RESTORE_SOURCE || path.join(root, digest.slice(0, 2), digest.slice(2));
13 if (!process.env.PROJECT_RESTORE_SOURCE) {
14 fs.mkdirSync(path.dirname(source));
15 fs.writeFileSync(source, bytes);
16 }
17 const destination = path.join(root, 'package');
18 fs.mkdirSync(destination);
19 restore(destination, [['bin/tool', source, 0o755]], []);
20 assert.equal(fs.readFileSync(path.join(destination, 'bin/tool'), 'utf8'), bytes.toString());
21 fs.writeFileSync(path.join(destination, 'bin/tool'), 'changed');
22 assert.deepEqual(fs.readFileSync(source), bytes);
23 fs.symlinkSync(root, path.join(destination, 'escape'));
24 assert.throws(() => restore(destination, [['escape/tool', source, 0o755]], []), /symlink/);
25 assert.throws(() => restore(destination, [['../tool', source, 0o755]], []), /Invalid/);
26 const corrupt = path.join(root, digest.slice(0, 2), digest.slice(2) + '-exec');
27 fs.mkdirSync(path.dirname(corrupt), {recursive: true});
28 fs.writeFileSync(corrupt, 'corrupt');
29 assert.throws(() => restore(destination, [['bin/tool', corrupt, 0o755]], []), /integrity/);
30 assert.equal(fs.readFileSync(path.join(destination, 'bin/tool'), 'utf8'), 'changed');
31 console.log('Reflink independence, path guards, and corrupt-cache rejection passed.');
32} finally {
33 fs.rmSync(root, {recursive: true, force: true});
34}