跳到主要内容

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

浏览文件

macos-cli-login.py

111 行 · 4.8 KB历史下载
1"""Run with Cage's Python inside a prepared, network-authorized test VirtualMac.
2
3Use the ordinary guest account. The test gives Chrome and the official CLI a
4fresh temporary home, opens the official sign-in page, then cancels. It never
5submits an account, authorization code or model prompt.
6"""
7import json
8import os
9from pathlib import Path
10import pty
11import secrets
12import select
13import signal
14import subprocess
15import tempfile
16import time
17from urllib.parse import urlsplit
18
19
20def browser_request(browser, route):
21 browser.stdin.write(json.dumps({"method": "GET", "path": route}).encode() + b"\n")
22 browser.stdin.flush()
23 if not select.select([browser.stdout], [], [], 30)[0]:
24 raise RuntimeError("Guest Chrome timed out")
25 value = json.loads(browser.stdout.readline())
26 if value.get("error"):
27 raise RuntimeError("The guest Chrome controller could not serve " + route + " (" + str(value.get("code")) + ")")
28 return value
29
30
31def authorized_tab(snapshot):
32 for tab in snapshot.get("tabs", []):
33 if not tab.get("login") or tab["id"] != snapshot.get("active"):
34 continue
35 if tab["url"] in ("about:blank", "null"):
36 continue
37 url = urlsplit(tab["url"])
38 if url.query or url.fragment or url.path not in ("", "/"):
39 raise RuntimeError("The workbench snapshot exposed a login URL path or parameters")
40 return url.scheme == "https" and url.hostname in (
41 "claude.ai", "claude.com", "platform.claude.com", "platform.anthropic.com", "console.anthropic.com")
42 return False
43
44
45def check_login(browser, env):
46 master, slave = pty.openpty()
47 try:
48 account = secrets.token_hex(12)
49 with subprocess.Popen(["/usr/local/bin/cage-claude-account", "login", account],
50 stdin=slave, stdout=slave, stderr=slave, env=env,
51 start_new_session=True) as cli:
52 try:
53 deadline = time.monotonic() + 45
54 while cli.poll() is None and time.monotonic() < deadline:
55 # Drain without storing or printing the access-bearing CLI output.
56 if select.select([master], [], [], .25)[0]:
57 os.read(master, 65536)
58 if authorized_tab(browser_request(browser, "/tabs")):
59 break
60 time.sleep(.3)
61 else:
62 raise RuntimeError("The CLI did not activate an isolated official authorization tab")
63 finally:
64 if cli.poll() is None:
65 os.killpg(cli.pid, signal.SIGINT)
66 try:
67 cli.wait(timeout=10)
68 except subprocess.TimeoutExpired:
69 os.killpg(cli.pid, signal.SIGKILL)
70 finally:
71 os.close(master)
72 os.close(slave)
73 if any(tab.get("login") for tab in browser_request(browser, "/tabs").get("tabs", [])):
74 raise RuntimeError("Canceling the login left its private tab open")
75
76
77def main():
78 model = subprocess.check_output(["/usr/sbin/sysctl", "-n", "hw.model"], text=True).strip()
79 if os.geteuid() == 0 or not model.startswith("VirtualMac") or Path("/var/db/cage-guest-os").read_text().strip() != "macos":
80 raise RuntimeError("Run in a prepared test VirtualMac as its ordinary account")
81 base = Path("/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0")
82 with tempfile.TemporaryDirectory(dir="/tmp", prefix="cgc.") as home:
83 env = dict(os.environ, HOME=home, TERM="xterm-256color",
84 PATH="/usr/local/libexec/cage-cli/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin")
85 with subprocess.Popen([base / "editor/lib/node", base / "controller/macos-native-browser.mjs"],
86 env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
87 stderr=subprocess.DEVNULL) as browser:
88 try:
89 deadline = time.monotonic() + 45
90 while True:
91 try:
92 if browser_request(browser, "/health").get("ready"):
93 break
94 except RuntimeError as error:
95 if "browser_unavailable" not in str(error) or time.monotonic() >= deadline:
96 raise
97 if time.monotonic() >= deadline:
98 raise RuntimeError("Guest Chrome is unavailable")
99 time.sleep(1)
100 check_login(browser, env)
101 finally:
102 browser.stdin.close()
103 try:
104 browser.wait(timeout=12)
105 except subprocess.TimeoutExpired:
106 browser.kill()
107 print("Official Claude Code authorization opened in guest Chrome and closed on cancellation.")
108
109
110if __name__ == "__main__":
111 main()