跳到主要内容

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

浏览文件

gate_control.go

268 行 · 8.5 KB历史下载
1package cage
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/subtle"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "io"
12 "net"
13 "net/http"
14 "os"
15 "path/filepath"
16 "sync"
17 "time"
18
19 "github.com/sylvinus/agent-vm/internal/host"
20)
21
22const gateRecordName = "cage-gate.json"
23
24type gateRecord struct {
25 Socket string `json:"socket"`
26 Token string `json:"token"`
27 RunID string `json:"run_id"`
28}
29
30type gateCommand struct {
31 Action string `json:"action"`
32 Fault bool `json:"fault,omitempty"`
33 Reason string `json:"reason,omitempty"`
34 Report *SafetyReport `json:"report,omitempty"`
35 ReportID string `json:"report_id,omitempty"`
36}
37
38// StartGateControl publishes an authenticated Unix endpoint in host-private
39// storage. It creates no TCP listener or guest-visible control credential.
40func StartGateControl(configPath, instanceDir string, gate *EgressGate) (func(), error) {
41 dir, err := os.MkdirTemp(gateTempDir(), "cage-gate-")
42 if err != nil {
43 return nil, err
44 }
45 if err = host.EnsurePrivateDir(dir); err != nil {
46 os.RemoveAll(dir)
47 return nil, err
48 }
49 socket := filepath.Join(dir, "control.sock")
50 listener, err := net.Listen("unix", socket)
51 if err != nil {
52 os.RemoveAll(dir)
53 return nil, err
54 }
55 if err = host.ProtectFile(socket); err != nil {
56 listener.Close()
57 os.RemoveAll(dir)
58 return nil, err
59 }
60 var token [32]byte
61 if _, err = rand.Read(token[:]); err != nil {
62 listener.Close()
63 os.RemoveAll(dir)
64 return nil, err
65 }
66 record := gateRecord{Socket: socket, Token: hex.EncodeToString(token[:]), RunID: gate.Status().RunID}
67 data, _ := json.Marshal(record)
68 temporary, err := os.CreateTemp(instanceDir, ".gate-*")
69 if err != nil {
70 listener.Close()
71 os.RemoveAll(dir)
72 return nil, err
73 }
74 defer os.Remove(temporary.Name())
75 if err = host.ProtectFile(temporary.Name()); err != nil {
76 temporary.Close()
77 listener.Close()
78 os.RemoveAll(dir)
79 return nil, err
80 }
81 _, err = temporary.Write(data)
82 if closeErr := temporary.Close(); err == nil {
83 err = closeErr
84 }
85 if err == nil {
86 err = os.Rename(temporary.Name(), filepath.Join(instanceDir, gateRecordName))
87 }
88 if err != nil {
89 listener.Close()
90 os.RemoveAll(dir)
91 return nil, err
92 }
93 server := &http.Server{ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 8192}
94 server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
95 w.Header().Set("Cache-Control", "no-store")
96 w.Header().Set("Content-Type", "application/json")
97 if r.Host != "cage" || r.Header.Get("Origin") != "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+record.Token)) != 1 {
98 w.WriteHeader(http.StatusForbidden)
99 return
100 }
101 var operationError error
102 if r.Method == "POST" && r.URL.Path == "/control" {
103 var command gateCommand
104 decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10))
105 decoder.DisallowUnknownFields()
106 if decoder.Decode(&command) != nil || len(command.Reason) > 200 {
107 w.WriteHeader(400)
108 return
109 }
110 if command.Action == "check" || command.Action == "grant" || command.Action == "renew" || command.Action == "proxy-revision" {
111 cfg, e := Load(configPath)
112 if e == nil {
113 e = cfg.RequireManagedProxy(filepath.Dir(configPath))
114 }
115 if e != nil {
116 gate.Close("代理节点未应用,外网保持关闭")
117 w.WriteHeader(409)
118 _ = json.NewEncoder(w).Encode(map[string]string{"error": e.Error()})
119 return
120 }
121 }
122 switch command.Action {
123 case "proxy-revision":
124 cfg, e := Load(configPath)
125 if e != nil {
126 operationError = e
127 } else {
128 operationError = gate.SyncProxyRevision(cfg)
129 if operationError == nil {
130 operationError = cfg.RecordRunningAt(instanceDir)
131 }
132 }
133 case "check":
134 operationError = gate.BeginCheck()
135 case "fault":
136 operationError = gate.SetFault(command.Fault)
137 case "grant":
138 if command.Report == nil {
139 operationError = errors.New("检测报告缺失")
140 } else {
141 operationError = gate.Grant(*command.Report)
142 }
143 case "renew":
144 operationError = gate.Renew(command.ReportID)
145 case "close":
146 gate.Close(command.Reason)
147 default:
148 w.WriteHeader(400)
149 return
150 }
151 } else if r.Method != "GET" || r.URL.Path != "/status" {
152 w.WriteHeader(404)
153 return
154 }
155 if operationError != nil {
156 w.WriteHeader(409)
157 _ = json.NewEncoder(w).Encode(map[string]string{"error": operationError.Error()})
158 return
159 }
160 _ = json.NewEncoder(w).Encode(gate.Status())
161 })
162 ctx, cancel := context.WithCancel(context.Background())
163 var once sync.Once
164 stop := func() {
165 once.Do(func() { cancel(); gate.Close("网络控制服务已停止"); _ = server.Close(); _ = os.RemoveAll(dir) })
166 }
167 go func() { _ = server.Serve(listener); stop() }()
168 go func() {
169 ticker := time.NewTicker(time.Second)
170 defer ticker.Stop()
171 for {
172 select {
173 case <-ctx.Done():
174 return
175 case <-ticker.C:
176 cfg, err := Load(configPath)
177 if err == nil {
178 err = cfg.RequireManagedProxy(filepath.Dir(configPath))
179 }
180 if err != nil || cfg.Fingerprint() != gate.Status().Configuration {
181 gate.Close("配置已变更或无法读取,请重启环境并重新检测")
182 }
183 }
184 }
185 }()
186 return stop, nil
187}
188
189type GateClient struct{ record gateRecord }
190
191func OpenGateClient(instanceDir string) (*GateClient, error) {
192 path := filepath.Join(instanceDir, gateRecordName)
193 if err := host.CheckPrivateFile(path); err != nil {
194 return nil, errors.New("网络门槛控制记录不可用,请停止并重启环境")
195 }
196 data, err := os.ReadFile(path)
197 if err != nil || len(data) > 4096 {
198 return nil, errors.New("网络门槛控制记录不可读")
199 }
200 var record gateRecord
201 if json.Unmarshal(data, &record) != nil || len(record.Token) != 64 || record.RunID == "" || !filepath.IsAbs(record.Socket) {
202 return nil, errors.New("网络门槛控制记录无效")
203 }
204 return &GateClient{record: record}, nil
205}
206
207func (c *GateClient) request(ctx context.Context, command *gateCommand) (GateStatus, error) {
208 var state GateStatus
209 transport := &http.Transport{Proxy: nil, DisableKeepAlives: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
210 return (&net.Dialer{}).DialContext(ctx, "unix", c.record.Socket)
211 }}
212 defer transport.CloseIdleConnections()
213 client := &http.Client{Transport: transport, Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("gate redirect refused") }}
214 method, path := "GET", "/status"
215 var body io.Reader
216 if command != nil {
217 method, path = "POST", "/control"
218 data, err := json.Marshal(command)
219 if err != nil {
220 return state, err
221 }
222 body = bytes.NewReader(data)
223 }
224 req, err := http.NewRequestWithContext(ctx, method, "http://cage"+path, body)
225 if err != nil {
226 return state, err
227 }
228 req.Header.Set("Authorization", "Bearer "+c.record.Token)
229 resp, err := client.Do(req)
230 if err != nil {
231 return state, errors.New("无法连接 VM 外网络门槛控制器")
232 }
233 defer resp.Body.Close()
234 if resp.StatusCode != 200 {
235 var message struct {
236 Error string `json:"error"`
237 }
238 _ = json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&message)
239 if message.Error == "" {
240 message.Error = "网络门槛操作被拒绝"
241 }
242 return state, errors.New(message.Error)
243 }
244 if json.NewDecoder(io.LimitReader(resp.Body, 128<<10)).Decode(&state) != nil || state.RunID != c.record.RunID || state.Policy != SafetyPolicyVersion {
245 return GateStatus{}, errors.New("网络门槛状态不属于当前运行实例")
246 }
247 return state, nil
248}
249
250func (c *GateClient) Status(ctx context.Context) (GateStatus, error) { return c.request(ctx, nil) }
251func (c *GateClient) BeginCheck(ctx context.Context) (GateStatus, error) {
252 return c.request(ctx, &gateCommand{Action: "check"})
253}
254func (c *GateClient) SetFault(ctx context.Context, fault bool) (GateStatus, error) {
255 return c.request(ctx, &gateCommand{Action: "fault", Fault: fault})
256}
257func (c *GateClient) Grant(ctx context.Context, report SafetyReport) (GateStatus, error) {
258 return c.request(ctx, &gateCommand{Action: "grant", Report: &report})
259}
260func (c *GateClient) Renew(ctx context.Context, reportID string) (GateStatus, error) {
261 return c.request(ctx, &gateCommand{Action: "renew", ReportID: reportID})
262}
263func (c *GateClient) Close(ctx context.Context, reason string) (GateStatus, error) {
264 return c.request(ctx, &gateCommand{Action: "close", Reason: reason})
265}
266func (c *GateClient) SyncProxyRevision(ctx context.Context) (GateStatus, error) {
267 return c.request(ctx, &gateCommand{Action: "proxy-revision"})
268}