跳到主要内容

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

浏览文件

server.go

393 行 · 10.8 KB历史下载
1// Package relay pairs two outbound WebSocket connections. It forwards opaque
2// bytes only; peer identity and application authorization belong to the hosts.
3package relay
4
5import (
6 "crypto/rand"
7 "crypto/sha256"
8 "crypto/subtle"
9 "encoding/base64"
10 "encoding/hex"
11 "encoding/json"
12 "errors"
13 "io"
14 "net/http"
15 "strings"
16 "sync"
17 "time"
18
19 "github.com/gorilla/websocket"
20)
21
22const MaxFrameSize = 64 << 10
23
24type Config struct {
25 PublicRooms bool
26 AdminToken string
27 MaxRooms int
28 PairTimeout time.Duration
29 IdleTimeout time.Duration
30}
31
32// Invitation contains short-lived transport capabilities, not device identity.
33// A client must authenticate its peer inside the tunnel before sending data.
34type Invitation struct {
35 ID string `json:"id"`
36 HostToken string `json:"host_token"`
37 ClientToken string `json:"client_token"`
38 ExpiresAt time.Time `json:"expires_at"`
39}
40
41type endpoint struct {
42 token [32]byte
43 claimed bool
44 socket *websocket.Conn
45}
46
47type room struct {
48 id string
49 expiresAt time.Time
50 host endpoint
51 client endpoint
52 ready chan struct{}
53 done chan struct{}
54 timer *time.Timer
55 paired bool
56 lastActivity time.Time
57 lookupHash [32]byte
58 discoverable bool
59 clientInvitation string
60}
61
62type Server struct {
63 config Config
64 admin [32]byte
65 mu sync.Mutex
66 rooms map[string]*room
67 slots map[[32]byte]*room
68 closed bool
69}
70
71func New(config Config) (*Server, error) {
72 if len(config.AdminToken) < 32 || strings.ContainsAny(config.AdminToken, " \t\r\n") {
73 return nil, errors.New("relay admin token must contain at least 32 bytes without whitespace")
74 }
75 if config.MaxRooms == 0 {
76 config.MaxRooms = 128
77 }
78 if config.PairTimeout == 0 {
79 config.PairTimeout = 2 * time.Minute
80 }
81 if config.IdleTimeout == 0 {
82 config.IdleTimeout = 5 * time.Minute
83 }
84 if config.MaxRooms < 1 || config.PairTimeout < 0 || config.IdleTimeout < 0 {
85 return nil, errors.New("relay limits must be positive")
86 }
87 admin := sha256.Sum256([]byte(config.AdminToken))
88 config.AdminToken = ""
89 return &Server{config: config, admin: admin, rooms: make(map[string]*room), slots: make(map[[32]byte]*room)}, nil
90}
91
92func secret() string {
93 var value [32]byte
94 _, _ = rand.Read(value[:]) // crypto/rand.Read always fills the buffer or terminates.
95 return base64.RawURLEncoding.EncodeToString(value[:])
96}
97
98func authorized(r *http.Request, expected [32]byte) bool {
99 values := r.Header.Values("Authorization")
100 if len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") {
101 return false
102 }
103 value := strings.TrimPrefix(values[0], "Bearer ")
104 if value == "" || strings.ContainsAny(value, " \t\r\n") {
105 return false
106 }
107 actual := sha256.Sum256([]byte(value))
108 return subtle.ConstantTimeCompare(actual[:], expected[:]) == 1
109}
110
111func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
112 w.Header().Set("Cache-Control", "no-store")
113 w.Header().Set("X-Content-Type-Options", "nosniff")
114 // Transport credentials only travel in headers. No browser-origin clients
115 // are accepted: the mobile native transport owns the TLS tunnel.
116 if r.URL.RawQuery != "" || r.Header.Get("Origin") != "" {
117 http.Error(w, "unsupported request", http.StatusBadRequest)
118 return
119 }
120 if r.Method == http.MethodGet && r.URL.Path == "/healthz" {
121 s.mu.Lock()
122 closed := s.closed
123 s.mu.Unlock()
124 if closed {
125 http.Error(w, "stopping", http.StatusServiceUnavailable)
126 return
127 }
128 _, _ = w.Write([]byte("ok\n"))
129 return
130 }
131 if r.Method == http.MethodPost && r.URL.Path == "/v1/rooms" {
132 s.create(w, r)
133 return
134 }
135 if r.Method == http.MethodGet && r.URL.Path == "/v1/invitation" {
136 s.lookup(w, r)
137 return
138 }
139 parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
140 if r.Method == http.MethodGet && len(parts) == 4 && parts[0] == "v1" && parts[1] == "rooms" && (parts[3] == "host" || parts[3] == "client") {
141 s.join(w, r, parts[2], parts[3])
142 return
143 }
144 http.NotFound(w, r)
145}
146
147func (s *Server) create(w http.ResponseWriter, r *http.Request) {
148 if !(s.config.PublicRooms && len(r.Header.Values("Authorization")) == 0) && !authorized(r, s.admin) {
149 http.Error(w, "unauthorized", http.StatusUnauthorized)
150 return
151 }
152 var hash [32]byte
153 discoverable := r.ContentLength != 0
154 if discoverable {
155 var body struct {
156 Hash string `json:"lookup_hash"`
157 }
158 decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256))
159 decoder.DisallowUnknownFields()
160 if decoder.Decode(&body) != nil || decoder.Decode(new(any)) != io.EOF {
161 http.Error(w, "invalid room registration", http.StatusBadRequest)
162 return
163 }
164 digest, err := hex.DecodeString(body.Hash)
165 if err != nil || len(digest) != len(hash) || hex.EncodeToString(digest) != body.Hash {
166 http.Error(w, "invalid room registration", http.StatusBadRequest)
167 return
168 }
169 copy(hash[:], digest)
170 }
171 s.mu.Lock()
172 if s.closed {
173 s.mu.Unlock()
174 http.Error(w, "stopping", http.StatusServiceUnavailable)
175 return
176 }
177 if len(s.rooms) >= s.config.MaxRooms {
178 s.mu.Unlock()
179 http.Error(w, "relay capacity reached", http.StatusTooManyRequests)
180 return
181 }
182 if discoverable && s.slots[hash] != nil {
183 s.mu.Unlock()
184 http.Error(w, "existing device connection", http.StatusConflict)
185 return
186 }
187 i := Invitation{ID: secret(), HostToken: secret(), ClientToken: secret(), ExpiresAt: time.Now().Add(s.config.PairTimeout)}
188 room := &room{id: i.ID, expiresAt: i.ExpiresAt, host: endpoint{token: sha256.Sum256([]byte(i.HostToken))},
189 client: endpoint{token: sha256.Sum256([]byte(i.ClientToken))}, ready: make(chan struct{}), done: make(chan struct{})}
190 s.rooms[i.ID] = room
191 if discoverable {
192 room.lookupHash, room.discoverable, room.clientInvitation = hash, true, i.ClientToken
193 s.slots[hash] = room
194 }
195 room.timer = time.AfterFunc(s.config.PairTimeout, func() { s.expire(room) })
196 s.mu.Unlock()
197 w.Header().Set("Content-Type", "application/json")
198 w.WriteHeader(http.StatusCreated)
199 _ = json.NewEncoder(w).Encode(i)
200}
201
202// A saved device resolves a fresh transport ticket. Both device certificates
203// are still independently verified end-to-end when it uses that ticket.
204func (s *Server) lookup(w http.ResponseWriter, r *http.Request) {
205 values := r.Header.Values("Authorization")
206 if len(values) != 1 {
207 http.NotFound(w, r)
208 return
209 }
210 value, ok := strings.CutPrefix(values[0], "Bearer ")
211 key, err := base64.RawURLEncoding.DecodeString(value)
212 if !ok || err != nil || len(key) != 32 || base64.RawURLEncoding.EncodeToString(key) != value {
213 http.NotFound(w, r)
214 return
215 }
216 hash := sha256.Sum256(key)
217 clear(key)
218 s.mu.Lock()
219 room := s.slots[hash]
220 if room == nil || room.host.socket == nil || room.client.claimed || !time.Now().Before(room.expiresAt) {
221 s.mu.Unlock()
222 http.NotFound(w, r)
223 return
224 }
225 response := struct {
226 ID string `json:"id"`
227 Token string `json:"client_token"`
228 ExpiresAt time.Time `json:"expires_at"`
229 }{room.id, room.clientInvitation, room.expiresAt}
230 s.mu.Unlock()
231 w.Header().Set("Content-Type", "application/json")
232 _ = json.NewEncoder(w).Encode(response)
233}
234
235func (s *Server) join(w http.ResponseWriter, r *http.Request, id, role string) {
236 s.mu.Lock()
237 room := s.rooms[id]
238 if room == nil || s.closed {
239 s.mu.Unlock()
240 http.Error(w, "connection unavailable", http.StatusNotFound)
241 return
242 }
243 endpoint := &room.client
244 if role == "host" {
245 endpoint = &room.host
246 }
247 if !authorized(r, endpoint.token) {
248 s.mu.Unlock()
249 http.Error(w, "unauthorized", http.StatusUnauthorized)
250 return
251 }
252 if endpoint.claimed || room.paired || !time.Now().Before(room.expiresAt) {
253 s.mu.Unlock()
254 http.Error(w, "connection invitation consumed or expired", http.StatusConflict)
255 return
256 }
257 endpoint.claimed = true
258 s.mu.Unlock()
259 defer s.remove(room)
260
261 upgrader := websocket.Upgrader{HandshakeTimeout: 5 * time.Second, CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "" }}
262 connection, err := upgrader.Upgrade(w, r, nil)
263 if err != nil {
264 return
265 }
266 defer connection.Close()
267 connection.SetReadLimit(MaxFrameSize)
268 s.mu.Lock()
269 if s.rooms[id] != room || s.closed {
270 s.mu.Unlock()
271 return
272 }
273 endpoint.socket = connection
274 if room.host.socket != nil && room.client.socket != nil {
275 room.paired = true
276 room.clientInvitation = ""
277 room.timer.Stop()
278 room.lastActivity = time.Now()
279 room.timer = time.AfterFunc(s.config.IdleTimeout, func() { s.expireIdle(room) })
280 close(room.ready)
281 }
282 s.mu.Unlock()
283
284 // Read even before the peer joins. A waiting host can disconnect on
285 // restart, and its saved pairing must immediately be free to register again.
286 var other *websocket.Conn
287 for {
288 kind, data, err := connection.ReadMessage()
289 if err != nil || kind != websocket.BinaryMessage {
290 return
291 }
292 if other == nil {
293 select {
294 case <-room.ready:
295 case <-room.done:
296 return
297 }
298 s.mu.Lock()
299 other = room.host.socket
300 if role == "host" {
301 other = room.client.socket
302 }
303 s.mu.Unlock()
304 }
305 s.mu.Lock()
306 live := s.rooms[room.id] == room
307 if live {
308 room.lastActivity = time.Now()
309 }
310 s.mu.Unlock()
311 if !live {
312 return
313 }
314 _ = other.SetWriteDeadline(time.Now().Add(10 * time.Second))
315 if err := other.WriteMessage(websocket.BinaryMessage, data); err != nil {
316 return
317 }
318 }
319}
320
321// A receive-only client is active while the host streams output. Account for
322// traffic in either direction instead of timing out the quieter endpoint.
323func (s *Server) expireIdle(room *room) {
324 s.mu.Lock()
325 if s.rooms[room.id] != room {
326 s.mu.Unlock()
327 return
328 }
329 remaining := time.Until(room.lastActivity.Add(s.config.IdleTimeout))
330 if remaining > 0 {
331 room.timer.Reset(remaining)
332 s.mu.Unlock()
333 return
334 }
335 connections := s.removeLocked(room)
336 s.mu.Unlock()
337 closeConnections(connections)
338}
339
340// expire only removes waiting rooms; active connections have an idle timeout.
341func (s *Server) expire(room *room) {
342 s.mu.Lock()
343 if s.rooms[room.id] != room || room.paired {
344 s.mu.Unlock()
345 return
346 }
347 connections := s.removeLocked(room)
348 s.mu.Unlock()
349 closeConnections(connections)
350}
351
352func (s *Server) removeLocked(room *room) []*websocket.Conn {
353 if s.rooms[room.id] != room {
354 return nil
355 }
356 delete(s.rooms, room.id)
357 if room.discoverable {
358 delete(s.slots, room.lookupHash)
359 room.clientInvitation = ""
360 }
361 room.timer.Stop()
362 close(room.done)
363 return []*websocket.Conn{room.host.socket, room.client.socket}
364}
365
366func closeConnections(connections []*websocket.Conn) {
367 for _, connection := range connections {
368 if connection != nil {
369 _ = connection.Close()
370 }
371 }
372}
373
374func (s *Server) remove(room *room) {
375 s.mu.Lock()
376 connections := s.removeLocked(room)
377 s.mu.Unlock()
378 closeConnections(connections)
379}
380
381// Close rejects new rooms and closes all upgraded connections. HTTP shutdown
382// alone does not close hijacked WebSockets; callers must also call Close.
383func (s *Server) Close() error {
384 s.mu.Lock()
385 s.closed = true
386 var connections []*websocket.Conn
387 for _, room := range s.rooms {
388 connections = append(connections, s.removeLocked(room)...)
389 }
390 s.mu.Unlock()
391 closeConnections(connections)
392 return nil
393}