| 1 | |
| 2 | |
| 3 | import assert from "node:assert/strict"; |
| 4 | import { spawn, execFileSync } from "node:child_process"; |
| 5 | import { once } from "node:events"; |
| 6 | import { randomBytes } from "node:crypto"; |
| 7 | import { cp, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; |
| 8 | import https from "node:https"; |
| 9 | import { tmpdir } from "node:os"; |
| 10 | import { join } from "node:path"; |
| 11 | import { setTimeout as delay } from "node:timers/promises"; |
| 12 | assert.ok(process.env.CAGE_TEST_BROWSER_PATH, "Set CAGE_TEST_BROWSER_PATH to Chromium"); |
| 13 | const dir = await realpath(await mkdtemp(join(tmpdir(), "cage-vault-controller-"))); |
| 14 | const token = randomBytes(32).toString("hex"), lease = randomBytes(32).toString("hex"); |
| 15 | execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(dir, "key.pem"), "-out", join(dir, "cert.pem"), "-days", "1", "-subj", "/CN=localhost"], { stdio: "ignore" }); |
| 16 | const 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 | }); |
| 20 | await new Promise(resolve => site.listen(0, "127.0.0.1", resolve)); |
| 21 | const origin = `https://127.0.0.1:${site.address().port}`; |
| 22 | let agent, control, stderr = ""; |
| 23 | async 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 | } |
| 27 | async 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 | } |
| 32 | const vault = input => api("/vault",{lease,...input}); |
| 33 | async 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 | } |
| 38 | try { |
| 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 | } |