跳到主要内容

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

浏览文件

test-macos-claude-trial.py

109 行 · 4.7 KB历史下载
1"""Check the installed local macOS trial's official app, without signing in.
2
3Run with uv run --no-project python scripts/guest-os/test-macos-claude-trial.py
4--profile <trial profile> --frame <new PNG path>. Inspect the final window PNG
5to distinguish the online login page from an offline error or another dialog.
6"""
7
8import argparse
9import base64
10import hashlib
11import http.cookiejar
12import json
13import os
14from pathlib import Path
15import struct
16import time
17from urllib import error, parse, request
18
19
20class LocalOnly(request.HTTPRedirectHandler):
21 def redirect_request(self, *args):
22 raise RuntimeError("Unexpected redirect from the local desktop gateway")
23
24
25def main():
26 args = argparse.ArgumentParser(description=__doc__)
27 args.add_argument("--profile", type=Path, required=True)
28 args.add_argument("--frame", type=Path, required=True)
29 options = args.parse_args()
30 if options.frame.exists():
31 args.error("Specify a new PNG path")
32 record = json.loads((options.profile / "desktop-entry/control.json").read_text())
33 port = record["port"]
34 if type(port) is not int or not 17777 <= port < 17808:
35 raise RuntimeError("Invalid local desktop gateway port")
36 origin = f"http://localhost:{port}"
37 client = request.build_opener(
38 request.ProxyHandler({}), request.HTTPCookieProcessor(http.cookiejar.CookieJar()), LocalOnly()
39 )
40 connection = None
41
42 def call(path, data=None):
43 headers = {"Origin": origin}
44 if connection:
45 headers["X-Cage-Connection"] = connection
46 body = None
47 if data is not None:
48 headers["Content-Type"] = "application/json"
49 body = json.dumps(data).encode()
50 req = request.Request(f"{origin}/api/{path}", body, headers)
51 try:
52 with client.open(req, timeout=60) as response:
53 return json.load(response)
54 except error.HTTPError as exc:
55 raise RuntimeError(f"Local {path} returned HTTP {exc.code}") from None
56
57 launch = parse.urlsplit(call("launch", {"token": record["token"]})["url"])
58 if f"{launch.scheme}://{launch.netloc}" != origin or not launch.fragment:
59 raise RuntimeError("Unexpected local launch URL")
60 call("session", {"token": launch.fragment})
61 context = call("client/context")
62 if context.get("mode") != "local" or not context.get("desktop_gateway"):
63 raise RuntimeError("The installed desktop app has not selected this local workload")
64 connection = context["connection_id"]
65 account, state = call("account"), call("status")
66 if account.get("guest_system") != "macos" or not account.get("unlocked") or not state.get("ready"):
67 raise RuntimeError("The target is not the unlocked, ready macOS guest workbench")
68 safety = state.get("safety") or {}
69 checks = [c for c in (safety.get("report") or {}).get("checks", []) if c.get("critical")]
70 if (safety.get("gate") or {}).get("mode") != "open" or len(checks) != 11 or any(c["state"] != "passed" for c in checks):
71 raise RuntimeError("The trial has not passed all eleven current network and isolation checks")
72
73 def window(action, **fields):
74 reply = call("macos/claude/window", {"action": action, **fields})
75 if "error" in reply:
76 raise RuntimeError("Guest window service: " + reply["error"])
77 return reply
78
79 status = window("status")
80 if not all(status.get(k) for k in ("installed", "screen", "input")):
81 raise RuntimeError("The guest application or its window permissions are unavailable")
82 window("launch")
83 deadline = time.monotonic() + 12
84 while True:
85 try:
86 before = window("frame")
87 break
88 except RuntimeError as exc:
89 if not any(key in str(exc) for key in ("not_running", "no_visible_window")) or time.monotonic() >= deadline:
90 raise
91 time.sleep(.4)
92 window("key", window=before["window"], pid=before["pid"], key="Tab")
93 time.sleep(.4)
94 after = window("frame")
95 if (before["window"], before["pid"]) != (after["window"], after["pid"]):
96 raise RuntimeError("Focused application window changed during the input check")
97 png = base64.b64decode(after["image"], validate=True)
98 if not png.startswith(b"\x89PNG\r\n\x1a\n") or png[12:16] != b"IHDR":
99 raise RuntimeError("Expected a window PNG")
100 with os.fdopen(os.open(options.frame, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600), "wb") as stream:
101 stream.write(png)
102 print(json.dumps({
103 "checked": len(checks), "size": struct.unpack(">II", png[16:24]), "bytes": len(png),
104 "sha256": hashlib.sha256(png).hexdigest(), "changedAfterTab": before["image"] != after["image"]
105 }))
106
107
108if __name__ == "__main__":
109 main()