跳到主要内容

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

浏览文件

server.go

891 行 · 35.0 KB历史下载
1package workbench
2
3import (
4 "context"
5 "crypto/rand"
6 "crypto/subtle"
7 "embed"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "github.com/sylvinus/agent-vm/internal/cage"
13 "github.com/sylvinus/agent-vm/internal/diagnostics"
14 "github.com/sylvinus/agent-vm/internal/guestos"
15 "github.com/sylvinus/agent-vm/internal/host"
16 "github.com/sylvinus/agent-vm/internal/hostimage"
17 "io"
18 "io/fs"
19 "log"
20 "net"
21 "net/http"
22 "net/url"
23 "os"
24 "os/signal"
25 "path/filepath"
26 "runtime/debug"
27 "strings"
28 "sync"
29 "syscall"
30 "time"
31)
32
33//go:embed web/*
34var assets embed.FS
35
36const cookieName = "cage_session"
37
38type controlFile struct {
39 Port int `json:"port"`
40 Token string `json:"token"`
41 PID int `json:"pid"`
42 Controller ControllerIdentity `json:"controller"`
43}
44type Server struct {
45 desktopViews displayViewDemand
46 desktopDisplayUpdate func(bool) error
47 browserViews displayViewDemand
48 desktopStatus desktopStatusCache
49 agentNativeQueue agentNativeQueue
50 macSetupProjectsChecked time.Time
51 macSetupProjectsAttempt time.Time
52 macProjectsRetryAt time.Time
53 macLoginLease *macLoginLease
54 macosGuest *guestos.MacOSProfile
55 macResources macOSResourceObserver
56 windowsGuest *guestos.WindowsProfile
57 windowsState windowsGuestState
58 windowsProjectHistory map[string]string
59 clipboardFiles map[string]clipboardFileSelection
60 clipboardRelease func([]string)
61 clipboardCancel context.CancelFunc
62 clipboardGuestSession string
63 phones mobilePairing
64 instanceID string
65 clientOnly bool
66 desktopEntry bool
67 windowOwners map[int]bool
68 remote *remoteGateway
69 account *localAccount
70 identity ControllerIdentity
71 guestManifest *cage.GuestManifest
72 guestUpdateRequired bool
73 guestUpdateError string
74 storageRecoveryError string
75 closing bool
76 shutdown func()
77 claudeAccounts claudeAccountManager
78 favoritesMu sync.Mutex
79 diagnosticMu sync.Mutex
80 diagnosticRateMu sync.Mutex
81 diagnosticWindow time.Time
82 diagnosticCount int
83 tickets map[string]time.Time
84 browserControl *browserClient
85 controlSession guestSession
86 windowsBrowserControl *windowsBrowserClient
87 nativeDownloads map[string]*nativeDownload
88 nativeDownloadSlots chan struct{}
89 nativeDownloadRevision uint64
90 windowsNetwork *windowsHostNetwork
91 op sync.Mutex
92 profile, configPath, exe, origin, token, session string
93 mu sync.Mutex
94 preferences Preferences
95 jobs jobManager
96 ready bool
97 location *Location
98 exitProbeError string
99 locationError string
100 networkIntentError string
101 credentials guestCredentials
102 terminals terminalManager
103 mobileCLI mobileCLIStore
104 conversationMu sync.Mutex
105 mobileConnectMu sync.Mutex
106 audioClients int
107 projectShares map[string]*projectShare
108 projectErrors []projectShareError
109 clientMounts map[string]*guestClientMount
110 clientWorkspace string
111 safety safetyState
112 recovery networkRecovery
113 locations map[string]Location
114 monitorCancel context.CancelFunc
115 monitorSafetyOp sync.Mutex
116 safetyOp sync.Mutex
117 networkPaused bool
118 proxyNetworkLost bool
119 checkCancel context.CancelFunc
120 lifeContext context.Context
121 lifeCancel context.CancelFunc
122 monitors sync.WaitGroup
123 activities sync.WaitGroup
124 closeOnce sync.Once
125 closeErr error
126 controlPublished bool
127}
128
129func randomToken() string {
130 b := make([]byte, 32)
131 if _, err := rand.Read(b); err != nil {
132 panic(err)
133 }
134 return hex.EncodeToString(b)
135}
136func equalSecret(a, b string) bool {
137 return len(a) > 0 && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
138}
139func Serve(configPath string) error { return serve(configPath, false, "") }
140
141func ServeClient(configPath string) error { return serve(configPath, true, "") }
142
143// ServeDesktop is the desktop window's connection gateway. Its control lock and
144// logs live separately from the workload it may later attach to.
145func ServeDesktop(fullConfigPath string) error {
146 return serve(desktopConfigPath(fullConfigPath), false, fullConfigPath)
147}
148
149func serve(configPath string, clientOnly bool, fullConfigPath string) (returned error) {
150 store := diagnostics.New(filepath.Dir(configPath))
151 diagnostics.SetDefault(store)
152 if err := store.Clean(); err != nil {
153 return err
154 }
155
156 diagnostics.Log("info", "controller", "service starting")
157 defer func() { diagnostics.Log("info", "controller", "service stopped") }()
158 profile := filepath.Dir(configPath)
159 if err := host.EnsurePrivateDir(profile); err != nil {
160 return err
161 }
162 lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
163 if err != nil {
164 return err
165 }
166 defer lock.Close()
167 if err = lockControllerForStart(lock); err != nil {
168 if controllerLockContended(err) {
169 return errors.New("此配置已有工作台服务正在运行")
170 }
171 return fmt.Errorf("无法锁定工作台控制文件: %w", err)
172 }
173 if err := host.ProtectFile(lock.Name()); err != nil {
174 return err
175 }
176 if err := store.ImportLegacy(filepath.Dir(configPath)); err != nil {
177 diagnostics.Log("warn", "diagnostics", "legacy log import failed: "+err.Error())
178 }
179 exe, err := os.Executable()
180 if err != nil {
181 return err
182 }
183 var listener net.Listener
184 port := 17777
185 for ; port < 17808; port++ {
186 listener, err = net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", port))
187 if err == nil {
188 break
189 }
190 }
191 if err != nil {
192 return err
193 }
194 defer listener.Close()
195 s := &Server{profile: profile, configPath: configPath, exe: exe, clientOnly: clientOnly, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: defaultKeyboard(), AutoTimezone: true, AutoLanguage: true, BalancedDisplay: true}}
196 s.desktopEntry = fullConfigPath != ""
197 workload := !s.desktopEntry && !clientOnly
198 if s.desktopEntry {
199 if err = importDesktopConnections(filepath.Dir(fullConfigPath), profile); err != nil {
200 return err
201 }
202 s.remote = newDesktopGateway(profile, NewDesktopLocalController(fullConfigPath, exe))
203 } else {
204 s.remote = newRemoteGateway(profile)
205 s.remote.clientOnly = clientOnly
206 }
207 defer s.remote.close()
208 if workload {
209 if err = guestos.RecoverWindowsStorage(context.Background(), profile); err != nil {
210 s.failStorageRecovery(err)
211 }
212 s.macosGuest, err = guestos.LoadMacOSProfile(profile)
213 if err != nil {
214 return err
215 }
216 s.windowsGuest, err = guestos.LoadWindowsProfile(profile)
217 if err != nil {
218 return err
219 }
220 if s.macosGuest != nil && s.windowsGuest != nil {
221 return errors.New("一个配置只能绑定一个客机系统")
222 }
223 if s.windowsGuest != nil {
224 pending, err := guestos.WindowsCloneCleanupPending(profile)
225 if err != nil {
226 return err
227 }
228 if pending {
229 s.windowsGuest = nil
230 }
231 }
232 s.instanceID, err = ensureRemoteInstance(profile)
233 if err != nil {
234 return err
235 }
236 s.account, err = loadLocalAccount(profile)
237 if err != nil {
238 return err
239 }
240 defer s.account.lock()
241 defer func() { returned = errors.Join(returned, s.closeService()) }()
242 if b, e := os.ReadFile(filepath.Join(profile, "workbench.json")); e == nil {
243 // Existing profiles without this field used manual language settings.
244 s.preferences.AutoLanguage = false
245 // Preserve the original density of profiles saved before this setting.
246 s.preferences.BalancedDisplay = false
247 _ = json.Unmarshal(b, &s.preferences)
248 }
249 if !s.storageRecoveryStatus().Required {
250 if err = s.prepareEnvironment(); err != nil {
251 if s.windowsGuest == nil {
252 return err
253 }
254 s.failStorageRecovery(err)
255 }
256 }
257 // Invalid intent keeps the gate paused and its error visible in status.
258 s.restoreNetworkIntent()
259 if s.preferences.Keyboard == "" {
260 s.preferences.Keyboard = defaultKeyboard()
261 }
262 if _, e := os.Stat(configPath); os.IsNotExist(e) {
263 if err = writePrivate(configPath, defaultConfig()); err != nil {
264 return err
265 }
266 }
267 // A previously running VM cannot keep an unmanaged endpoint online.
268 if s.macosGuest != nil {
269 _ = s.closeProxyGate("控制服务已重新连接,外网等待重新检查")
270 } else if cfg, e := loadConfig(configPath); s.windowsGuest == nil && (e != nil || cfg.RequireManagedProxy(profile) != nil) {
271 _ = s.closeProxyGate("尚未配置有效节点,外网保持关闭")
272 }
273 if s.networkPaused && s.windowsGuest == nil {
274 _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网")
275 }
276 s.startMonitors()
277 if err = s.restorePhone(); err != nil {
278 s.phones.status = "无法恢复手机配对,请移除旧记录后重试"
279 }
280 defer s.stopPhone()
281 }
282 s.identity, err = currentController()
283 if err != nil {
284 return err
285 }
286 if err = writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: s.identity}); err != nil {
287 return err
288 }
289 s.controlPublished = true
290 if !workload {
291 defer os.Remove(filepath.Join(profile, "control.json"))
292 }
293 serverErrors := store.Stream("http", "error")
294 defer serverErrors.Close()
295 server := &http.Server{ErrorLog: log.New(serverErrors, "", 0), Handler: s.handler(), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}
296 defer server.Close()
297 shutdownDone := make(chan struct{})
298 var shutdownOnce sync.Once
299 s.shutdown = func() {
300 shutdownOnce.Do(func() {
301 defer close(shutdownDone)
302 s.beginClose()
303 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
304 defer cancel()
305 _ = server.Shutdown(ctx)
306 _ = server.Close()
307 })
308 }
309 signals, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
310 defer stopSignals()
311 serveDone := make(chan struct{})
312 defer close(serveDone)
313 if s.desktopEntry {
314 go s.watchDesktopOwners(serveDone)
315 }
316 go func() {
317 select {
318 case <-signals.Done():
319 s.shutdown()
320 case <-serveDone:
321 }
322 }()
323 err = server.Serve(listener)
324 if errors.Is(err, http.ErrServerClosed) {
325 <-shutdownDone
326 return nil
327 }
328 return err
329}
330func (s *Server) handler() http.Handler {
331 mux := newDiscoverableMux()
332 mux.HandleFunc("GET /api/agent/routes", func(w http.ResponseWriter, r *http.Request) {
333 jsonReply(w, mux.routes())
334 })
335 s.agentRoutes(mux)
336 s.agentNativeRoutes(mux)
337 s.mobileCLIRoutes(mux)
338 s.mobileSurfaceRoutes(mux)
339 mux.HandleFunc("GET /api/mobile-pair", s.phoneStatus)
340 mux.HandleFunc("POST /api/mobile-pair", s.pairPhone)
341 mux.HandleFunc("DELETE /api/mobile-pair", s.removePhone)
342 mux.HandleFunc("POST /api/mobile/device", s.reportPhoneDevice)
343 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { jsonReply(w, map[string]bool{"ready": true}) })
344 mux.HandleFunc("POST /api/launch", func(w http.ResponseWriter, r *http.Request) {
345 if !s.launcherAuthenticated(w, r) {
346 return
347 }
348 jsonReply(w, launchResponse{ConfigPath: s.configPath, ClientOnly: s.clientOnly, DesktopGateway: s.desktopEntry, URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity})
349 })
350 if s.desktopEntry || s.clientOnly {
351 mux.HandleFunc("POST /api/handoff", s.handoffEntry)
352 } else {
353 mux.HandleFunc("POST /api/handoff", s.handoff)
354 mux.HandleFunc("POST /api/desktop-local/trusted-login", s.localTrustedLogin)
355 mux.HandleFunc("POST /api/desktop-local/{action}", s.desktopLocalControl)
356 }
357 if s.desktopEntry {
358 mux.HandleFunc("POST /api/desktop-owner", s.registerDesktopOwner)
359 }
360 mux.HandleFunc("POST /api/session", func(w http.ResponseWriter, r *http.Request) {
361 var v struct {
362 Token string `json:"token"`
363 }
364 if !readJSON(w, r, &v) {
365 return
366 }
367 if !s.consumeTicket(v.Token) {
368 http.Error(w, "访问凭证无效,请从 Cage 应用重新打开。", http.StatusUnauthorized)
369 return
370 }
371 http.SetCookie(w, &http.Cookie{Name: s.cookieName(), Value: s.session, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 86400 * 30})
372 jsonReply(w, map[string]bool{"ok": true})
373 })
374 mux.HandleFunc("GET /api/status", s.status)
375 mux.HandleFunc("GET /api/environment/initialization", s.initialization)
376 mux.HandleFunc("POST /api/environment/initialization", s.initialization)
377 mux.HandleFunc("GET /api/remote/manifest", s.remoteManifest)
378 mux.HandleFunc("GET /api/projects/directories", s.projectDirectories)
379 mux.HandleFunc("POST /api/input", s.remoteInput)
380 mux.HandleFunc("GET /api/diagnostics", s.diagnosticStatus)
381 mux.HandleFunc("POST /api/diagnostics/events", s.diagnosticEvent)
382 mux.HandleFunc("GET /api/diagnostics/export", s.diagnosticExport)
383 mux.HandleFunc("GET /api/claude-accounts", s.listClaudeAccounts)
384 mux.HandleFunc("POST /api/claude-accounts", s.mutateClaudeAccounts)
385 mux.HandleFunc("GET /api/vault", s.vaultList)
386 mux.HandleFunc("POST /api/vault", s.vaultMutation)
387 mux.HandleFunc("POST /api/vault/browser", s.vaultBrowser)
388 mux.HandleFunc("GET /api/account", s.accountStatus)
389 mux.HandleFunc("POST /api/account/{action}", s.accountAction)
390 mux.HandleFunc("GET /api/settings", s.getSettings)
391 mux.HandleFunc("POST /api/projects/open", s.openProject)
392 mux.HandleFunc("POST /api/projects/remove", s.removeProject)
393 mux.HandleFunc("POST /api/projects/client-share", s.guestClientShare)
394 mux.HandleFunc("GET /api/projects/client-share", s.guestClientShare)
395 mux.HandleFunc("GET /api/environment/versions", s.environmentVersions)
396 mux.HandleFunc("GET /api/environment/guest-systems", s.guestInstallation)
397 mux.HandleFunc("GET /api/environment/guest-systems/clone", s.hostClone)
398 mux.HandleFunc("DELETE /api/environment/guest-systems", s.guestInstallation)
399 mux.HandleFunc("POST /api/environment/guest-systems/activate", s.guestInstallation)
400 mux.HandleFunc("GET /api/environment/storage", s.environmentStorage)
401 mux.HandleFunc("POST /api/environment/storage", s.environmentStorage)
402 mux.HandleFunc("POST /api/environment/storage/recover", s.recoverEnvironmentStorage)
403 mux.HandleFunc("GET /api/environment/resources", s.resourceStatus)
404 mux.HandleFunc("POST /api/environment/resources", s.applyResources)
405 mux.HandleFunc("POST /api/environment/update", s.updateEnvironment)
406 mux.HandleFunc("POST /api/environment/tools", s.updateEnvironmentTools)
407 mux.HandleFunc("GET /api/host/git", s.hostGit)
408 mux.HandleFunc("POST /api/host/git", s.enableHostGit)
409 mux.HandleFunc("GET /api/appearance", s.getAppearance)
410 mux.HandleFunc("GET /api/favorites", s.serveFavorites)
411 mux.HandleFunc("POST /api/favorites", s.serveFavorites)
412 mux.HandleFunc("POST /api/appearance", s.saveAppearance)
413 mux.HandleFunc("GET /api/appearance/codex", s.codexAppearance)
414 mux.HandleFunc("POST /api/settings/probe", s.probe)
415 mux.HandleFunc("GET /api/proxy", s.proxyStatus)
416 mux.HandleFunc("POST /api/proxy/delay", s.proxyDelay)
417 mux.HandleFunc("GET /api/proxy/connections", s.proxyConnections)
418 mux.HandleFunc("GET /api/proxy/logs", s.proxyLogs)
419 mux.HandleFunc("POST /api/proxy/{action}", s.proxyMutation)
420 mux.HandleFunc("POST /api/settings", s.saveSettings)
421 mux.HandleFunc("POST /api/restore", s.restore)
422 mux.HandleFunc("POST /api/start", s.start)
423 mux.HandleFunc("POST /api/stop", s.stop)
424 mux.HandleFunc("POST /api/safety/check", s.safetyCheck)
425 mux.HandleFunc("POST /api/safety/close", s.pauseNetwork)
426 mux.HandleFunc("GET /api/safety/report", s.safetyExport)
427 mux.HandleFunc("GET /api/tailscale", s.tailnet)
428 mux.HandleFunc("POST /api/tailscale/{action}", s.tailnet)
429 mux.HandleFunc("GET /api/browser/tabs", s.browser)
430 mux.HandleFunc("GET /api/browser/events", s.browserEvents)
431 mux.HandleFunc("POST /api/browser/clipboard", s.browserClipboard)
432 mux.HandleFunc("GET /api/browser/preferences", s.browserPreferences)
433 mux.HandleFunc("POST /api/browser/preferences", s.browserPreferences)
434 mux.HandleFunc("POST /api/browser/extensions/upload", s.browserExtensionUpload)
435 mux.HandleFunc("GET /api/client/browser-extensions", s.localBrowserExtensions)
436 mux.HandleFunc("POST /api/client/browser-extensions", s.localBrowserExtensions)
437 mux.HandleFunc("POST /api/browser/{action}", s.browser)
438 mux.HandleFunc("POST /api/input/image", s.imageInput)
439 mux.HandleFunc("POST /api/input/text", s.textInput)
440 mux.HandleFunc("POST /api/input/paste/start", s.pasteInputStart)
441 mux.HandleFunc("POST /api/input/paste/cancel", s.pasteInputCancel)
442 mux.HandleFunc("POST /api/input/files/{action}", s.fileInputAction)
443 mux.HandleFunc("POST /api/input/files/{target}/{id}", s.fileInputUpload)
444 mux.HandleFunc("GET /api/input/files/desktop/requests", s.desktopFileRequests)
445 mux.HandleFunc("POST /api/input/files/desktop/open", s.desktopFileOpenAction)
446 mux.HandleFunc("POST /api/browser/files/uploads/{id}", s.browserUpload)
447 mux.HandleFunc("GET /api/browser/files/downloads/{id}", s.browserDownload)
448 mux.HandleFunc("GET /api/browser/files/downloads/{id}/{action}", s.browserDownload)
449 mux.HandleFunc("GET /api/browser/files/saved", s.savedBrowserDownloads)
450 mux.HandleFunc("GET /api/vnc-credentials", func(w http.ResponseWriter, r *http.Request) {
451 s.mu.Lock()
452 defer s.mu.Unlock()
453 if !s.ready {
454 http.Error(w, "环境尚未就绪", 409)
455 return
456 }
457 jsonReply(w, map[string]any{"password": s.credentials.VNCPassword, "display_scale": s.credentials.DisplayScale, "dynamic_scale": s.credentials.DynamicScale})
458 })
459 mux.HandleFunc("GET /api/vnc", s.vnc)
460 mux.HandleFunc("GET /api/claude-desktop", s.claudeDesktopStatus)
461 mux.HandleFunc("GET /api/claude-desktop/vnc-credentials", s.claudeDesktopCredentials)
462 mux.HandleFunc("GET /api/claude-desktop/vnc", s.claudeDesktopVNC)
463 mux.HandleFunc("POST /api/claude-desktop/resize", s.claudeDesktopResize)
464 mux.HandleFunc("POST /api/claude-desktop/{action}", s.claudeDesktopAction)
465 if s.macosGuest != nil {
466 mux.HandleFunc("POST /api/macos/first-setup", s.macOSLoginWindow)
467 mux.HandleFunc("POST /api/macos/login", s.macOSLoginWindow)
468 mux.HandleFunc("POST /api/macos/maintenance", s.macOSLoginWindow)
469 s.registerMacOSClaudeRoutes(mux)
470 s.registerMacOSBrowserRoutes(mux)
471 mux.HandleFunc("POST /api/macos/project-approval", s.macOSProjectApproval)
472 mux.HandleFunc("POST /api/macos/exit-policy", s.bindMacOSExit)
473 }
474 mux.HandleFunc("GET /api/terminals", s.listTerminals)
475 mux.HandleFunc("GET /api/audio", s.audio)
476 mux.HandleFunc("GET /api/clipboard", s.sharedClipboard)
477 mux.HandleFunc("POST /api/clipboard/copy", s.clipboardCopy)
478 mux.HandleFunc("POST /api/clipboard/files", s.clipboardArchive)
479 mux.HandleFunc("GET /api/clipboard/files/{id}", s.clipboardArchive)
480 mux.HandleFunc("DELETE /api/clipboard/files/{id}", s.clipboardArchive)
481 mux.HandleFunc("POST /api/terminals", s.newTerminal)
482 mux.HandleFunc("DELETE /api/terminals/{id}", s.closeTerminal)
483 mux.HandleFunc("POST /api/terminals/{id}/login-link", s.terminalLoginLink)
484 mux.HandleFunc("POST /api/terminals/{id}/metadata", s.terminalSessionMetadata)
485 mux.HandleFunc("GET /api/terminals/{id}/stream", s.terminalStream)
486 web, _ := fs.Sub(assets, "web")
487 mux.Handle("GET /", http.FileServer(http.FS(web)))
488 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
489 origin, err := url.Parse(s.origin)
490 if err != nil || r.Host != origin.Host {
491 http.Error(w, "Host refused", 403)
492 return
493 }
494 w.Header().Set("Cache-Control", "no-store")
495 w.Header().Set("X-Content-Type-Options", "nosniff")
496 w.Header().Set("Referrer-Policy", "no-referrer")
497 w.Header().Set("X-Frame-Options", "DENY")
498 w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://"+origin.Host+"; img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
499 if (r.Method != "GET" && r.Method != "HEAD") || strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
500 if r.Header.Get("Origin") != s.origin {
501 http.Error(w, "Origin refused", 403)
502 return
503 }
504 }
505 // Launcher-token routes are handled only by this listener, never by a
506 // selected workload. They perform their own authentication.
507 if strings.HasPrefix(r.URL.Path, "/api/desktop-local/") || r.URL.Path == "/api/desktop-owner" {
508 if (strings.HasPrefix(r.URL.Path, "/api/desktop-local/") && (s.desktopEntry || s.clientOnly)) || (r.URL.Path == "/api/desktop-owner" && !s.desktopEntry) {
509 http.NotFound(w, r)
510 return
511 }
512 mux.ServeHTTP(w, r)
513 return
514 }
515 if r.URL.Path == "/api/remote/manifest" && (s.desktopEntry || s.clientOnly) {
516 http.NotFound(w, r)
517 return
518 }
519 if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api/session" && r.URL.Path != "/api/launch" && r.URL.Path != "/api/handoff" {
520 c, e := r.Cookie(s.cookieName())
521 if e != nil || !equalSecret(c.Value, s.session) {
522 http.Error(w, "请从 Cage 应用重新打开工作台", 401)
523 return
524 }
525 }
526 if strings.HasPrefix(r.URL.Path, "/api/agent/native") || r.URL.Path == "/api/agent/routes" {
527 mux.ServeHTTP(w, r)
528 return
529 }
530 if s.windowsGuest != nil && !windowsWorkbenchRoute(r.URL.Path) {
531 s.windowsUnavailable(w)
532 return
533 }
534 if s.macosGuest != nil && (!macOSWorkbenchRoute(r.URL.Path) || s.macSetupPending() && !macOSSetupRoute(r.URL.Path)) {
535 http.Error(w, "此功能尚未接入 macOS 客机", http.StatusConflict)
536 return
537 }
538 if strings.HasPrefix(r.URL.Path, "/api/mobile/") {
539 // Device trust is scoped to this host. Never forward a paired phone
540 // into a different host selected by the desktop SSH client.
541 if s.desktopEntry && !s.clientOnly && s.remote != nil && s.remote.desktop != nil && r.Header.Get(connectionHeader) != "" {
542 // The desktop's own viewer pins the selected local workload's
543 // connection generation. routeRemote checks the acquired target.
544 if s.routeRemote(w, r) {
545 return
546 }
547 }
548 if s.clientOnly || s.desktopEntry {
549 http.Error(w, "请连接运行 Cage 环境的主机", http.StatusConflict)
550 return
551 }
552 } else if s.macosGuest == nil && s.windowsGuest == nil && s.routeRemote(w, r) {
553 return
554 }
555 ctx, finish, err := s.beginActivity(r.Context())
556 if err != nil {
557 http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable)
558 return
559 }
560 defer finish()
561 r = r.WithContext(ctx)
562 accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/")
563 bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" || r.URL.Path == "/api/remote/manifest"
564 var phoneRoom context.Context
565 if (s.windowsGuest != nil || s.macosGuest != nil) && strings.HasPrefix(r.URL.Path, "/api/") && !bootstrapRoute && !s.hasTrustedView(r) {
566 phoneRoom = s.nativePhoneRoom(r)
567 if phoneRoom == nil {
568 http.Error(w, "请通过本机 Cage 窗口或当前配对手机打开客机", http.StatusForbidden)
569 return
570 }
571 }
572 if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !strings.HasPrefix(r.URL.Path, "/api/diagnostics") && !(r.Method == "GET" && r.URL.Path == "/api/appearance") {
573 epoch, unlocked := s.account.accessFor(s.hasTrustedView(r))
574 if !unlocked {
575 http.Error(w, "Cage 已锁定,请先登录", http.StatusLocked)
576 return
577 }
578 ctx, cancel := context.WithCancel(r.Context())
579 if strings.HasPrefix(r.URL.Path, "/api/mobile/") || strings.HasPrefix(r.URL.Path, "/api/cli/") {
580 ctx = context.WithValue(ctx, mobileEpochKey{}, epoch)
581 }
582 stop := context.AfterFunc(epoch, cancel)
583 defer func() { stop(); cancel() }()
584 if phoneRoom != nil {
585 stopPhone := context.AfterFunc(phoneRoom, cancel)
586 defer stopPhone()
587 }
588 r = r.WithContext(ctx)
589 }
590 defer interruptHTTPOnCancel(w, r)()
591 response := &diagnosticResponse{ResponseWriter: w}
592 w = response
593 defer func() {
594 if response.status >= 400 && r.URL.Path != "/api/diagnostics/events" {
595 _ = diagnostics.New(s.profile).Record("warn", "http", fmt.Sprintf("%s %s returned %d", r.Method, r.Pattern, response.status))
596 }
597 }()
598 defer func() {
599 if failure := recover(); failure != nil {
600 diagnostics.Log("error", "http", fmt.Sprintf("handler panic: %v\n%s", failure, debug.Stack()))
601 panic(failure)
602 }
603 }()
604 if !storageRecoveryRoute(r) {
605 if err := s.requireStorageReady(); err != nil {
606 http.Error(w, err.Error(), http.StatusConflict)
607 return
608 }
609 }
610 mux.ServeHTTP(w, r)
611 })
612}
613func readJSON(w http.ResponseWriter, r *http.Request, v any, limits ...int64) bool {
614 if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
615 http.Error(w, "需要 JSON 请求", 415)
616 return false
617 }
618 limit := int64(64 << 10)
619 if len(limits) > 0 {
620 limit = limits[0]
621 }
622 d := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
623 d.DisallowUnknownFields()
624 if err := d.Decode(v); err != nil {
625 http.Error(w, "请求格式无效", 400)
626 return false
627 }
628 var extra any
629 if d.Decode(&extra) != io.EOF {
630 http.Error(w, "请求格式无效", 400)
631 return false
632 }
633 return true
634}
635func jsonReply(w http.ResponseWriter, v any) {
636 w.Header().Set("Content-Type", "application/json; charset=utf-8")
637 _ = json.NewEncoder(w).Encode(v)
638}
639func requestError(w http.ResponseWriter, err error) {
640 diagnostics.Log("error", "api", fmt.Sprintf("%v; cause=%v", err, errors.Unwrap(err)))
641 http.Error(w, err.Error(), http.StatusBadRequest)
642}
643func (s *Server) status(w http.ResponseWriter, r *http.Request) {
644 if s.windowsGuest != nil && !s.storageRecoveryStatus().Required {
645 s.refreshWindowsComponents()
646 }
647 projects, err := s.projectPaths()
648 if err != nil {
649 requestError(w, errors.New("无法读取项目列表,请检查项目配置"))
650 return
651 }
652 running := s.vmRunning()
653 s.mu.Lock()
654 defer s.mu.Unlock()
655 _, e := os.Stat(filepath.Join(s.profile, "previous-profile.json"))
656 projectError := ""
657 if len(s.projectErrors) > 0 {
658 projectError = "部分项目文件夹尚未连接,环境和浏览器可继续使用。"
659 }
660 if m := s.clientMounts[s.clientWorkspace]; s.clientWorkspace != "" && (m == nil || !m.live()) {
661 projectError = "当前本机项目已断开,请重新共享或选择其他项目。"
662 }
663 view := map[string]any{
664 "projects": projects, "ready": s.ready, "vm_running": running,
665 "workspace": s.workspaceLocked(), "environment_workspace": s.workspaceLocked() == s.environmentDir(), "environment_directory": s.environmentDir(),
666 "environment_identity_directory": cage.EnvironmentIdentityDir(s.profile),
667 "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors,
668 "storage_recovery": s.storageRecoveryStatusLocked(),
669 "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(),
670 "location": s.location, "network_error": s.currentNetworkErrorLocked(), "can_restore": e == nil,
671 "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError,
672 }
673 if s.windowsGuest != nil {
674 view["guest_system"] = guestos.Windows11
675 view["guest_capabilities"] = s.windowsCapabilitiesLocked()
676 view["location"] = nil
677 if s.safety.Gate == nil && view["network_error"] == "" {
678 view["network_error"] = "Windows 客机网络组件尚未连接,外网保持关闭"
679 }
680 } else if s.macosGuest != nil {
681 view["guest_system"] = guestos.MacOS
682 } else if system, err := s.installedLinuxSystem(); err != nil {
683 view["guest_system_error"] = err.Error()
684 } else if system != guestos.Debian13 {
685 view["guest_system"] = system
686 }
687 jsonReply(w, view)
688}
689func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) {
690 c, err := loadConfig(s.configPath)
691 if err != nil {
692 requestError(w, err)
693 return
694 }
695 s.mu.Lock()
696 p := s.preferences
697 s.mu.Unlock()
698 jsonReply(w, settingsView(c, p))
699}
700func (s *Server) proposed(w http.ResponseWriter, r *http.Request) (savedProfile, bool) {
701 var input Settings
702 // Older clients omit preferences introduced after their release.
703 s.mu.Lock()
704 input.MobileRelay = s.preferences.MobileRelay
705 input.BalancedDisplay = s.preferences.BalancedDisplay
706 input.BrowserHomeURL = browserHomeURL(s.preferences)
707 s.mu.Unlock()
708 if !readJSON(w, r, &input) {
709 return savedProfile{}, false
710 }
711 old, err := loadConfig(s.configPath)
712 if err != nil {
713 requestError(w, err)
714 return savedProfile{}, false
715 }
716 c, p, err := proposedSettings(input, old, s.profile)
717 if err != nil {
718 requestError(w, err)
719 return savedProfile{}, false
720 }
721 return savedProfile{c, p}, true
722}
723func (s *Server) probe(w http.ResponseWriter, r *http.Request) {
724 v, ok := s.proposed(w, r)
725 if !ok {
726 return
727 }
728 if err := v.Config.RequireManagedProxy(s.profile); err != nil {
729 requestError(w, err)
730 return
731 }
732 loc, err := probeLocation(r.Context(), v.Config)
733 if finishErr := s.finishLocationProbe(v.Config, loc, err); finishErr != nil {
734 requestError(w, finishErr)
735 return
736 }
737 if err != nil {
738 requestError(w, err)
739 return
740 }
741 jsonReply(w, loc)
742}
743func (s *Server) saveSettings(w http.ResponseWriter, r *http.Request) {
744 v, ok := s.proposed(w, r)
745 if !ok {
746 return
747 }
748 kind := "settings"
749 old, err := loadConfig(s.configPath)
750 s.mu.Lock()
751 previous := s.preferences
752 s.mu.Unlock()
753 if err == nil && old == v.Config && previous.AutoTimezone == v.Preferences.AutoTimezone && previous.AutoLanguage == v.Preferences.AutoLanguage && previous.Workspace != v.Preferences.Workspace {
754 kind = "project"
755 }
756 s.launch(w, kind, func() error {
757 s.mu.Lock()
758 v.Preferences.BrowserHomeURL = s.preferences.BrowserHomeURL
759 s.mu.Unlock()
760 return s.apply(v, true)
761 })
762}
763func (s *Server) restore(w http.ResponseWriter, r *http.Request) {
764 var v savedProfile
765 b, e := os.ReadFile(filepath.Join(s.profile, "previous-profile.json"))
766 if e != nil || json.Unmarshal(b, &v) != nil {
767 requestError(w, errors.New("没有可恢复的配置"))
768 return
769 }
770 s.launch(w, "restore", func() error {
771 if err := s.apply(v, false); err != nil {
772 return err
773 }
774 return s.startEnvironment(false)
775 })
776}
777func (s *Server) start(w http.ResponseWriter, r *http.Request) {
778 var input guestInstallRequest
779 if r.ContentLength != 0 && !readJSON(w, r, &input) {
780 return
781 }
782 if s.windowsGuest != nil {
783 if input.System != "" && input.System != guestos.Windows11 {
784 http.Error(w, "此配置已绑定 Windows 客机", http.StatusConflict)
785 return
786 }
787 s.launch(w, "start", s.startWindowsGuest)
788 return
789 }
790 if s.macosGuest != nil {
791 if input.System != "" && input.System != guestos.MacOS {
792 http.Error(w, "此配置已绑定 macOS 客机", http.StatusConflict)
793 return
794 }
795 s.launch(w, "start", s.startMacOSGuest)
796 return
797 }
798 if input.System == guestos.MacOS || input.System == guestos.Windows11 || input.CloneKey != "" {
799 s.beginGuestInstall(w, r, input)
800 return
801 }
802 pending, err := guestos.LoadInstallation(s.profile)
803 if err != nil || (pending != nil && !hostimage.IsLinux(pending.System)) {
804 http.Error(w, "已有原生客户机安装,请继续原安装", http.StatusConflict)
805 return
806 }
807 if pending != nil && input.System != "" && pending.System != input.System {
808 http.Error(w, "此环境已绑定所选 Linux 系统,请继续原安装", http.StatusConflict)
809 return
810 }
811 if pending != nil {
812 input.System = pending.System
813 s.beginGuestInstall(w, r, input)
814 return
815 }
816 boundSystem, err := s.installedLinuxSystem()
817 if err != nil {
818 requestError(w, err)
819 return
820 }
821 if input.System != "" && input.System != boundSystem {
822 if canInstallCatalogLinux(input.System) {
823 s.beginGuestInstall(w, r, input)
824 } else {
825 http.Error(w, "当前环境无法启动所选客户机系统,请保留原环境并重新检查安装选择", http.StatusConflict)
826 }
827 return
828 }
829 s.launch(w, "start", func() error {
830 if err := s.prepareEnvironment(); err != nil {
831 return err
832 }
833 return s.startEnvironment(true)
834 })
835}
836func (s *Server) stop(w http.ResponseWriter, r *http.Request) {
837 s.requestStop(w, false)
838}
839
840func (s *Server) requestStop(w http.ResponseWriter, logout bool) {
841 if err := s.requireStorageReady(); err != nil {
842 http.Error(w, err.Error(), http.StatusConflict)
843 return
844 }
845 for _, name := range []string{cage.InstanceName(s.profile, s.environmentDir()), "base-building"} {
846 if owner := cage.InstanceJobID(filepath.Join(s.profile, "state"), name); owner != "" {
847 _ = cage.RequestJobStop(s.profile, owner)
848 }
849 }
850 jobID := s.jobs.cancelRunning()
851 if jobID != "" {
852 _ = cage.RequestJobStop(s.profile, jobID)
853 }
854 if s.macosGuest != nil {
855 // Stopping the guest revokes its current grant. A user's saved pause
856 // remains distinct so the next Mac start can honor the same intent.
857 _ = s.revokeNetworkNow("正在停止环境", false)
858 } else if s.windowsGuest == nil {
859 _ = s.pauseNetworkNow("正在停止环境")
860 }
861 kind := "stop"
862 if logout {
863 kind = "logout"
864 }
865 s.launch(w, kind, s.stopEnvironment)
866}
867
868func (s *Server) cookieName() string { u, _ := url.Parse(s.origin); return cookieName + "_" + u.Port() }
869
870func (s *Server) issueTicket() string {
871 s.mu.Lock()
872 defer s.mu.Unlock()
873 if s.tickets == nil {
874 s.tickets = map[string]time.Time{}
875 }
876 for token, expires := range s.tickets {
877 if time.Now().After(expires) {
878 delete(s.tickets, token)
879 }
880 }
881 token := randomToken()
882 s.tickets[token] = time.Now().Add(time.Minute)
883 return token
884}
885func (s *Server) consumeTicket(token string) bool {
886 s.mu.Lock()
887 defer s.mu.Unlock()
888 expires, ok := s.tickets[token]
889 delete(s.tickets, token)
890 return ok && time.Now().Before(expires)
891}