跳到主要内容

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

浏览文件

test-smoke.mjs

157 行 · 8.8 KB历史下载
1#!/usr/bin/env node
2// Run under a real Linux display or xvfb-run + dbus-run-session.
3import { mkdtemp, mkdir, readFile, rm, stat } from 'node:fs/promises';
4import { tmpdir } from 'node:os';
5import { dirname, isAbsolute, join, resolve } from 'node:path';
6import { randomBytes } from 'node:crypto';
7import { spawn } from 'node:child_process';
8
9const [nativeArgument, outputArgument] = process.argv.slice(2);
10if (!nativeArgument || !outputArgument || process.argv.length !== 4) {
11 console.error('Usage: test-smoke.mjs /path/to/cage-desktop /absolute/report.json');
12 process.exit(2);
13}
14const native = resolve(nativeArgument);
15const backend = join(dirname(native), 'cage');
16const output = resolve(outputArgument);
17const root = await mkdtemp(join(tmpdir(), 'cage-linux-smoke-'));
18// Cage places the default workspace beside the profile; both stay in this
19// fixture directory so cleanup also removes the temporary workspace.
20// Keep the selected gateway alive for the two native storage phases. The
21// native windows register their own owners in addition to this test process.
22const env = { ...process.env, CLAUDE_CAGE_CONFIG: join(root, 'profile', 'config.json'), CAGE_DESKTOP_OWNER_PID: String(process.pid) };
23let clean = false;
24let result = 1;
25
26function execute(executable, args, timeout = 190000) {
27 return new Promise((resolvePromise, reject) => {
28 const child = spawn(executable, args, { env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
29 let stdout = '', stderr = '', overflow = false;
30 const stopGroup = () => {
31 try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ }
32 };
33 const timer = setTimeout(stopGroup, timeout);
34 child.stdout.on('data', data => {
35 stdout += data;
36 if (stdout.length > 65536) { overflow = true; stopGroup(); }
37 });
38 child.stderr.on('data', data => {
39 stderr = (stderr + data).slice(-8192);
40 if (executable === native && args[0] === '--smoke-test') process.stderr.write(data);
41 });
42 child.on('error', error => { clearTimeout(timer); reject(error); });
43 // A failed native process can leave WebKit children holding its pipes open.
44 // The controller deliberately detaches into its own group and is cleaned
45 // through prepare-update below, never by this process-group signal.
46 child.on('exit', (code, signal) => { if (code !== 0 || signal) stopGroup(); });
47 child.on('close', (code, signal) => {
48 clearTimeout(timer);
49 if (overflow) reject(new Error('Backend response exceeded the output limit.'));
50 else resolvePromise({ code, signal, stdout, stderr });
51 });
52 });
53}
54function parseBackend(run) {
55 // Do not include stdout in errors: desktop's URL carries a session token.
56 let data;
57 try { data = JSON.parse(run.stdout); } catch { throw new Error('Backend returned invalid JSON.'); }
58 if (run.code !== 0) throw new Error('Backend operation failed; inspect the isolated control.log.');
59 return data;
60}
61
62try {
63 if (!isAbsolute(output)) throw new Error('Report path must be absolute.');
64 await mkdir(join(root, 'profile'), { mode: 0o700 });
65 await mkdir(dirname(output), { recursive: true });
66 await rm(output, { force: true });
67 await rm(output + '.png', { force: true });
68 const policy = await execute(native, ['--self-test'], 30000);
69 if (policy.code !== 0) throw new Error('Native origin policy tests failed.');
70 const entry = parseBackend(await execute(backend, ['desktop', '--json']));
71 if (entry.status !== 'ready') throw new Error('Isolated backend was not ready.');
72 const url = new URL(entry.url);
73 if (url.protocol !== 'http:' || url.hostname !== 'localhost' || !url.hash || url.username || url.password)
74 throw new Error('Backend returned an invalid loopback entry.');
75 const authenticate = await fetch(url.origin + '/api/session', {
76 method: 'POST', redirect: 'error',
77 headers: { 'Origin': url.origin, 'Content-Type': 'application/json' },
78 body: JSON.stringify({ token: url.hash.slice(1) }),
79 });
80 if (!authenticate.ok) throw new Error('Session authentication failed.');
81 const cookie = authenticate.headers.get('set-cookie')?.split(';')[0];
82 if (!cookie) throw new Error('Authenticated response did not create a session cookie.');
83 async function api(path, body, generation) {
84 const headers = { Origin: url.origin, Cookie: cookie };
85 if (body !== undefined) headers['Content-Type'] = 'application/json';
86 if (generation) headers['X-Cage-Connection'] = generation;
87 const response = await fetch(url.origin + '/api/' + path, {
88 method: body === undefined ? 'GET' : 'POST', redirect: 'error', headers,
89 body: body === undefined ? undefined : JSON.stringify(body),
90 });
91 if (!response.ok) throw new Error(`Isolated smoke API ${path} failed with ${response.status}.`);
92 return response.json();
93 }
94 let current = await api('client/context');
95 if (!current.desktop_gateway || current.mode !== 'none') throw new Error('A fresh full Cage must start at the environment picker.');
96 const idle = await api('client/local-status');
97 if (!idle.known || idle.service_running || idle.running) throw new Error('The desktop picker started a local workload.');
98 const original = current.connection_id;
99 const pending = await api('client/candidate', { connection_id: original, mode: 'local' });
100 const deadline = Date.now() + 30000;
101 while (true) {
102 current = await api('client/context');
103 if (current.connection_id !== original || current.candidate?.id !== pending.id) throw new Error('The local candidate lost its original desktop view.');
104 if (current.candidate.connection.state === 'connected') break;
105 if (current.candidate.connection.state === 'failed' || Date.now() > deadline) throw new Error('Could not open the local test workbench.');
106 await new Promise((r) => setTimeout(r, 100));
107 }
108 current = await api('client/commit', { connection_id: original, candidate_id: pending.id, local_action: 'auto' });
109 if (current.mode !== 'local' || current.connection_id === original) throw new Error('Local workbench generation was not selected.');
110 const password = randomBytes(24).toString('base64url');
111 const account = await api('account/create', { username: 'Linux Smoke', password, confirm_password: password }, current.connection_id);
112 if (!account.unlocked) throw new Error('Could not prepare the isolated unlocked test account.');
113 env.CAGE_SMOKE_STORAGE_MARKER = randomBytes(24).toString('hex');
114 for (const phase of ['seed', 'verify']) {
115 env.CAGE_SMOKE_STORAGE_PHASE = phase;
116 await rm(output, { force: true });
117 const nativeRun = await execute(native, ['--smoke-test', output], 150000);
118 if (nativeRun.code !== 0) throw new Error(`Native WebKit workbench ${phase} test failed.`);
119 const pass = JSON.parse(await readFile(output, 'utf8'));
120 if (pass.success !== true || pass.storageMarkerMatched !== true) throw new Error(`Native storage ${phase} evidence is incomplete.`);
121 }
122 const evidence = JSON.parse(await readFile(output, 'utf8'));
123 for (const key of ['success', 'nativeBridgeReady', 'authenticated', 'accountUnlocked', 'workbenchRendered', 'workbenchReadyAcknowledged', 'statusReceived', 'settingsReceived', 'unauthenticatedBridgeDenied', 'localStoragePersisted']) {
124 if (evidence[key] !== true) throw new Error(`Native smoke report lacks ${key}.`);
125 }
126 if ((await stat(output + '.png')).size < 1024) throw new Error('Native screenshot is missing or empty.');
127 for (const directory of ['webkit', 'webkit/data', 'webkit/cache']) {
128 if ((await stat(join(root, 'profile', directory))).mode & 0o077) throw new Error('WebKit profile storage is not private.');
129 }
130 result = 0;
131 console.log(JSON.stringify({ success: true, report: output, screenshot: output + '.png', version: evidence.version }));
132} catch (error) {
133 console.error(error.message);
134} finally {
135 try {
136 const cleanupRun = await execute(backend, ['prepare-update', '--json']);
137 if (cleanupRun.code !== 0) {
138 // prepare-update returns only status/message. Never log desktop's
139 // entry JSON or arbitrary stdout, which can contain a session URL.
140 let message = '';
141 try {
142 const response = JSON.parse(cleanupRun.stdout);
143 if (typeof response.message === 'string') message = response.message.slice(0, 500);
144 } catch { /* Keep malformed or non-JSON output private. */ }
145 console.error(`Cleanup prepare-update failed (exit ${cleanupRun.code}, signal ${cleanupRun.signal || 'none'}): ${message}`);
146 }
147 const stopped = parseBackend(cleanupRun);
148 clean = stopped.status === 'prepared';
149 if (!clean) console.error(`Cleanup prepare-update returned ${stopped.status || 'unknown status'}.`);
150 } catch (error) {
151 console.error(`Cleanup could not confirm controller exit: ${error.message}`);
152 // Preserve the fixture until a remaining controller can be stopped.
153 }
154 if (clean) await rm(root, { recursive: true, force: true });
155 else { console.error(`Cleanup incomplete; isolated profile retained at ${root}`); result = 1; }
156}
157process.exitCode = result;