| 1 | |
| 2 | |
| 3 | import assert from 'node:assert/strict'; |
| 4 | import { spawn } from 'node:child_process'; |
| 5 | import { once } from 'node:events'; |
| 6 | import { randomBytes } from 'node:crypto'; |
| 7 | import { cp, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; |
| 8 | import http from 'node:http'; |
| 9 | import { tmpdir } from 'node:os'; |
| 10 | import { join } from 'node:path'; |
| 11 | import { setTimeout as delay } from 'node:timers/promises'; |
| 12 | |
| 13 | export async function createPrivacyController({ preferences, headless = true } = {}) { |
| 14 | const browserPath = process.env.CAGE_PRIVACY_BROWSER_PATH || process.env.CAGE_TEST_BROWSER_PATH; |
| 15 | assert.ok(browserPath, 'Set CAGE_PRIVACY_BROWSER_PATH or CAGE_TEST_BROWSER_PATH to Chromium'); |
| 16 | const directory = await realpath(await mkdtemp(join(tmpdir(), 'cage-browser-privacy-'))); |
| 17 | if (preferences) { |
| 18 | await mkdir(join(directory, 'profile/Default'), { recursive: true }); |
| 19 | await writeFile(join(directory, 'profile/Default/Preferences'), JSON.stringify(preferences)); |
| 20 | } |
| 21 | const token = randomBytes(32).toString('hex'); |
| 22 | const site = http.createServer((req, res) => { |
| 23 | if (req.url === '/language-header') { |
| 24 | res.end(req.headers['accept-language'] || ''); |
| 25 | return; |
| 26 | } |
| 27 | res.setHeader('Content-Type', 'text/html'); |
| 28 | res.end('<!doctype html><script>globalThis.webdriverAtLoad = navigator.webdriver; if (parent !== self) parent.postMessage({fixtureIdentity: navigator.webdriver, fixtureGetter: Object.getOwnPropertyDescriptor(Navigator.prototype, "webdriver").get.toString()}, "*")</script><title>Privacy fixture</title><form><input autocomplete="username"><input type="password" autocomplete="current-password"><button>Sign in</button></form>'); |
| 29 | }); |
| 30 | await new Promise(resolve => site.listen(0, '127.0.0.1', resolve)); |
| 31 | const origin = `http://localhost:${site.address().port}`; |
| 32 | let agent, control, stderr = ''; |
| 33 | const waitFor = async (read, label) => { |
| 34 | const deadline = Date.now() + 15000; |
| 35 | while (Date.now() < deadline) { |
| 36 | if (agent && agent.exitCode !== null) throw new Error(`Controller exited: ${stderr}`); |
| 37 | const value = await read(); |
| 38 | if (value) return value; |
| 39 | await delay(50); |
| 40 | } |
| 41 | throw new Error(`Timed out: ${label}. ${stderr.slice(-1000)}`); |
| 42 | }; |
| 43 | const api = async (path, body) => { |
| 44 | const response = await fetch(control + path, { |
| 45 | method: body === undefined ? 'GET' : 'POST', |
| 46 | headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, |
| 47 | body: body === undefined ? undefined : JSON.stringify(body), |
| 48 | }); |
| 49 | const result = await response.json(); |
| 50 | if (!response.ok) throw new Error(result.error || 'Controller request failed'); |
| 51 | return result; |
| 52 | }; |
| 53 | const cdp = (id, method, params = {}) => api('/__privacy-test', { id, method, params }); |
| 54 | const evaluate = async (id, expression) => { |
| 55 | const result = await cdp(id, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); |
| 56 | assert.equal(result.exceptionDetails, undefined); |
| 57 | return result.result.value; |
| 58 | }; |
| 59 | const stop = async () => { |
| 60 | if (agent?.exitCode === null) { |
| 61 | const done = once(agent, 'exit'); agent.kill('SIGTERM'); |
| 62 | const kill = setTimeout(() => agent.kill('SIGKILL'), 5000); |
| 63 | await done; clearTimeout(kill); |
| 64 | } |
| 65 | }; |
| 66 | const close = async () => { |
| 67 | await stop(); |
| 68 | site.closeAllConnections(); |
| 69 | await new Promise(resolve => site.close(resolve)); |
| 70 | await rm(directory, { recursive: true, force: true }); |
| 71 | }; |
| 72 | try { |
| 73 | const sourceDirectory = new URL('../internal/cage/', import.meta.url); |
| 74 | for (const name of await readdir(sourceDirectory)) |
| 75 | if ((name.startsWith('browser-') && name.endsWith('.mjs')) || name === 'native-input.mjs' || name === 'tailnet-client.mjs' || name === 'browser-extension-archive.py') |
| 76 | await cp(new URL(name, sourceDirectory), join(directory, name)); |
| 77 | await cp(new URL('split-extension', sourceDirectory), join(directory, 'extension'), { recursive: true }); |
| 78 | const source = await readFile(new URL('browser-agent.mjs', sourceDirectory), 'utf8'); |
| 79 | const marker = 'const input = JSON.parse(text || "{}");'; |
| 80 | assert.ok(source.includes(marker)); |
| 81 | const adapted = source.replaceAll('/home/cage-browser', directory) |
| 82 | .replace('/etc/claude-cage/browser-control.json', join(directory, 'control.json')) |
| 83 | .replace('/usr/local/lib/cage-split', join(directory, 'extension')) |
| 84 | .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(browserPath)}, flags`) |
| 85 | .replace('"--start-fullscreen",', headless ? '"--headless=new", "--disable-background-networking",' : '"--start-fullscreen", "--disable-background-networking",') |
| 86 | .replace('server.listen(18500, "127.0.0.1");', 'server.listen(0,"127.0.0.1",()=>console.log("PORT="+server.address().port));') |
| 87 | .replace(marker, `${marker}\nif(req.url === "/__privacy-test") { res.end(JSON.stringify(await cdp(input.method, input.params || {}, input.id ? await session(input.id) : input.sessionId))); return; }`); |
| 88 | await writeFile(join(directory, 'browser-agent.mjs'), adapted); |
| 89 | await writeFile(join(directory, 'control.json'), JSON.stringify({ token, workspace: directory })); |
| 90 | await writeFile(join(directory, 'homepage.json'), JSON.stringify({ url: origin + '/home' })); |
| 91 | const start = async () => { |
| 92 | control = ''; stderr = ''; |
| 93 | agent = spawn(process.execPath, [join(directory, 'browser-agent.mjs')], { stdio: ['ignore', 'pipe', 'pipe'] }); |
| 94 | let output = ''; |
| 95 | agent.stdout.on('data', chunk => { |
| 96 | output += chunk; |
| 97 | const match = output.match(/PORT=(\d+)/); |
| 98 | if (match) control = 'http://127.0.0.1:' + match[1]; |
| 99 | }); |
| 100 | agent.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); }); |
| 101 | await waitFor(() => control, 'listener'); |
| 102 | await waitFor(async () => { |
| 103 | try { |
| 104 | const response = await fetch(control + '/health', { headers: { Authorization: `Bearer ${token}` } }); |
| 105 | return response.ok; |
| 106 | } catch { return false; } |
| 107 | }, 'browser readiness'); |
| 108 | }; |
| 109 | await start(); |
| 110 | const uploadExtension = async bytes => { |
| 111 | const response = await fetch(control + '/extensions-upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: bytes }); |
| 112 | const result = await response.json(); |
| 113 | if (!response.ok) throw new Error(result.error || '扩展包读取失败'); |
| 114 | return result; |
| 115 | }; |
| 116 | const states = signal => fetch(control + '/events', { headers: { Authorization: `Bearer ${token}` }, signal }); |
| 117 | return { api, cdp, evaluate, waitFor, origin, directory, close, uploadExtension, states, restart: async () => { await stop(); await start(); } }; |
| 118 | } catch (error) { await close(); throw error; } |
| 119 | } |