跳到主要内容

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

浏览文件

proxy-chain-smoke.mjs

136 行 · 8.5 KB历史下载
1// Real authenticated workbench, bundled Mihomo and local HTTP CONNECT servers.
2// Uses a new private profile. Never touches the user's Cage, VM or subscriptions.
3import assert from 'node:assert/strict';
4import fs from 'node:fs/promises';
5import http from 'node:http';
6import net from 'node:net';
7import path from 'node:path';
8import { spawn, execFile } from 'node:child_process';
9import { promisify } from 'node:util';
10import { createRequire } from 'node:module';
11const require=createRequire(import.meta.url);
12const {chromium}=require(process.env.CAGE_PLAYWRIGHT_MODULE || 'playwright');
13const run=promisify(execFile);
14const root=path.resolve(import.meta.dirname,'../..');
15const executable=process.env.CAGE_CHAIN_QA_EXECUTABLE || path.join(root,'_output/proxy-chain-20261105/bin/cage');
16const output=path.join(root,'docs/test-reports/2026-11-05-proxy-chain');
17await fs.mkdir(output,{recursive:true});
18const profile=await fs.mkdtemp('/private/tmp/cage-chain-qa-');
19const env={...process.env,CLAUDE_CAGE_CONFIG:path.join(profile,'config.json')};
20await run(executable,['init'],{env});
21const sockets=new Set();
22const listen=server=>new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
23async function upstream(){
24 const destinations=[];
25 const server=http.createServer();
26 server.on('connect',(req,client,head)=>{
27 destinations.push(req.url);
28 const destination=new URL(`http://${req.url}`);
29 const remote=net.connect(Number(destination.port),destination.hostname,()=>{
30 client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
31 if(head.length)remote.write(head);
32 remote.pipe(client);client.pipe(remote);
33 });
34 for(const socket of [client,remote]){sockets.add(socket);socket.on('close',()=>sockets.delete(socket));socket.on('error',()=>{client.destroy();remote.destroy();});}
35 });
36 await listen(server);
37 return {server,port:server.address().port,destinations};
38}
39const entry=await upstream(),exit=await upstream();
40let targetRequests=0;
41const target=http.createServer((_req,res)=>{targetRequests++;res.end('residential-exit-verified');});
42await listen(target);
43const reserve=net.createServer();await listen(reserve);const port=reserve.address().port;await new Promise(r=>reserve.close(r));
44const log=await fs.open(path.join(profile,'server.log'),'w',0o600);
45const server=spawn(executable,['serve'],{env,stdio:['ignore',log.fd,log.fd]});
46let browser;
47const errors=[];
48try{
49 let control;
50 for(let i=0;i<100;i++){try{control=JSON.parse(await fs.readFile(path.join(profile,'control.json')));break;}catch{await new Promise(r=>setTimeout(r,100));}}
51 assert.ok(control,'private service did not start');
52 const origin=`http://localhost:${control.port}`;
53 assert.equal((await fetch(origin+'/api/proxy')).status,401);
54 const launch=await fetch(origin+'/api/launch',{method:'POST',headers:{Origin:origin,'Content-Type':'application/json'},body:JSON.stringify({token:control.token})}).then(r=>r.json());
55 browser=await chromium.launch({headless:true,executablePath:process.env.CAGE_TEST_BROWSER_PATH});
56 const page=await browser.newPage({viewport:{width:1280,height:1000}});
57 page.on('pageerror',e=>errors.push(e.message));
58 await page.goto(launch.url);
59 await page.getByLabel('用户名',{exact:true}).fill('Proxy Chain QA');
60 await page.getByLabel('设置密码',{exact:true}).fill('isolated-chain-test-password');
61 await page.getByLabel('确认密码',{exact:true}).fill('isolated-chain-test-password');
62 await page.getByRole('button',{name:'创建本地账户',exact:true}).click();
63 const enter=async()=>{
64 await page.getByRole('button',{name:/^设置/}).click();
65 await page.getByRole('button',{name:'网络与代理',exact:true}).click();
66 await page.getByRole('heading',{name:'内置代理',exact:true}).waitFor();
67 };
68 await enter();
69 const idle=()=>page.waitForFunction(()=>!document.querySelector('.proxy-progress'));
70 for(const [name,node,upstreamPort] of [['中转来源','本地中转',entry.port],['住宅来源','住宅出口',exit.port]]){
71 await page.getByRole('tab',{name:'订阅',exact:true}).click();
72 await page.getByRole('button',{name:'添加来源',exact:true}).click();
73 await page.getByRole('button',{name:'本地 YAML',exact:true}).click();
74 await page.getByLabel('来源名称',{exact:true}).fill(name);
75 await page.getByLabel('节点 YAML',{exact:true}).fill(`proxies:\n - {name: ${node}, type: http, server: 127.0.0.1, port: ${upstreamPort}}\n`);
76 await page.getByRole('button',{name:'导入并验证',exact:true}).click();await idle();
77 await page.getByText(name,{exact:true}).waitFor();
78 }
79 await page.getByRole('tab',{name:'诊断',exact:true}).click();
80 await page.getByLabel('独立代理端口',{exact:true}).fill(String(port));
81 await page.getByRole('tab',{name:'节点',exact:true}).click();
82 await page.getByRole('button',{name:'链式代理',exact:true}).click();
83 const choose=async(label,name)=>{
84 await page.getByRole('combobox',{name:label,exact:true}).click();
85 await page.getByRole('option',{name,exact:true}).click();
86 };
87 await choose('最终出口','住宅出口');
88 await choose('中转节点','本地中转');
89 await page.getByRole('button',{name:'应用代理',exact:true}).click();await idle();
90 await page.getByText('当前配置已应用',{exact:true}).waitFor();
91 const state=()=>page.evaluate(()=>fetch('/api/proxy').then(r=>r.json()));
92 const applied=await state();assert.equal(applied.active,true);assert.equal(applied.running,true);assert.equal(applied.route.length,2);
93 const stored=JSON.parse(await fs.readFile(path.join(profile,'proxy/sources.json')));
94 const curlConfig=path.join(profile,'curl.conf');
95 await fs.writeFile(curlConfig,`proxy = "socks5h://cage:${stored.auth}@127.0.0.1:${stored.port}"\n`,{mode:0o600});
96 const through=()=>run('curl',['--config',curlConfig,'--noproxy','','--fail','--silent','--show-error','--max-time','6',`http://127.0.0.1:${target.address().port}/probe`]);
97 assert.equal((await through()).stdout,'residential-exit-verified');
98 assert.deepEqual(entry.destinations,[`127.0.0.1:${exit.port}`]);
99 assert.deepEqual(exit.destinations,[`127.0.0.1:${target.address().port}`]);
100 await page.reload();await enter();
101 assert.equal((await state()).route.join(','),applied.route.join(','));
102 assert.match(await page.getByRole('combobox',{name:'中转节点',exact:true}).innerText(),/本地中转/);
103 await page.locator('.settings-content').evaluate(el=>el.scrollTop=0);
104 await page.waitForFunction(()=>[...document.querySelectorAll('.proxy-route-hop')].every(el=>getComputedStyle(el).opacity==='1'));
105 await page.screenshot({path:path.join(output,'real-chain.png')});
106 // Single-node explicitly bypasses the intermediate, without editing its source.
107 const entryCount=entry.destinations.length;
108 await page.getByRole('button',{name:'单节点',exact:true}).click();
109 await page.getByRole('button',{name:'应用代理',exact:true}).click();await idle();
110 await page.getByText('当前配置已应用',{exact:true}).waitFor();
111 assert.equal((await through()).stdout,'residential-exit-verified');
112 assert.equal(entry.destinations.length,entryCount);
113 // Re-enable the chain, then break its exit: no direct target request may occur.
114 await page.getByRole('button',{name:'链式代理',exact:true}).click();await choose('中转节点','本地中转');
115 await page.getByRole('button',{name:'应用代理',exact:true}).click();await idle();
116 await page.getByText('当前配置已应用',{exact:true}).waitFor();
117 for(const socket of sockets)socket.destroy();
118 await new Promise(resolve=>exit.server.close(resolve));
119 const beforeFailure=targetRequests;
120 await assert.rejects(through());
121 assert.equal(targetRequests,beforeFailure,'broken chain fell back to target directly');
122 const final=await state();assert.deepEqual(final.route,applied.route);
123 assert.deepEqual(errors,[]);
124 const result={passed:true,realWorkbench:true,realMihomo:true,crossSourceChain:true,entryReachedExit:entry.destinations.length>0,exitReachedTarget:true,reloadPersistence:true,singleNodeBypassesTransit:true,brokenExitHasNoDirectFallback:true,targetRequests,browserErrors:errors,guestVMTested:false,platform:process.platform};
125 await fs.writeFile(path.join(output,'result.json'),JSON.stringify(result,null,2));
126 console.log(JSON.stringify(result));
127}catch(e){await fs.writeFile(path.join(output,'failure.txt'),String(e));throw e;}
128finally{
129 if(browser)await browser.close();
130 await run(executable,['proxy-stop'],{env}).catch(()=>{});
131 server.kill('SIGTERM');await log.close();
132 for(const socket of sockets)socket.destroy();
133 entry.server.closeAllConnections();exit.server.closeAllConnections();target.closeAllConnections();
134 entry.server.close();exit.server.close();target.close();
135 console.log('Private QA profile retained at '+profile);
136}