跳到主要内容

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

浏览文件

macos_safety.go

283 行 · 9.8 KB历史下载
1package workbench
2
3import (
4 "bytes"
5 "context"
6 _ "embed"
7 "encoding/base64"
8 "encoding/json"
9 "errors"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "time"
15
16 "al.essio.dev/pkg/shellescape"
17 "github.com/sylvinus/agent-vm/internal/cage"
18 "github.com/sylvinus/agent-vm/internal/guestos"
19 "github.com/sylvinus/agent-vm/internal/managedproxy"
20 "go.yaml.in/yaml/v3"
21)
22
23//go:embed macos_safety_probe.cjs
24var macOSSafetyProbe string
25
26func macOSZone(zone string) string {
27 switch zone {
28 case "+00:00", "GMT", "UTC", "Etc/GMT", "Etc/UTC":
29 return "UTC"
30 default:
31 return zone
32 }
33}
34func macOSLocale(raw string) string {
35 return strings.ToLower(strings.ReplaceAll(strings.TrimSuffix(raw, ".UTF-8"), "_", "-"))
36}
37
38func (s *Server) guestSettingsOK(v guestObservation, cfg cage.Config) bool {
39 if s.windowsGuest != nil {
40 return windowsGuestSettingsMatch(v, cfg)
41 }
42 if s.macosGuest == nil {
43 return guestSettingsMatch(v, cfg)
44 }
45 return macOSZone(v.TZ) == macOSZone(cfg.Timezone) && macOSZone(v.SystemTimezone) == macOSZone(cfg.Timezone) &&
46 macOSLocale(v.ProcessLocale) == macOSLocale(cfg.Locale) && macOSLocale(v.SystemLocale) == macOSLocale(cfg.Locale) &&
47 macOSLocale(v.SystemLanguage) == macOSLocale(cfg.Locale)
48}
49
50func (s *Server) browserSettingsIssue(v browserObservation, cfg cage.Config) string {
51 if s.windowsGuest != nil {
52 if !strings.HasPrefix(v.Platform, "Win") {
53 return "客机浏览器没有报告 Windows 平台"
54 }
55 if effectiveWindowsZone(v.Timezone) != effectiveWindowsZone(cfg.Timezone) || effectiveWindowsZone(v.ExpectedTimezone) != effectiveWindowsZone(cfg.Timezone) {
56 return "客机浏览器实际时区与配置不符"
57 }
58 if !strings.EqualFold(v.Language, cfg.BrowserLanguage) {
59 return "客机浏览器实际语言与配置不符"
60 }
61 return ""
62 }
63 if s.macosGuest == nil {
64 return browserSettingsMismatch(v, cfg)
65 }
66 if !strings.HasPrefix(v.Platform, "Mac") {
67 return "客机浏览器没有报告 macOS 平台"
68 }
69 // Intl canonicalizes IANA aliases, including Etc/UTC -> UTC. The browser
70 // must independently report the same effective zone as the applied config.
71 if macOSZone(v.Timezone) != macOSZone(cfg.Timezone) || macOSZone(v.ExpectedTimezone) != macOSZone(cfg.Timezone) {
72 return "客机浏览器实际时区与配置不符"
73 }
74 if !strings.EqualFold(v.Language, cfg.BrowserLanguage) {
75 return "客机浏览器实际语言与配置不符"
76 }
77 return ""
78}
79
80func (s *Server) macOSGuestObservation(ctx context.Context, in map[string]any) (guestObservation, error) {
81 var result guestObservation
82 data, err := json.Marshal(in)
83 if err != nil {
84 return result, err
85 }
86 node := "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/editor/lib/node"
87 out, err := s.guestControl(ctx, "exec "+shellescape.QuoteCommand([]string{node, "-e", macOSSafetyProbe, base64.StdEncoding.EncodeToString(data)}), "safety-probe")
88 if err != nil || json.Unmarshal(out, &result) != nil {
89 return result, errors.New("macOS 客机未返回完整的网络观测")
90 }
91 if in["stage"] == "boundary" {
92 private, _ := in["private_file"].(string)
93 result.PrivateFile = s.checkMacOSPrivateFile(ctx, private)
94 shared, _ := in["shared_file"].(string)
95 challenge, _ := in["challenge"].(string)
96 result.SharedFile = s.checkMacOSSharedFile(ctx, shared, challenge)
97 }
98 return result, nil
99}
100
101// Use only the VM provisioning identity for this fixed read-only operation.
102// The GUI user never receives an administrator key, password, or root shell.
103func (s *Server) checkMacOSPrivateFile(ctx context.Context, private string) string {
104 if filepath.Dir(private) != s.profile || !strings.HasPrefix(filepath.Base(private), ".cage-private-probe-") {
105 return "unknown"
106 }
107 user, err := guestos.MacOSProvisionUser(s.profile)
108 if err != nil {
109 return "unknown"
110 }
111 base, err := guestos.MacOSSSHArgs(s.profile, user)
112 if err != nil {
113 return "unknown"
114 }
115 perl := `$> == 0 or exit 1; if (sysopen(my $fh,$ARGV[0],O_RDONLY|O_NONBLOCK)) {print "readable"} elsif ($! == ENOENT || $! == EACCES || $! == ENOTDIR) {print "unreachable"} else {print "unknown"}`
116 op := shellescape.QuoteCommand([]string{"/usr/bin/sudo", "-S", "-p", "", "/usr/bin/env", "-i", "PATH=/usr/bin:/bin", "/usr/bin/perl", "-MFcntl=:DEFAULT", "-MErrno=ENOENT,EACCES,ENOTDIR", "-e", perl, "--", private})
117 cmd := exec.CommandContext(ctx, sshExecutable(), append(base, "-T", s.sshTarget(), "--", "exec "+op+` < "$HOME/password"`)...)
118 cmd.Env = sshEnvironment()
119 out, err := cmd.Output()
120 if err != nil {
121 return "unknown"
122 }
123 result := strings.TrimSpace(string(out))
124 if result != "unreachable" && result != "readable" {
125 return "unknown"
126 }
127 return result
128}
129
130// The approved GUI login, rather than sshd, has the security-scoped bookmark.
131// Open the real project's terminal and send only the bounded marker operation.
132func (s *Server) checkMacOSSharedFile(ctx context.Context, shared, challenge string) bool {
133 host := filepath.Dir(shared)
134 name := filepath.Base(shared)
135 if !strings.HasPrefix(name, ".cage-share-probe-") || challenge == "" {
136 return false
137 }
138 s.mu.Lock()
139 share := s.projectShares[host]
140 approved := share != nil && share.detach != nil
141 s.mu.Unlock()
142 if !approved {
143 return false
144 }
145 probe, err := os.Open(shared)
146 if err != nil {
147 return false
148 }
149 defer probe.Close()
150 info, err := probe.Stat()
151 if err != nil || !info.Mode().IsRegular() {
152 return false
153 }
154 dir := macOSProjectPath(s.macosGuest.User, host)
155 op := `p=` + shellescape.Quote(name) + `; if test -f "$p" && test ! -L "$p" && test "$(cat "$p")" = ` + shellescape.Quote(challenge) + `; then printf %s ` + shellescape.Quote(challenge+":guest") + ` > "$p"; fi; exit`
156 cmd := s.macOSSSHCommand(ctx, "-tt", s.sshTarget(), "--", "exec /usr/local/libexec/cage-macos-terminal "+shellescape.Quote(dir))
157 tty, err := startTerminal(cmd, 80, 24)
158 if err != nil {
159 return false
160 }
161 defer func() { _ = tty.Close(); _ = tty.Kill(); _ = tty.Wait() }()
162 // OpenSSH switches its outer terminal to raw mode during authentication.
163 // Sending before it does so can discard typeahead. Wait for the mounted
164 // project's own login shell to emit its first prompt through the broker.
165 ready := make(chan bool, 1)
166 go func() { var buf [4096]byte; n, err := tty.Read(buf[:]); ready <- n > 0 && err == nil }()
167 select {
168 case ok := <-ready:
169 if !ok {
170 return false
171 }
172 case <-ctx.Done():
173 return false
174 case <-time.After(5 * time.Second):
175 return false
176 }
177 if _, err := tty.Write([]byte(op + "\r")); err != nil {
178 return false
179 }
180 timer := time.NewTimer(6 * time.Second)
181 defer timer.Stop()
182 tick := time.NewTicker(80 * time.Millisecond)
183 defer tick.Stop()
184 for {
185 select {
186 case <-ctx.Done():
187 return false
188 case <-timer.C:
189 return false
190 case <-tick.C:
191 var buf [257]byte
192 n, _ := probe.ReadAt(buf[:], 0)
193 if bytes.Equal(buf[:n], []byte(challenge+":guest")) {
194 return true
195 }
196 }
197 }
198}
199
200func (s *Server) macOSVMLayout() (bool, bool) {
201 data, err := os.ReadFile(filepath.Join(s.instanceDir(), "lima.yaml"))
202 if err != nil {
203 return false, false
204 }
205 var spec struct {
206 OS string `yaml:"os"`
207 Driver string `yaml:"vmType"`
208 Mounts, Networks []any
209 Extra []any `yaml:"additionalDisks"`
210 }
211 if yaml.Unmarshal(data, &spec) != nil || spec.OS != "Darwin" || spec.Driver != "vz" {
212 return false, false
213 }
214 return spec.Mounts != nil && len(spec.Mounts) == 0 && len(spec.Extra) == 0, spec.Networks != nil && len(spec.Networks) == 0
215}
216
217func (s *Server) macOSBrowserObservation(ctx context.Context, cfg cage.Config, network bool) (browserObservation, error) {
218 var observation browserObservation
219 data, err := s.nativeBrowserClient().request(ctx, "POST", "/audit", map[string]any{"timezone": cfg.Timezone, "network": network})
220 if err != nil || json.Unmarshal(data, &observation) != nil || observation.Platform == "" {
221 return observation, errors.New("无法在虚拟 Mac 的实际浏览器页面读取观测结果")
222 }
223 return observation, nil
224}
225
226func macOSIPv6LinkVerified(v guestObservation, before, after cage.GateStatus) bool {
227 if !after.PolicyVerified || before.Mode != cage.GateChecking || after.Mode != cage.GateChecking || before.RunID == "" || after.RunID != before.RunID || before.CheckID == "" || after.CheckID != before.CheckID || after.IPv6LinkProbeCheck != before.CheckID {
228 return false
229 }
230 if v.IPv6Connected || !v.IPv6UnscopedAbsent || !v.IPv6LinkSent || v.IPv6LinkInterface == "" || v.IPv6Unbound.Result != "no-route" || v.IPv6Unbound.GlobalSources != 0 || v.IPv6DefaultRoutes != len(v.IPv6Scoped) {
231 return false
232 }
233 seen := map[string]bool{}
234 for _, p := range v.IPv6Scoped {
235 if !strings.HasPrefix(p.Name, "utun") || seen[p.Name] || !p.RouteVerified || p.BoundIndex <= 0 || p.GlobalSources != 0 || (p.Result != "no-route" && p.Result != "timeout") {
236 return false
237 }
238 seen[p.Name] = true
239 }
240 return true
241}
242
243// Called only from the explicitly requested safety check. Restart the existing
244// selected core without selecting another node or changing its revision.
245func (s *Server) checkMacOSNetwork() error {
246 cfg, err := loadConfig(s.configPath)
247 if err != nil {
248 return err
249 }
250 if err = cfg.RequireManagedProxy(s.profile); err != nil {
251 return err
252 }
253 store, err := managedproxy.Load(s.profile)
254 if err != nil {
255 return err
256 }
257 if store.Selected == "" || store.Revision != cfg.ProxyRevision || store.Endpoint() != cfg.ProxyURL {
258 return errors.New("请先为这台 macOS 客机选择并应用代理节点")
259 }
260 if s.vmRunning() {
261 client, err := s.gateClient()
262 if err != nil {
263 return err
264 }
265 state, err := client.Status(s.operationContext())
266 if err != nil {
267 return err
268 }
269 if state.Configuration != cfg.Fingerprint() {
270 return errors.New("网络设置已保存,请重启 macOS 客机,登录后重新检测")
271 }
272 }
273 ctx := s.operationContext()
274 if !managedproxy.Running(ctx, s.profile, store) {
275 if err = validateProxyCore(ctx, s.profile, store); err != nil {
276 return err
277 }
278 if err = startProxyCore(ctx, s.profile, store); err != nil {
279 return err
280 }
281 }
282 return s.runSafetyCheck()
283}