跳到主要内容

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

浏览文件

release-control.test.mjs

413 行 · 22.8 KB历史下载
1import assert from 'node:assert/strict';
2import { execFileSync } from 'node:child_process';
3import { createHash, randomUUID } from 'node:crypto';
4import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
5import { tmpdir } from 'node:os';
6import { dirname, join } from 'node:path';
7import test from 'node:test';
8import {
9 assembleRelease, expectedFiles, prepareRelease, publishRelease, releaseFiles,
10 verifyCandidate, versionPaths, workflowContext, releaseNotes,
11} from './release-control.mjs';
12
13const repository = 'Lee-xeo/Claude-Cage';
14const base = `/repos/${repository}`;
15const currentVersion = (await readFile(new URL('../VERSION', import.meta.url), 'utf8')).trim();
16const windowsDependencies = JSON.parse(await readFile(new URL('../packaging/windows/dependencies.json', import.meta.url), 'utf8'));
17const linuxDependencies = JSON.parse(await readFile(new URL('../packaging/linux/dependencies.json', import.meta.url), 'utf8'));
18const macCoreVersion = (await readFile(new URL('./fetch-proxy-core.sh', import.meta.url), 'utf8')).match(/^version=(v[\d.]+)$/m)[1];
19const digest = value => createHash('sha256').update(value).digest('hex');
20const copy = value => structuredClone(value);
21
22async function temporary(t) {
23 const root = await mkdtemp(join(tmpdir(), 'cage-release-control-'));
24 t.after(() => rm(root, { recursive: true, force: true }));
25 return root;
26}
27
28// Git trees and commits are real. Only the GitHub transport and remote refs
29// are simulated, so changes to version files can be checked against Git data.
30async function repositoryFixture(t) {
31 const root = await temporary(t);
32 const environment = {
33 ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(root, 'no-global-config'),
34 GIT_AUTHOR_NAME: 'Release Test', GIT_AUTHOR_EMAIL: '[email protected]',
35 GIT_COMMITTER_NAME: 'Release Test', GIT_COMMITTER_EMAIL: '[email protected]',
36 };
37 const git = (args, options = {}) => execFileSync('git', args, {
38 cwd: root, encoding: 'utf8', env: environment, stdio: ['pipe', 'pipe', 'pipe'], ...options,
39 }).trimEnd();
40 git(['init', '--quiet', '--initial-branch=main']);
41 await writeFile(join(root, 'VERSION'), currentVersion + '\n');
42 for (const directory of ['ui', 'www']) {
43 await mkdir(join(root, directory));
44 const manifest = { name: directory, version: currentVersion, dependencies: { fixture: '1.0.0' } };
45 const lock = { ...manifest, lockfileVersion: 3, packages: { '': manifest, 'node_modules/fixture': { version: '1.0.0', integrity: 'keep-this-integrity' } } };
46 await writeFile(join(root, directory, 'package.json'), JSON.stringify(manifest, null, 2) + '\n');
47 await writeFile(join(root, directory, 'package-lock.json'), JSON.stringify(lock, null, 2) + '\n');
48 }
49 git(['add', '--', ...versionPaths]);
50 git(['commit', '--quiet', '-m', 'Fixture source']);
51 const sourceSha = git(['rev-parse', 'HEAD']);
52 const context = { repository, sourceSha, runId: '1042', defaultBranch: 'main', bump: 'prerelease' };
53 const state = { main: sourceSha, refs: new Map(), release: null, otherReleases: [], nextReleaseId: 42, assets: [], calls: [], uploads: [], promotions: [] };
54 async function tree(baseTree, entries) {
55 const index = join(root, '.git', `test-index-${randomUUID()}`);
56 const env = { ...environment, GIT_INDEX_FILE: index };
57 try {
58 git(['read-tree', baseTree], { env });
59 for (const entry of entries) {
60 const blob = git(['hash-object', '-w', '--stdin'], { input: entry.content, env });
61 git(['update-index', '--add', '--cacheinfo', entry.mode || '100644', blob, entry.path], { env });
62 }
63 return git(['write-tree'], { env });
64 } finally { await rm(index, { force: true }); }
65 }
66 const notFound = () => { throw Object.assign(new Error('Not found'), { status: 404 }); };
67 const api = async (method, fullPath, body) => {
68 state.calls.push({ method, path: fullPath, body: copy(body) });
69 assert.ok(fullPath.startsWith(base + '/'), 'API must stay in the configured repository');
70 const path = fullPath.slice(base.length);
71 if (method === 'GET' && path.startsWith('/git/ref/')) {
72 const ref = path.slice('/git/ref/'.length);
73 const sha = ref === 'heads/main' ? state.main : state.refs.get(ref);
74 return sha ? { object: { sha } } : notFound();
75 }
76 if (method === 'GET' && path.startsWith('/git/commits/')) {
77 const sha = path.slice('/git/commits/'.length);
78 return { sha, message: git(['show', '-s', '--format=%B', sha]), tree: { sha: git(['rev-parse', `${sha}^{tree}`]) },
79 parents: git(['show', '-s', '--format=%P', sha]).split(' ').filter(Boolean).map(parent => ({ sha: parent })) };
80 }
81 if (method === 'GET' && path.startsWith('/compare/')) {
82 const [from, to] = path.slice('/compare/'.length).split('...');
83 const files = git(['diff', '--name-status', from, to]).split('\n').filter(Boolean).map(line => {
84 const [status, filename] = line.split('\t');
85 return { status: status === 'M' ? 'modified' : 'added', filename };
86 });
87 return { status: 'ahead', ahead_by: Number(git(['rev-list', '--count', `${from}..${to}`])), files };
88 }
89 if (method === 'GET' && path.startsWith('/contents/')) {
90 const [filename, sha] = path.slice('/contents/'.length).split('?ref=');
91 const content = execFileSync('git', ['show', `${sha}:${filename}`], { cwd: root, env: environment });
92 return { type: 'file', encoding: 'base64', content: content.toString('base64') };
93 }
94 if (method === 'GET' && path === '/git/matching-refs/tags/v') return [];
95 if (method === 'GET' && path.startsWith('/releases?')) {
96 const query = new URL(path, 'https://api.example.invalid').searchParams;
97 const page = Number(query.get('page') || 1);
98 const size = Number(query.get('per_page') || 30);
99 const releases = [...state.otherReleases, ...(state.release ? [state.release] : [])];
100 return copy(releases.slice((page - 1) * size, page * size));
101 }
102 if (method === 'POST' && path === '/git/trees') return { sha: await tree(body.base_tree, body.tree) };
103 if (method === 'POST' && path === '/git/commits') {
104 return { sha: git(['commit-tree', body.tree, '-p', body.parents[0]], { input: body.message }) };
105 }
106 if (method === 'POST' && path === '/git/refs') {
107 state.refs.set(body.ref.replace('refs/', ''), body.sha);
108 return { object: { sha: body.sha } };
109 }
110 // GitHub's tag lookup exposes published Releases only, even when this
111 // token can list private drafts. Resume logic must use the list endpoint.
112 if (method === 'GET' && path.startsWith('/releases/tags/')) {
113 const tag = decodeURIComponent(path.slice('/releases/tags/'.length));
114 const found = [...state.otherReleases, ...(state.release ? [state.release] : [])]
115 .find(release => !release.draft && release.tag_name === tag);
116 return found ? copy(found) : notFound();
117 }
118 if (method === 'POST' && path === '/releases/generate-notes') return { body: 'Fixture release notes' };
119 if (method === 'POST' && path === '/releases') {
120 if (state.release) state.otherReleases.push(copy(state.release));
121 const id = state.nextReleaseId++;
122 state.release = { ...body, id, html_url: `https://example.invalid/release/${id}` };
123 state.assets = [];
124 return copy(state.release);
125 }
126 if (method === 'GET' && path === `/releases/${state.release?.id}/assets?per_page=100`) return copy(state.assets);
127 if (method === 'GET' && path === `/releases/${state.release?.id}`) return copy(state.release);
128 if (method === 'DELETE' && path.startsWith('/releases/assets/')) {
129 state.assets = state.assets.filter(asset => asset.id !== Number(path.split('/').at(-1)));
130 return null;
131 }
132 if (method === 'PATCH' && path === `/releases/${state.release?.id}`) {
133 Object.assign(state.release, body);
134 return copy(state.release);
135 }
136 throw new Error(`Unexpected fake API request: ${method} ${path}`);
137 };
138 const promote = async candidate => {
139 state.promotions.push(copy(candidate));
140 state.main = candidate.commitSha;
141 state.refs.set(`tags/v${candidate.version}`, candidate.commitSha);
142 };
143 const upload = async (_repository, _id, file) => {
144 state.uploads.push(file.name);
145 state.assets.push({ id: state.assets.length + 1, name: file.name, state: 'uploaded', size: file.size, digest: file.digest });
146 };
147 const candidate = () => prepareRelease({ api, root, ...context });
148 return { root, git, tree, api, context, state, promote, upload, candidate };
149}
150
151async function uploadFiles(root, version) {
152 const directory = join(root, 'publish');
153 await mkdir(directory);
154 const names = [`Cage-${version}-macos-arm64.dmg`, `Cage-${version}-windows-amd64-setup.exe`, `Cage-${version}-linux-amd64.deb`];
155 for (const name of names) await writeFile(join(directory, name), `fixture ${name}`);
156 await writeFile(join(directory, 'SHA256SUMS'), names.map(name => `${digest(`fixture ${name}`)} ${name}\n`).join(''));
157 return releaseFiles(directory);
158}
159
160function publish(fixture, candidate, files, overrides = {}) {
161 const { api, root, promote, upload } = fixture;
162 return publishRelease({ api, root, promote, upload, ...candidate, files, ...overrides });
163}
164
165function published(fixture, candidate, files, runId = candidate.runId) {
166 fixture.state.main = candidate.commitSha;
167 fixture.state.refs.set(`tags/v${candidate.version}`, candidate.commitSha);
168 fixture.state.release = { id: 42, tag_name: `v${candidate.version}`, draft: false,
169 body: `<!-- cage-release-run:${runId}; commit:${candidate.commitSha} -->` };
170 fixture.state.assets = files.map((file, index) => ({ id: index + 1, name: file.name, state: 'uploaded', size: file.size, digest: file.digest }));
171}
172
173test('release context rejects ordinary pushes, forks and non-main dispatches', () => {
174 const env = { GITHUB_ACTIONS: 'true', GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/main',
175 GITHUB_REPOSITORY: repository, GITHUB_SHA: 'a'.repeat(40), GITHUB_RUN_ID: '1042' };
176 const event = { repository: { default_branch: 'main' }, inputs: { bump: 'prerelease' } };
177 assert.equal(workflowContext(env, event).sourceSha, env.GITHUB_SHA);
178 for (const change of [{ GITHUB_EVENT_NAME: 'push' }, { GITHUB_REPOSITORY: 'someone/fork' }, { GITHUB_REF: 'refs/heads/feature' }, { GITHUB_ACTIONS: 'false' }, { GITHUB_SHA: 'main' }]) {
179 assert.throws(() => workflowContext({ ...env, ...change }, event));
180 }
181});
182
183test('prepare leaves the working version unchanged and reuses the same run candidate', async t => {
184 const f = await repositoryFixture(t);
185 const before = await readFile(join(f.root, 'VERSION'), 'utf8');
186 const first = await f.candidate();
187 assert.notEqual(first.version, currentVersion);
188 assert.equal(await readFile(join(f.root, 'VERSION'), 'utf8'), before);
189 assert.equal(f.git(['status', '--porcelain']), '');
190 assert.equal(f.state.main, f.context.sourceSha);
191 const second = await f.candidate();
192 assert.equal(second.commitSha, first.commitSha);
193 assert.equal(second.version, first.version);
194 assert.equal(f.state.calls.filter(call => call.method === 'POST' && call.path.endsWith('/git/commits')).length, 1);
195});
196
197test('exact requested version is retained on preparation and resume, with reserved versions rejected', async t => {
198 const f = await repositoryFixture(t);
199 f.context.requestedVersion = '99.1.0-rc.1';
200 const first = await f.candidate();
201 assert.equal(first.version, '99.1.0-rc.1');
202 assert.equal((await f.candidate()).commitSha, first.commitSha);
203 f.context.requestedVersion = '99.1.0-rc.2';
204 await assert.rejects(f.candidate(), /another requested version/);
205 const reserved = await repositoryFixture(t);
206 reserved.context.requestedVersion = '99.1.0-rc.1';
207 reserved.state.otherReleases.push({ tag_name: 'v99.1.0-rc.1', draft: true });
208 await assert.rejects(reserved.candidate(), /reserved/);
209 assert.equal(reserved.state.calls.some(call => call.method !== 'GET'), false);
210});
211
212test('custom release notes come from the immutable source and are published with RC status', async t => {
213 const f = await repositoryFixture(t);
214 f.context.notesPath = 'docs/releases/v99.1.0-rc.1.md';
215 await mkdir(join(f.root, 'docs/releases'), { recursive: true });
216 await writeFile(join(f.root, f.context.notesPath), '# 本轮更新\n\n功能与已验证范围。\n');
217 f.git(['add', f.context.notesPath]);
218 f.git(['commit', '--quiet', '-m', 'Public release notes']);
219 f.context.sourceSha = f.state.main = f.git(['rev-parse', 'HEAD']);
220 f.context.requestedVersion = '99.1.0-rc.1';
221 const candidate = await f.candidate();
222 await writeFile(join(f.root, f.context.notesPath), 'Concurrent local draft, must not be published.');
223 const files = await uploadFiles(f.root, candidate.version);
224 const release = await publish(f, candidate, files);
225 assert.equal(release.prerelease, true);
226 assert.ok(release.body.endsWith('# 本轮更新\n\n功能与已验证范围。'));
227 assert.equal(f.state.calls.some(call => call.path.endsWith('/generate-notes')), false);
228 for (const notesPath of ['../private.md', 'docs/../private.md', '/docs/notes.md', 'docs/notes.txt']) {
229 await assert.rejects(releaseNotes(f.root, { ...candidate, notesPath }), /committed Markdown/);
230 }
231});
232
233test('main movement prevents candidate creation and later publication', async t => {
234 const f = await repositoryFixture(t);
235 f.state.main = 'b'.repeat(40);
236 await assert.rejects(f.candidate(), /Main advanced/);
237 assert.equal(f.state.calls.some(call => call.method !== 'GET'), false);
238 f.state.main = f.context.sourceSha;
239 const candidate = await f.candidate();
240 const files = await uploadFiles(f.root, candidate.version);
241 f.state.main = 'b'.repeat(40);
242 await assert.rejects(publish(f, candidate, files), /Main changed/);
243 assert.equal(f.state.promotions.length, 0);
244 assert.equal(f.state.uploads.length, 0);
245 assert.equal(f.state.release, null);
246});
247
248test('candidate verification rejects extra files and dependency edits hidden in version files', async t => {
249 for (const kind of ['extra file', 'dependency change']) await t.test(kind, async t => {
250 const f = await repositoryFixture(t);
251 const candidate = await f.candidate();
252 const expected = await expectedFiles(f.root, candidate.sourceSha, candidate.version);
253 const changed = new Map(expected);
254 if (kind === 'extra file') changed.set('unexpected-script.sh', 'echo unauthorized\n');
255 else changed.set('ui/package.json', changed.get('ui/package.json').replace('"fixture": "1.0.0"', '"fixture": "9.9.9"'));
256 const treeSha = await f.tree(f.git(['rev-parse', `${candidate.sourceSha}^{tree}`]), [...changed].map(([path, content]) => ({ path, content })));
257 const message = f.git(['show', '-s', '--format=%B', candidate.commitSha]);
258 const commitSha = f.git(['commit-tree', treeSha, '-p', candidate.sourceSha], { input: message });
259 await assert.rejects(verifyCandidate(f.api, { ...candidate, commitSha }, expected), /only the five|unexpected change/);
260 });
261});
262
263async function artifactFixture(t) {
264 const root = await temporary(t);
265 const commitSha = 'a'.repeat(40);
266 const packages = {
267 macos: { [`Cage-${currentVersion}-macos-arm64.dmg`]: 'mac installer', [`mihomo-${macCoreVersion}-source.tar.gz`]: 'same core source', [`cage-macos-guest-${currentVersion}-source.tar.gz`]: 'mac guest corresponding source' },
268 windows: { [`Cage-${currentVersion}-windows-amd64-setup.exe`]: 'windows installer', [`mihomo-${windowsDependencies.mihomo.version}-source.tar.gz`]: 'same core source', [`qemu-${windowsDependencies.qemu.version}-windows-full-source.zip`]: 'complete qemu source' },
269 linux: { [`Cage-${currentVersion}-linux-amd64.deb`]: 'linux installer', [linuxDependencies.mihomoSource.file]: 'same core source' },
270 };
271 for (const [platform, entries] of Object.entries(packages)) {
272 const directory = join(root, platform);
273 await mkdir(directory);
274 for (const [name, content] of Object.entries(entries)) await writeFile(join(directory, name), content);
275 await writeFile(join(directory, 'SHA256SUMS'), Object.entries(entries).map(([name, content]) => `${digest(content)} ${name}\n`).join(''));
276 await writeFile(join(directory, 'build-metadata.json'), JSON.stringify({ schema: 1, platform, version: currentVersion, commitSha }));
277 }
278 return { directory: root, output: join(root, 'assembled'), version: currentVersion, commitSha };
279}
280
281test('all three platform identities are required before any assets are assembled', async t => {
282 for (const kind of ['missing metadata', 'different commit', 'different version']) await t.test(kind, async t => {
283 const f = await artifactFixture(t);
284 const path = join(f.directory, 'linux', 'build-metadata.json');
285 if (kind === 'missing metadata') await rm(path);
286 else {
287 const metadata = JSON.parse(await readFile(path, 'utf8'));
288 if (kind === 'different commit') metadata.commitSha = 'b'.repeat(40);
289 else metadata.version = '99.0.0';
290 await writeFile(path, JSON.stringify(metadata));
291 }
292 let assembled = false;
293 await assert.rejects(assembleRelease({ ...f, assemble: async () => { assembled = true; throw new Error('must not assemble'); } }));
294 assert.equal(assembled, false);
295 });
296});
297
298test('assembly accepts matching platforms but excludes metadata from public assets', async t => {
299 const f = await artifactFixture(t);
300 const result = await assembleRelease(f);
301 assert.ok(result.assets.includes(`Cage-${currentVersion}-linux-amd64.deb`));
302 assert.ok(!result.assets.some(name => name.includes('metadata')));
303 assert.ok((await releaseFiles(f.output)).length > 3);
304});
305
306test('an installer for an unsupported version cannot enter the public release', async t => {
307 const f = await artifactFixture(t);
308 const wrong = 'Cage-99999.0.0-linux-amd64.deb';
309 const path = join(f.directory, 'linux');
310 await writeFile(join(path, wrong), 'wrong version');
311 const manifest = await readFile(join(path, 'SHA256SUMS'), 'utf8');
312 await writeFile(join(path, 'SHA256SUMS'), manifest + `${digest('wrong version')} ${wrong}\n`);
313 await assert.rejects(assembleRelease(f), /Unsupported asset or version/);
314});
315
316test('a public release owned by another run is never overwritten', async t => {
317 const f = await repositoryFixture(t);
318 const candidate = await f.candidate();
319 const files = await uploadFiles(f.root, candidate.version);
320 published(f, candidate, files, '9999');
321 const before = copy(f.state.release);
322 await assert.rejects(publish(f, candidate, files), /another operation/);
323 assert.deepEqual(f.state.release, before);
324 assert.equal(f.state.promotions.length, 0);
325 assert.equal(f.state.uploads.length, 0);
326});
327
328test('an upload failure retains a private draft and never publishes partial assets', async t => {
329 const f = await repositoryFixture(t);
330 const candidate = await f.candidate();
331 const files = await uploadFiles(f.root, candidate.version);
332 let attempts = 0;
333 await assert.rejects(publish(f, candidate, files, { upload: async (...args) => {
334 if (++attempts === 2) throw new Error('fixture upload failure');
335 await f.upload(...args);
336 } }), /fixture upload failure/);
337 assert.equal(f.state.release.draft, true);
338 assert.equal(f.state.assets.length, 1);
339 assert.equal(f.state.calls.some(call => call.method === 'PATCH'), false);
340});
341
342test('retry after an interrupted upload resumes the same private draft, including on the second page', async t => {
343 for (const precedingReleases of [0, 100]) await t.test(precedingReleases ? 'draft on page two' : 'draft on page one', async t => {
344 const f = await repositoryFixture(t);
345 const candidate = await f.candidate();
346 const files = await uploadFiles(f.root, candidate.version);
347 let attempts = 0;
348 await assert.rejects(publish(f, candidate, files, { upload: async (...args) => {
349 if (++attempts === 2) throw new Error('fixture interrupted upload');
350 await f.upload(...args);
351 } }), /fixture interrupted upload/);
352 const draftId = f.state.release.id;
353 assert.equal(f.state.release.draft, true);
354 assert.equal(f.state.assets.length, 1);
355 const completedAsset = f.state.assets[0].name;
356 await assert.rejects(f.api('GET', `${base}/releases/tags/v${candidate.version}`), { status: 404 });
357 f.state.otherReleases = Array.from({ length: precedingReleases }, (_, i) => ({
358 id: 1000 + i, tag_name: `v0.0.0-fixture.${i}`, draft: false, body: 'Unrelated older release',
359 }));
360 const resumed = await publish(f, candidate, files);
361 assert.equal(resumed.id, draftId);
362 assert.equal(resumed.draft, false);
363 assert.equal(f.state.calls.filter(call => call.method === 'POST' && call.path === `${base}/releases`).length, 1);
364 assert.equal(f.state.uploads.filter(name => name === completedAsset).length, 1);
365 assert.deepEqual(new Set(f.state.assets.map(asset => asset.name)), new Set(files.map(file => file.name)));
366 });
367});
368
369test('multiple drafts reserving the same tag are left untouched', async t => {
370 const f = await repositoryFixture(t);
371 const candidate = await f.candidate();
372 const files = await uploadFiles(f.root, candidate.version);
373 published(f, candidate, files);
374 f.state.release.draft = true;
375 f.state.otherReleases.push({ ...copy(f.state.release), id: 43 });
376 const before = copy([f.state.release, ...f.state.otherReleases]);
377 f.state.calls.length = 0;
378 await assert.rejects(publish(f, candidate, files), /Multiple Releases reserve/);
379 assert.deepEqual([f.state.release, ...f.state.otherReleases], before);
380 assert.equal(f.state.calls.some(call => call.method !== 'GET'), false);
381 assert.equal(f.state.promotions.length, 0);
382 assert.equal(f.state.uploads.length, 0);
383});
384
385test('missing or incorrect server digests prevent publication even after successful upload requests', async t => {
386 for (const receivedDigest of [undefined, `sha256:${'0'.repeat(64)}`]) await t.test(receivedDigest ? 'wrong digest' : 'missing digest', async t => {
387 const f = await repositoryFixture(t);
388 const candidate = await f.candidate();
389 const files = await uploadFiles(f.root, candidate.version);
390 await assert.rejects(publish(f, candidate, files, { upload: async (...args) => {
391 await f.upload(...args);
392 f.state.assets.at(-1).digest = receivedDigest;
393 } }), /uploaded assets do not match/);
394 assert.equal(f.state.release.draft, true);
395 assert.equal(f.state.calls.some(call => call.method === 'PATCH'), false);
396 });
397});
398
399test('retrying this run after publication checks identical assets without uploading or changing refs', async t => {
400 const f = await repositoryFixture(t);
401 const candidate = await f.candidate();
402 const files = await uploadFiles(f.root, candidate.version);
403 const first = await publish(f, candidate, files);
404 assert.equal(first.draft, false);
405 const uploaded = [...f.state.uploads];
406 const promotions = f.state.promotions.length;
407 const mutations = f.state.calls.filter(call => call.method !== 'GET').length;
408 const again = await publish(f, candidate, files);
409 assert.equal(again.id, first.id);
410 assert.deepEqual(f.state.uploads, uploaded);
411 assert.equal(f.state.promotions.length, promotions);
412 assert.equal(f.state.calls.filter(call => call.method !== 'GET').length, mutations);
413});