跳到主要内容

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

浏览文件

operations.go

206 行 · 6.3 KB历史下载
1// Package mobilelink connects a paired mobile client to the mobile
2// operations of a single Cage host. It never exposes the full workbench API.
3package mobilelink
4
5import (
6 "bytes"
7 "context"
8 "errors"
9 "io"
10 "mime"
11 "net/http"
12 "net/url"
13 "regexp"
14 "strconv"
15 "strings"
16 "time"
17)
18
19const (
20 maxRequest = 72 << 10
21 maxResponse = 4 << 20
22 linkOrigin = "https://cage-mobile.invalid"
23)
24
25var sessionPath = regexp.MustCompile(`^/api/mobile/cli/sessions/[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}(/messages|/media|/stop|/approval|/open|/metadata|/account|/delete|/archive|/restore|/purge)?$`)
26
27var surfacePath = regexp.MustCompile(`^/api/mobile/(?:browser|desktop)/[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/(frame|action|close)$`)
28
29var epochID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
30
31var frameQuery = regexp.MustCompile(`^after=([0-9a-f]{32})$`)
32
33// FrameAfter accepts a single opaque frame tag in its canonical wire form.
34func FrameAfter(query string) (string, bool) {
35 match := frameQuery.FindStringSubmatch(query)
36 if match == nil {
37 return "", false
38 }
39 return match[1], true
40}
41
42func allowed(method string, u *url.URL) bool {
43 if u == nil || u.RawPath != "" || u.Opaque != "" || u.User != nil || u.Fragment != "" || u.ForceQuery {
44 return false
45 }
46 if u.Path == "/api/mobile/cli/sessions" && u.RawQuery == "archived=true" {
47 return method == http.MethodGet
48 }
49 if u.RawQuery == "" {
50 switch u.Path {
51 case "/api/mobile/browser/open", "/api/mobile/desktop/open", "/api/mobile/device":
52 return method == http.MethodPost
53 case "/api/mobile/cli/projects":
54 return method == http.MethodGet
55 case "/api/mobile/cli/sessions", "/api/mobile/browser/favorites":
56 return method == http.MethodGet || method == http.MethodPost
57 }
58 }
59 if match := surfacePath.FindStringSubmatch(u.Path); match != nil {
60 if u.RawQuery == "" {
61 return (match[1] == "frame" && method == http.MethodGet) || (match[1] != "frame" && method == http.MethodPost)
62 }
63 _, ok := FrameAfter(u.RawQuery)
64 return ok && match[1] == "frame" && method == http.MethodGet && strings.HasPrefix(u.Path, "/api/mobile/browser/")
65 }
66 match := sessionPath.FindStringSubmatch(u.Path)
67 if match == nil {
68 return false
69 }
70 if match[1] != "" {
71 return method == http.MethodPost && u.RawQuery == ""
72 }
73 if method != http.MethodGet {
74 return false
75 }
76 if u.RawQuery == "" {
77 return true
78 }
79 fields := strings.Split(u.RawQuery, "&")
80 if len(fields) > 2 {
81 return false
82 }
83 var after string
84 var hasEpoch bool
85 for _, field := range fields {
86 key, value, _ := strings.Cut(field, "=")
87 switch key {
88 case "after":
89 if after != "" || value == "" {
90 return false
91 }
92 after = value
93 case "epoch":
94 if hasEpoch || !epochID.MatchString(value) {
95 return false
96 }
97 hasEpoch = true
98 default:
99 return false
100 }
101 }
102 if after == "" {
103 return false
104 }
105 for _, digit := range after {
106 if digit < '0' || digit > '9' {
107 return false
108 }
109 }
110 _, err := strconv.ParseUint(after, 10, 64)
111 return err == nil
112}
113
114// Reply carries only application data. Browser cookies, redirects, hop headers
115// and upstream authentication fields never cross the device link.
116type Reply struct {
117 Status int
118 ContentType string
119 Body []byte
120}
121
122type performFunc func(context.Context, string, string, []byte) (*Reply, error)
123
124func limited(r io.Reader, limit int64) ([]byte, error) {
125 data, err := io.ReadAll(io.LimitReader(r, limit+1))
126 if err != nil || int64(len(data)) > limit {
127 return nil, errors.New("payload exceeds limit or could not be read")
128 }
129 return data, nil
130}
131
132// operations checks the method and route before reading data. Callers establish
133// the peer identity or the local browser session before invoking this handler.
134func operations(do performFunc) http.Handler {
135 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
136 w.Header().Set("Cache-Control", "no-store")
137 w.Header().Set("X-Content-Type-Options", "nosniff")
138 if !allowed(r.Method, r.URL) {
139 http.NotFound(w, r)
140 return
141 }
142 if r.Method == http.MethodPost {
143 kind, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
144 if kind != "application/json" {
145 http.Error(w, "JSON is required", http.StatusUnsupportedMediaType)
146 return
147 }
148 }
149 body, err := limited(r.Body, maxRequest)
150 if err != nil {
151 http.Error(w, "request body too large or unreadable", http.StatusRequestEntityTooLarge)
152 return
153 }
154 if r.Method == http.MethodGet && len(body) != 0 {
155 http.Error(w, "GET must not have a body", http.StatusBadRequest)
156 return
157 }
158 reply, err := do(r.Context(), r.Method, r.URL.RequestURI(), body)
159 if err != nil {
160 http.Error(w, "与电脑的连接已中断。请检查手机网络和电脑上的 Cage,再重新读取会话。", http.StatusBadGateway)
161 return
162 }
163 w.Header().Set("Content-Type", reply.ContentType)
164 w.WriteHeader(reply.Status)
165 if reply.Status != http.StatusNoContent {
166 _, _ = w.Write(reply.Body)
167 }
168 })
169}
170
171func request(ctx context.Context, client http.RoundTripper, origin, method, path string, body []byte, localOrigin bool) (*Reply, error) {
172 u, err := url.ParseRequestURI(path)
173 if err != nil || u.IsAbs() || u.Host != "" || !allowed(method, u) || len(body) > maxRequest || (method == http.MethodGet && len(body) > 0) {
174 return nil, errors.New("mobile operation refused")
175 }
176 ctx, cancel := context.WithTimeout(ctx, 40*time.Second)
177 defer cancel()
178 req, err := http.NewRequestWithContext(ctx, method, origin+path, bytes.NewReader(body))
179 if err != nil {
180 return nil, errors.New("invalid mobile operation")
181 }
182 req.GetBody = nil // A mutation with a lost response is never replayed here.
183 if method == http.MethodPost {
184 req.Header.Set("Content-Type", "application/json")
185 }
186 if localOrigin {
187 req.Header.Set("Origin", origin)
188 }
189 res, err := client.RoundTrip(req)
190 if err != nil {
191 return nil, errors.New("mobile operation interrupted")
192 }
193 defer res.Body.Close()
194 if res.StatusCode < 200 || (res.StatusCode >= 300 && res.StatusCode < 400) {
195 return nil, errors.New("unexpected mobile response status")
196 }
197 data, err := limited(res.Body, maxResponse)
198 if err != nil {
199 return nil, err
200 }
201 contentType := "text/plain; charset=utf-8"
202 if kind, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")); kind == "application/json" {
203 contentType = "application/json"
204 }
205 return &Reply{res.StatusCode, contentType, data}, nil
206}