跳到主要内容

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

浏览文件

vault-controller-smoke.mjs

84 行 · 6.8 KB历史下载
1// Production controller and private CDP pipe, with a disposable local HTTPS site.
2// Only deployment paths, test certificate handling and the test CDP route differ.
3import assert from "node:assert/strict";
4import { spawn, execFileSync } from "node:child_process";
5import { once } from "node:events";
6import { randomBytes } from "node:crypto";
7import { cp, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
8import https from "node:https";
9import { tmpdir } from "node:os";
10import { join } from "node:path";
11import { setTimeout as delay } from "node:timers/promises";
12assert.ok(process.env.CAGE_TEST_BROWSER_PATH, "Set CAGE_TEST_BROWSER_PATH to Chromium");
13const dir = await realpath(await mkdtemp(join(tmpdir(), "cage-vault-controller-")));
14const token = randomBytes(32).toString("hex"), lease = randomBytes(32).toString("hex");
15execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(dir, "key.pem"), "-out", join(dir, "cert.pem"), "-days", "1", "-subj", "/CN=localhost"], { stdio: "ignore" });
16const site = https.createServer({ key: await readFile(join(dir,"key.pem")), cert: await readFile(join(dir,"cert.pem")) }, (req,res) => {
17 res.setHeader("Content-Type","text/html");
18 res.end('<title>Vault fixture</title><form onsubmit="event.preventDefault()"><label>Email<input id="user" autocomplete="username"></label><label>Password<input id="pass" type="password" autocomplete="current-password"></label><button>Sign in</button></form>');
19});
20await new Promise(resolve => site.listen(0, "127.0.0.1", resolve));
21const origin = `https://127.0.0.1:${site.address().port}`;
22let agent, control, stderr = "";
23async function waitFor(fn, label) {
24 for (let i=0;i<150;i++) { if (agent?.exitCode !== null) throw new Error("Controller exited: " + stderr.slice(-1000)); const result=await fn(); if(result) return result; await delay(50); }
25 throw new Error("Timed out: " + label);
26}
27async function api(path, input) {
28 const res=await fetch(control+path,{method:input===undefined?"GET":"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:input===undefined?undefined:JSON.stringify(input)});
29 assert.equal(res.status,200);
30 return res.json();
31}
32const vault = input => api("/vault",{lease,...input});
33async function evaluate(id, expression) {
34 const result=await api("/__vault-test",{id,method:"Runtime.evaluate",params:{expression,returnByValue:true}});
35 assert.equal(result.exceptionDetails, undefined);
36 return result.result.value;
37}
38try {
39 const sourceDir=new URL("../internal/cage/",import.meta.url);
40 for(const name of await readdir(sourceDir)) if ((name.startsWith("browser-")&&name.endsWith(".mjs"))||name==="native-input.mjs") await cp(new URL(name,sourceDir),join(dir,name));
41 await cp(new URL("split-extension",sourceDir),join(dir,"extension"),{recursive:true});
42 const original=await readFile(new URL("browser-agent.mjs",sourceDir),"utf8");
43 const marker='const input = JSON.parse(text || "{}");';
44 const adapted=original.replaceAll("/home/cage-browser",dir).replace("/etc/claude-cage/browser-control.json",join(dir,"control.json"))
45 .replace("/usr/local/lib/cage-split",join(dir,"extension"))
46 .replace('spawn("/usr/bin/chromium", flags',`spawn(${JSON.stringify(process.env.CAGE_TEST_BROWSER_PATH)}, flags`)
47 .replace('"--start-fullscreen",','"--headless=new", "--ignore-certificate-errors", "--disable-background-networking",')
48 .replace('server.listen(18500, "127.0.0.1");','server.listen(0,"127.0.0.1",()=>console.log("PORT="+server.address().port));')
49 .replace(marker,`${marker}\nif (req.url === "/__vault-test") { res.end(JSON.stringify(await cdp(input.method,input.params||{},await session(input.id)))); return; }`);
50 assert.notEqual(adapted, original);
51 await writeFile(join(dir,"browser-agent.mjs"),adapted);
52 await writeFile(join(dir,"control.json"),JSON.stringify({token,workspace:dir}));
53 await writeFile(join(dir,"homepage.json"),JSON.stringify({url:origin+"/login"}));
54 agent=spawn(process.execPath,[join(dir,"browser-agent.mjs")],{stdio:["ignore","pipe","pipe"]});
55 agent.stdout.on("data",chunk=>{const match=chunk.toString().match(/PORT=(\d+)/);if(match)control="http://127.0.0.1:"+match[1];});
56 agent.stderr.on("data",chunk=>{stderr=(stderr+chunk).slice(-3000);});
57 await waitFor(()=>control,"listener");
58 await waitFor(async()=> (await fetch(control+"/health",{headers:{Authorization:`Bearer ${token}`}})).ok,"ready");
59 const tab=(await api("/tabs")).active;
60 await waitFor(()=>evaluate(tab,"document.readyState === 'complete'"),"fixture");
61 const state=await vault({action:"status",tab});
62 assert.equal(state.origin,origin);assert.ok(state.document);
63 await evaluate(tab,"document.getElementById('user').value='[email protected]';document.getElementById('pass').value='controller-secret'");
64 const point=await evaluate(tab,"(()=>{const r=document.querySelector('button').getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()");
65 for(const type of ["mousePressed","mouseReleased"]) await api("/__vault-test",{id:tab,method:"Input.dispatchMouseEvent",params:{type,...point,button:"left",clickCount:1}});
66 const pending=await waitFor(async()=> (await vault({action:"status",tab})).candidates[0],"captured password");
67 assert.equal(pending.password,"controller-secret");assert.equal(pending.username,"[email protected]");
68 assert.ok(!JSON.stringify(await api("/tabs")).includes("controller-secret"));
69 assert.equal((await fetch(control+"/vault",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).status,401);
70 assert.equal((await fetch(control+"/vault",{method:"POST",headers:{Authorization:`Bearer ${token}`,Origin:origin,"Content-Type":"application/json"},body:"{}"})).status,403);
71 await evaluate(tab,"document.getElementById('user').value='';document.getElementById('pass').value=''");
72 assert.equal((await vault({action:"fill",tab,origin,document:state.document,username:"[email protected]",password:"selected-secret"})).ok,true);
73 assert.equal(await evaluate(tab,"document.getElementById('pass').value"),"selected-secret");
74 await api("/navigate",{id:tab,url:origin+"/next"});
75 await waitFor(()=>evaluate(tab,"location.pathname === '/next' && document.readyState === 'complete'"),"navigation");
76 assert.ok((await vault({action:"fill",tab,origin,document:state.document,username:"stale",password:"stale"})).vaultError);
77 await vault({action:"lock"});
78 assert.ok((await vault({action:"candidate",candidate:pending.id})).vaultError);
79 console.log("PASS: production controller HTTPS capture/fill, private authentication, public-state redaction, navigation and lock");
80} finally {
81 if(agent?.exitCode===null){const exit=once(agent,"exit");agent.kill("SIGTERM");const timer=setTimeout(()=>agent.kill("SIGKILL"),5000);await exit;clearTimeout(timer);}
82 await new Promise(resolve=>site.close(resolve));
83 await rm(dir,{recursive:true,force:true});
84}