跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

prepare-release-assets.mjs

184 行 · 9.9 KB历史下载
1// Assemble local assets produced by the platform release packagers. Those
2// packagers and the native updater own signature verification; this script
3// checks the release names, complete source materials and exact file digests.
4import { createHash } from 'node:crypto';
5import { constants, createWriteStream } from 'node:fs';
6import { copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, rm, rmdir, unlink, writeFile } from 'node:fs/promises';
7import { tmpdir } from 'node:os';
8import { dirname, join, resolve } from 'node:path';
9import { Transform, Writable } from 'node:stream';
10import { pipeline } from 'node:stream/promises';
11import { pathToFileURL } from 'node:url';
12import { parseArgs } from 'node:util';
13
14const maxChecksums = 64 * 1024;
15const maxInstaller = 512 * 1024 * 1024;
16
17async function releaseNames() {
18 const version = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim();
19 if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error('Invalid repository VERSION');
20 const dependencies = JSON.parse(await readFile(new URL('../packaging/windows/dependencies.json', import.meta.url), 'utf8'));
21 const linuxDependencies = JSON.parse(await readFile(new URL('../packaging/linux/dependencies.json', import.meta.url), 'utf8'));
22 const macCoreScript = await readFile(new URL('./fetch-proxy-core.sh', import.meta.url), 'utf8');
23 const macCore = macCoreScript.match(/^version=(v[\d.]+)$/m)?.[1];
24 if (!macCore || !/^v[\d.]+$/.test(dependencies.mihomo.version) || !/^[\d.]+$/.test(dependencies.qemu.version)) {
25 throw new Error('Cannot identify the pinned release dependencies');
26 }
27 return {
28 version,
29 mac: `Cage-${version}-macos-arm64.dmg`,
30 windows: `Cage-${version}-windows-amd64-setup.exe`,
31 linux: `Cage-${version}-linux-amd64.deb`,
32 linuxSource: linuxDependencies.mihomoSource.file,
33 macSource: `mihomo-${macCore}-source.tar.gz`,
34 macGuestSource: `cage-macos-guest-${version}-source.tar.gz`,
35 windowsSource: `mihomo-${dependencies.mihomo.version}-source.tar.gz`,
36 qemuPrefix: `qemu-${dependencies.qemu.version}-windows-full-source.`,
37 qemuSource: `${dependencies.qemuSource.file}.gz`,
38 qemuKeymap: `qemu-keycodemapdb-${dependencies.qemuKeycodemap.version}-source.tar.gz`,
39 qemuChanges: `qemu-${dependencies.qemu.version}-cage-changes-source.tar.gz`,
40 };
41}
42
43async function regularFile(path) {
44 const info = await lstat(path);
45 if (!info.isFile() || info.isSymbolicLink()) throw new Error(`Expected a regular file: ${path}`);
46 return info;
47}
48
49async function readManifest(directory) {
50 const path = join(directory, 'SHA256SUMS');
51 const info = await regularFile(path);
52 if (!info.size || info.size > maxChecksums) throw new Error(`Invalid SHA256SUMS size: ${directory}`);
53 const text = (await readFile(path, 'utf8')).replace(/^\uFEFF/, '');
54 const entries = new Map();
55 for (const line of text.split(/\r?\n/)) {
56 if (!line) continue;
57 const match = /^([a-f0-9]{64}) [ *]([A-Za-z0-9][A-Za-z0-9._-]*)$/i.exec(line);
58 if (!match || entries.has(match[2])) throw new Error(`Invalid or duplicate SHA256SUMS entry: ${directory}`);
59 entries.set(match[2], match[1].toLowerCase());
60 }
61 if (!entries.size) throw new Error(`Empty SHA256SUMS: ${directory}`);
62 return entries;
63}
64
65function isQemuArchive(name, names) {
66 return name.startsWith(names.qemuPrefix) && /^(?:tar\.)?(?:gz|xz|bz2|zst|zip|7z|tar)$/.test(name.slice(names.qemuPrefix.length));
67}
68
69async function verifyAndStage(source, digest, destination, installer) {
70 const before = await regularFile(source);
71 if (!before.size || (installer && before.size > maxInstaller)) throw new Error(`Invalid release asset size: ${source}`);
72 const file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
73 try {
74 const opened = await file.stat();
75 if (!opened.isFile() || before.ino !== opened.ino || before.dev !== opened.dev) throw new Error(`Release asset changed while opening: ${source}`);
76 const hash = createHash('sha256');
77 let size = 0;
78 const sink = destination ? createWriteStream(destination, { flags: 'wx', mode: 0o600 }) : new Writable({ write(_chunk, _encoding, callback) { callback(); } });
79 await pipeline(file.createReadStream({ autoClose: false }), new Transform({
80 transform(chunk, _encoding, callback) {
81 size += chunk.length;
82 if (size > opened.size) return callback(new Error(`Release asset changed while reading: ${source}`));
83 hash.update(chunk);
84 callback(null, chunk);
85 },
86 }), sink);
87 if (size !== opened.size || hash.digest('hex') !== digest) throw new Error(`SHA-256 mismatch: ${source}`);
88 } finally {
89 await file.close();
90 }
91}
92
93export async function prepareReleaseAssets({ inputs, output }) {
94 if (!Array.isArray(inputs) || !inputs.length || !output) throw new Error('Provide --output and at least one platform release directory');
95 const target = resolve(output);
96 try {
97 await lstat(target);
98 throw new Error(`Output must be a new directory; existing release assets are never overwritten: ${target}`);
99 } catch (error) {
100 if (error.code !== 'ENOENT') throw error;
101 }
102 const names = await releaseNames();
103 const all = new Map();
104 const inputsToVerify = [];
105 for (const input of inputs) {
106 const directory = resolve(input);
107 const info = await lstat(directory);
108 if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Expected a platform release directory: ${directory}`);
109 const files = await readdir(directory);
110 if (files.some(name => /^Cage-.*-windows-.*-unsigned\.exe$/i.test(name) || name === 'DEVELOPMENT-BUILD.txt')) {
111 throw new Error(`Unsigned Windows development build cannot be prepared for release: ${directory}`);
112 }
113 const entries = await readManifest(directory);
114 const mac = entries.has(names.mac);
115 const windows = entries.has(names.windows);
116 const linux = entries.has(names.linux);
117 if (!mac && !windows && !linux) throw new Error(`No supported package name for VERSION ${names.version}: ${directory}`);
118 if (linux && !entries.has(names.linuxSource)) throw new Error(`Missing Linux Mihomo source in SHA256SUMS: ${directory}`);
119 if (mac && !entries.has(names.macSource)) throw new Error(`Missing macOS Mihomo source in SHA256SUMS: ${directory}`);
120 if (mac && !entries.has(names.macGuestSource)) throw new Error(`Missing macOS guest corresponding source in SHA256SUMS: ${directory}`);
121 if (windows && (!entries.has(names.windowsSource) || ![...entries.keys()].some(name => isQemuArchive(name, names)))) {
122 throw new Error(`Windows release requires its Mihomo and complete QEMU source archives in the same SHA256SUMS: ${directory}`);
123 }
124 for (const [name, digest] of entries) {
125 const installer = name === names.mac || name === names.windows || name === names.linux;
126 if (!installer && ![names.macSource, names.macGuestSource, names.windowsSource, names.linuxSource, names.qemuSource, names.qemuKeymap, names.qemuChanges].includes(name) && !isQemuArchive(name, names)) {
127 throw new Error(`Unsupported asset or version in SHA256SUMS: ${name}`);
128 }
129 const existing = all.get(name);
130 if (existing && existing !== digest) throw new Error(`Conflicting same-name release asset: ${name}`);
131 inputsToVerify.push({ source: join(directory, name), digest, name, installer, first: !existing });
132 all.set(name, digest);
133 }
134 }
135
136 const staging = await mkdtemp(join(tmpdir(), 'cage-release-assets-'));
137 const created = [];
138 let ownsTarget = false;
139 try {
140 // Validate every input, including identical-name duplicates. The output
141 // gets these verified snapshots, never a second read of mutable inputs.
142 for (const asset of inputsToVerify) {
143 await verifyAndStage(asset.source, asset.digest, asset.first ? join(staging, asset.name) : undefined, asset.installer);
144 }
145 const sorted = [...all].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
146 const checksums = sorted.map(([name, digest]) => `${digest} ${name}\n`).join('');
147 if (Buffer.byteLength(checksums) > maxChecksums) throw new Error('Merged SHA256SUMS exceeds the updater limit');
148 await mkdir(dirname(target), { recursive: true });
149 await mkdir(target); // Exclusive creation also closes the preflight race.
150 ownsTarget = true;
151 for (const [name] of sorted) {
152 await copyFile(join(staging, name), join(target, name), constants.COPYFILE_EXCL);
153 created.push(name);
154 }
155 await writeFile(join(target, 'SHA256SUMS'), checksums, { flag: 'wx', mode: 0o644 });
156 created.push('SHA256SUMS');
157 return { version: names.version, directory: target, assets: sorted.map(([name]) => name) };
158 } catch (error) {
159 if (ownsTarget) {
160 // Delete only our files. Preserve any unexpected concurrently added file.
161 for (const name of created) await unlink(join(target, name)).catch(() => {});
162 await rmdir(target).catch(() => {});
163 }
164 throw error;
165 } finally {
166 await rm(staging, { recursive: true, force: true });
167 }
168}
169
170async function main() {
171 const { values, positionals } = parseArgs({ allowPositionals: true, options: {
172 output: { type: 'string' }, help: { type: 'boolean', short: 'h' },
173 } });
174 if (values.help) {
175 console.log('Usage: node scripts/prepare-release-assets.mjs --output NEW_DIRECTORY PLATFORM_DIRECTORY [...]\nAccepts macOS, Windows and Linux release outputs with SHA256SUMS. Checks current VERSION, source archives and hashes; macOS/Windows signature verification belongs to their packagers. Linux packages use manual system installation. Never uploads or overwrites an existing output directory.');
176 return;
177 }
178 const result = await prepareReleaseAssets({ inputs: positionals, output: values.output });
179 console.log(`Prepared Cage ${result.version}: ${result.assets.length} verified assets and one SHA256SUMS in ${result.directory}`);
180}
181
182if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
183 main().catch(error => { console.error(error.message); process.exitCode = 1; });
184}