跳到主要内容

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

浏览文件

macos_login.go

325 行 · 10.6 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "github.com/sylvinus/agent-vm/internal/cage"
8 "io"
9 "net"
10 "net/http"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "time"
15
16 "github.com/sylvinus/agent-vm/internal/guestos"
17 "github.com/sylvinus/agent-vm/internal/host"
18)
19
20// Only installer-created bindings carry this identity. A damaged binding stays
21// quarantined; the VM process independently requires a valid matching binding.
22func (s *Server) macSetupPending() bool {
23 if s.macosGuest == nil || s.macosGuest.SetupID == "" {
24 return false
25 }
26 current, err := guestos.LoadMacOSProfile(s.profile)
27 return err != nil || current == nil || current.SetupID != ""
28}
29
30func macOSSetupRoute(path string) bool {
31 if strings.HasPrefix(path, "/api/agent/jobs/") {
32 return true
33 }
34 if !strings.HasPrefix(path, "/api/") {
35 return true
36 }
37 switch path {
38 case "/api/account", "/api/appearance", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", "/api/status", "/api/start", "/api/stop", "/api/macos/first-setup", "/api/environment/initialization":
39 return true
40 }
41 return strings.HasPrefix(path, "/api/account/") || strings.HasPrefix(path, "/api/diagnostics")
42}
43
44type macSetupPermissions struct {
45 Screen bool `json:"screen"`
46 Input bool `json:"input"`
47 Projects bool `json:"projects"`
48 ProjectsError string `json:"projects_error,omitempty"`
49 Error string `json:"error,omitempty"`
50 ManagedCredential bool `json:"managed_credential,omitempty"`
51}
52
53type macLoginLease struct {
54 request guestos.MacLoginRequest
55 stopAccount func() bool
56 stopService func() bool
57}
58
59func (l *macLoginLease) stop() {
60 if l == nil {
61 return
62 }
63 l.stopAccount()
64 l.stopService()
65}
66
67func (s *Server) revokeMacLogin(session string) {
68 s.mu.Lock()
69 lease := s.macLoginLease
70 if lease == nil || lease.request.Session != session {
71 s.mu.Unlock()
72 return
73 }
74 s.macLoginLease = nil
75 s.mu.Unlock()
76 lease.stop()
77 connection, err := net.DialTimeout("unix", filepath.Join(s.instanceDir(), "cage-login.sock"), 2*time.Second)
78 if err != nil {
79 return
80 }
81 defer connection.Close()
82 _ = connection.SetWriteDeadline(time.Now().Add(2 * time.Second))
83 _ = json.NewEncoder(connection).Encode(lease.request)
84}
85
86func (s *Server) trackMacLogin(epoch context.Context, input guestos.MacLoginRequest, result guestos.MacLoginReply) {
87 if input.Action == "open" && result.Session != "" {
88 lifetime := s.lifetimeContext()
89 lease := &macLoginLease{request: guestos.MacLoginRequest{Action: "close", Session: result.Session, Setup: input.Setup, Maintenance: input.Maintenance}}
90 s.mu.Lock()
91 previous := s.macLoginLease
92 s.macLoginLease = lease
93 lease.stopAccount = context.AfterFunc(epoch, func() { s.revokeMacLogin(result.Session) })
94 lease.stopService = context.AfterFunc(lifetime, func() { s.revokeMacLogin(result.Session) })
95 s.mu.Unlock()
96 previous.stop()
97 return
98 }
99 if input.Action == "close" || result.Closed {
100 s.mu.Lock()
101 lease := s.macLoginLease
102 if lease != nil && lease.request.Session == input.Session {
103 s.macLoginLease = nil
104 } else {
105 lease = nil
106 }
107 s.mu.Unlock()
108 lease.stop()
109 }
110}
111
112func (s *Server) macSetupPermissions(ctx context.Context) (macSetupPermissions, error) {
113 var status macSetupPermissions
114 data, err := s.macOSWindowCall(ctx, macOSWindowRequest{Action: "setup-status"})
115 if err != nil {
116 return status, err
117 }
118 if json.Unmarshal(data, &status) != nil || status.Error != "" {
119 return status, errors.New("请在首次设置画面中登录客机账户")
120 }
121 s.mu.Lock()
122 status.Projects = !s.macSetupProjectsChecked.IsZero() && time.Since(s.macSetupProjectsChecked) < 2*time.Minute
123 probeDue := time.Since(s.macSetupProjectsAttempt) > 15*time.Second
124 s.mu.Unlock()
125 if status.Screen && status.Input && !status.Projects && probeDue && s.op.TryLock() {
126 s.mu.Lock()
127 s.macSetupProjectsAttempt = time.Now()
128 s.mu.Unlock()
129 probeErr := s.checkMacOSSetupProjects(ctx)
130 s.op.Unlock()
131 if probeErr != nil {
132 status.ProjectsError = probeErr.Error()
133 }
134 s.mu.Lock()
135 status.Projects = !s.macSetupProjectsChecked.IsZero()
136 s.mu.Unlock()
137 }
138 if install, err := guestos.LoadInstallation(s.profile); err == nil && install != nil {
139 password, err := s.account.savedMacGuestPassword(ctx, install.ID)
140 status.ManagedCredential = err == nil && password != ""
141 }
142 return status, nil
143}
144
145func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) {
146 if s.macosGuest == nil || !s.hasTrustedView(r) {
147 http.NotFound(w, r)
148 return
149 }
150 var input guestos.MacLoginRequest
151 if !readJSON(w, r, &input) {
152 return
153 }
154 input.Setup = r.URL.Path == "/api/macos/first-setup"
155 if r.URL.Path == "/api/macos/maintenance" {
156 if !guestos.ValidMacMaintenancePurpose(input.Maintenance) {
157 http.Error(w, "请选择需要恢复的客机系统权限", http.StatusBadRequest)
158 return
159 }
160 switch input.Action {
161 case "open", "close", "frame", "click", "key", "scroll", "select-all", "fill-password":
162 default:
163 http.Error(w, "维护画面只接受窗口查看与局部输入", http.StatusBadRequest)
164 return
165 }
166 } else {
167 input.Maintenance = ""
168 }
169 if input.Setup && !s.macSetupPending() {
170 http.Error(w, "首次设置入口已关闭", http.StatusGone)
171 return
172 }
173 // Passwords are supplied exclusively from encrypted storage, never from HTTP.
174 input.Password = ""
175 if input.Action == "show-password" {
176 install, err := guestos.LoadInstallation(s.profile)
177 bound, bindingErr := guestos.LoadMacOSProfile(s.profile)
178 if err != nil || bindingErr != nil || install == nil || bound == nil || bound.MachineID != s.macosGuest.MachineID {
179 http.Error(w, "客机身份已改变", 409)
180 return
181 }
182 password, err := s.account.savedMacGuestPassword(r.Context(), install.ID)
183 if err != nil || password == "" {
184 http.Error(w, "客机凭据不可用,请核对安装记录与保险箱", 409)
185 return
186 }
187 w.Header().Set("Cache-Control", "no-store")
188 jsonReply(w, map[string]string{"password": password})
189 return
190 }
191 if input.Setup {
192 gate, err := s.gateClient()
193 if err != nil {
194 http.Error(w, "请先启动客机,确认首次设置期间外网已关闭", 409)
195 return
196 }
197 check, cancel := context.WithTimeout(r.Context(), 2*time.Second)
198 state, err := gate.Status(check)
199 cancel()
200 if err != nil || state.Mode != cage.GateClosed {
201 http.Error(w, "首次设置仅在客机断网时可用", 409)
202 return
203 }
204 switch input.Action {
205 case "fill-password":
206 // The native runner fills macOS's own authorization dialog. The browser
207 // never receives the stored credential; no submit key is sent.
208 install, err := guestos.LoadInstallation(s.profile)
209 if err != nil || install == nil || install.ID.String() != s.macosGuest.SetupID {
210 http.Error(w, "首次设置身份已改变", 409)
211 return
212 }
213 password, err := s.account.savedMacGuestPassword(r.Context(), install.ID)
214 if err != nil || password == "" {
215 http.Error(w, "客机凭据不可用,请核对安装记录与保险箱", 409)
216 return
217 }
218 input.Password = password
219 case "permissions", "verify-projects", "finish":
220 perm, err := s.macSetupPermissions(r.Context())
221 if err != nil {
222 http.Error(w, err.Error(), 409)
223 return
224 }
225 if input.Action == "permissions" {
226 jsonReply(w, perm)
227 return
228 }
229 if input.Action == "finish" && (!perm.Screen || !perm.Input) {
230 http.Error(w, "请先完成窗口录制、辅助功能和文件系统扩展三项授权", 409)
231 return
232 }
233 if !s.op.TryLock() {
234 http.Error(w, "正在处理其他客机操作,请重试", 409)
235 return
236 }
237 defer s.op.Unlock()
238 if err = s.checkMacOSSetupProjects(r.Context()); err != nil {
239 http.Error(w, err.Error(), 409)
240 return
241 }
242 if input.Action == "verify-projects" {
243 perm.Projects = true
244 jsonReply(w, perm)
245 return
246 }
247 // The cleanup executable is fixed, root-owned and verifies the temporary
248 // setup administrator before retiring it. Its output contains no credentials.
249 ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
250 defer cancel()
251 cmd := s.macOSSetupAdminCommand(ctx)
252 if err = cmd.Run(); err != nil {
253 http.Error(w, "临时设置账户未关闭,请重试完成设置", 409)
254 return
255 }
256 case "screen", "input", "projects":
257 s.macOSWindowRPC(w, r, macOSWindowRequest{Action: "setup-" + input.Action})
258 return
259 case "open", "close", "frame", "click", "key", "scroll":
260 default:
261 http.Error(w, "无效的首次设置操作", 400)
262 return
263 }
264 } else if input.Action == "finish" {
265 http.Error(w, "无效的登录操作", 400)
266 return
267 }
268 if len(input.Session) > 80 {
269 http.Error(w, "无效的登录会话", 400)
270 return
271 }
272 timeout := 8 * time.Second
273 if input.Maintenance != "" {
274 timeout = 15 * time.Second
275 }
276 epoch, _ := s.account.accessFor(true)
277 ctx, cancel := context.WithTimeout(r.Context(), timeout)
278 defer cancel()
279 var dial net.Dialer
280 conn, err := dial.DialContext(ctx, "unix", filepath.Join(s.instanceDir(), "cage-login.sock"))
281 if err != nil {
282 http.Error(w, "这台客机尚未启动带登录控件的运行器", 409)
283 return
284 }
285 defer conn.Close()
286 stop := context.AfterFunc(ctx, func() { conn.Close() })
287 defer stop()
288 _ = conn.SetDeadline(time.Now().Add(timeout))
289 var result guestos.MacLoginReply
290 if json.NewEncoder(conn).Encode(input) != nil || json.NewDecoder(io.LimitReader(conn, 6<<20)).Decode(&result) != nil {
291 http.Error(w, "客机登录界面无法响应", 503)
292 return
293 }
294 if input.Maintenance != "" && result.MaintenanceVersion != 1 {
295 result = guestos.MacLoginReply{Closed: true, Recovery: "environment-restart", Error: "虚拟 Mac 运行器需要重新加载。请保存工作,在环境设置中停止并重新启动虚拟 Mac,再打开授权设置。"}
296 }
297 s.trackMacLogin(epoch, input, result)
298 if input.Action == "open" && ctx.Err() != nil {
299 s.revokeMacLogin(result.Session)
300 return
301 }
302 if input.Setup && input.Action == "finish" && result.Error == "" && !s.macSetupPending() {
303 s.restoreProjectShares()
304 }
305 w.Header().Set("Cache-Control", "no-store")
306 w.Header().Set("Content-Type", "application/json; charset=utf-8")
307 if err := json.NewEncoder(w).Encode(result); err != nil && input.Action == "open" {
308 s.revokeMacLogin(result.Session)
309 }
310}
311
312func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd {
313 user, err := guestos.MacOSProvisionUser(s.profile)
314 if err != nil {
315 return &exec.Cmd{Err: err}
316 }
317 args, err := guestos.MacOSSSHArgs(s.profile, user)
318 if err != nil {
319 return &exec.Cmd{Err: err}
320 }
321 cmd := exec.CommandContext(ctx, sshExecutable(), append(args, "-T", "cage-macos", "--", "exec /usr/bin/sudo -S -p '' /usr/local/libexec/cage-finish-initial-setup < /Users/"+user+"/password")...)
322 cmd.Env = sshEnvironment()
323 host.HideCommandWindow(cmd)
324 return cmd
325}