跳到主要内容

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

浏览文件

cloud_guest_share.go

232 行 · 7.0 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "io"
7 "net/http"
8 "regexp"
9 "runtime"
10 "slices"
11 "sort"
12 "strings"
13 "time"
14
15 "al.essio.dev/pkg/shellescape"
16 "github.com/sylvinus/agent-vm/internal/containerenv"
17 "golang.org/x/net/http/httpguts"
18)
19
20// This namespace exists only in the Linux guest. Never resolve its paths on
21// the server host or persist them as grants across connections.
22const clientMountRoot = "/run/cage-client-projects"
23
24var clientMountID = regexp.MustCompile(`^[0-9a-f]{32}$`)
25var errClientMountGone = errors.New("本机项目共享已断开,请在本机重新选择文件夹")
26
27type guestClientMount struct {
28 ctx context.Context
29 cancel context.CancelFunc
30 done chan struct{}
31 ready bool // protected by Server.mu
32}
33
34// Caller holds Server.mu. Cancellation closes admission before unmount cleanup.
35func (m *guestClientMount) live() bool { return m.ready && m.ctx.Err() == nil }
36
37func isClientMountPath(path string) bool {
38 return path == clientMountRoot || strings.HasPrefix(path, clientMountRoot+"/")
39}
40
41func (s *Server) clientMountWorkspace(path string) (string, error) {
42 s.mu.Lock()
43 defer s.mu.Unlock()
44 if mount := s.clientMounts[path]; mount != nil && mount.live() {
45 return path, nil
46 }
47 return "", errClientMountGone
48}
49
50func (s *Server) appendClientMounts(paths []string) []string {
51 s.mu.Lock()
52 defer s.mu.Unlock()
53 var live []string
54 for path, mount := range s.clientMounts {
55 if mount.live() && !slices.Contains(paths, path) {
56 live = append(live, path)
57 }
58 }
59 sort.Strings(live)
60 return append(paths, live...)
61}
62
63func (s *Server) closeClientMounts() {
64 s.mu.Lock()
65 var mounts []*guestClientMount
66 for _, m := range s.clientMounts {
67 m.cancel()
68 mounts = append(mounts, m)
69 }
70 s.mu.Unlock()
71 for _, m := range mounts {
72 <-m.done
73 }
74}
75
76// After a controller crash a disconnected FUSE mount may outlive its stream.
77// Only retire exact Cage names in the guest's reserved, root-owned directory.
78// rmdir preserves any unexpected nonempty directory.
79func (s *Server) recoverClientMounts(ctx context.Context) error {
80 s.mu.Lock()
81 initialized := s.clientMounts != nil
82 s.mu.Unlock()
83 if initialized {
84 return nil
85 }
86 const recoverScript = `set -eu
87root=` + clientMountRoot + `
88[ ! -L "$root" ] || exit 1
89[ -d "$root" ] || exit 0
90for p in "$root"/*; do
91 [[ ${p##*/} =~ ^[a-f0-9]{32}$ ]] || continue
92 [ ! -L "$p" ] || continue
93 kind=$(findmnt -rn --nocanonicalize -o FSTYPE --mountpoint "$p") || kind=
94 case "$kind" in
95 fuse.sshfs) sudo -n umount -l -- "$p";;
96 "") ;;
97 *) continue;;
98 esac
99 sudo -n rmdir -- "$p" || true
100done`
101 if _, err := s.guest(ctx, recoverScript); err != nil {
102 return errors.New("无法清理上次连接遗留的本机项目挂载")
103 }
104 s.mu.Lock()
105 if s.clientMounts == nil {
106 s.clientMounts = make(map[string]*guestClientMount)
107 }
108 s.mu.Unlock()
109 return nil
110}
111
112func (s *Server) guestClientShare(w http.ResponseWriter, r *http.Request) {
113 if runtime.GOOS != "linux" || !containerenv.Configured(s.profile) {
114 http.NotFound(w, r)
115 return
116 }
117 id := r.URL.Query().Get("id")
118 if !clientMountID.MatchString(id) {
119 http.Error(w, "本机项目标识无效", http.StatusBadRequest)
120 return
121 }
122 path := clientMountRoot + "/" + id
123 if r.Method == http.MethodGet {
124 if _, err := s.clientMountWorkspace(path); err != nil {
125 http.Error(w, "本机项目尚未连接", http.StatusConflict)
126 return
127 }
128 jsonReply(w, map[string]string{"workspace": path})
129 return
130 }
131 if !httpguts.HeaderValuesContainsToken(r.Header.Values("Connection"), "upgrade") || !strings.EqualFold(r.Header.Get("Upgrade"), "cage-sftp-v1") || r.ContentLength != 0 {
132 http.Error(w, "需要项目共享连接", http.StatusBadRequest)
133 return
134 }
135 if !s.op.TryLock() {
136 http.Error(w, "环境正在处理其他操作", http.StatusConflict)
137 return
138 }
139 ctx, cancel := context.WithCancel(r.Context())
140 defer cancel()
141 mount := &guestClientMount{ctx: ctx, cancel: cancel, done: make(chan struct{})}
142 s.mu.Lock()
143 available := s.ready && !s.closing && len(s.clientMounts) < 16 && s.clientMounts[path] == nil && !s.busy()
144 if available {
145 if s.clientMounts == nil {
146 s.clientMounts = make(map[string]*guestClientMount)
147 }
148 s.clientMounts[path] = mount
149 }
150 s.mu.Unlock()
151 s.op.Unlock()
152 if !available {
153 http.Error(w, "环境未就绪、共享已存在或已达共享上限", http.StatusConflict)
154 return
155 }
156 defer func() {
157 s.mu.Lock()
158 delete(s.clientMounts, path)
159 // Keep a revoked active selection until another project is selected.
160 // New tasks must fail, not silently start in the previous cloud folder.
161 s.mu.Unlock()
162 close(mount.done)
163 }()
164
165 // A disconnected mount exposes an inaccessible underlying directory until
166 // teardown removes it. Never let an old cwd accept writes into the cloud.
167 target := shellescape.Quote(path)
168 setup, finishSetup := context.WithTimeout(ctx, 10*time.Second)
169 _, err := s.guest(setup, "sudo -n install -d -m 0755 "+clientMountRoot+" && sudo -n mkdir -m 000 -- "+target)
170 finishSetup()
171 if err != nil {
172 http.Error(w, "无法准备云端容器挂载位置", http.StatusConflict)
173 return
174 }
175 defer func() {
176 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
177 defer cancel()
178 _, _ = s.guest(ctx, "if findmnt -rn --nocanonicalize --mountpoint "+target+" >/dev/null; then sudo -n umount -l -- "+target+"; fi; sudo -n rmdir -- "+target)
179 }()
180 conn, buffer, err := http.NewResponseController(w).Hijack()
181 if err != nil {
182 http.Error(w, "无法建立项目共享数据流", http.StatusServiceUnavailable)
183 return
184 }
185 defer conn.Close()
186 stopClose := context.AfterFunc(ctx, func() { _ = conn.Close() })
187 defer stopClose()
188 if _, err = buffer.WriteString("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: cage-sftp-v1\r\n\r\n"); err != nil || buffer.Flush() != nil {
189 return
190 }
191 // sshfs runs inside the guest. Its only SFTP transport is this stream.
192 // Keep normal mmap/read-ahead support for compilers and search tools.
193 // Present files as the guest user so ownership checks (e.g. Git) work
194 // when the workstation uses a different UID or Windows ACLs.
195 script := "exec sudo -n sshfs -f :/ " + target + ` -o "slave,allow_other,cache=no,nodev,nosuid,uid=$(id -u),gid=$(id -g)"`
196 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script)
197 cmd.Stdout = conn
198 input, err := cmd.StdinPipe()
199 if err != nil {
200 return
201 }
202 defer input.Close()
203 if err = cmd.Start(); err != nil {
204 return
205 }
206 ingressDone := make(chan struct{})
207 go func() {
208 defer close(ingressDone)
209 _, _ = io.Copy(input, buffer.Reader)
210 cancel()
211 }()
212 // Wait for the actual kernel mount and a successful SFTP stat before
213 // admitting any terminal, editor or Claude session to this workspace.
214 probed := make(chan struct{})
215 go func() {
216 defer close(probed)
217 probe, end := context.WithTimeout(ctx, 15*time.Second)
218 defer end()
219 verify := "until [ \"$(findmnt -n -o FSTYPE --mountpoint " + target + ")\" = fuse.sshfs ] && stat -- " + target + "/. >/dev/null 2>&1; do sleep 0.1; done"
220 if _, err := s.guest(probe, verify); err != nil {
221 cancel()
222 return
223 }
224 s.mu.Lock()
225 mount.ready = ctx.Err() == nil
226 s.mu.Unlock()
227 }()
228 _ = cmd.Wait()
229 cancel()
230 <-ingressDone
231 <-probed
232}