跳到主要内容

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

浏览文件

saved.go

274 行 · 8.2 KB历史下载
1package main
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/base64"
8 "encoding/json"
9 "errors"
10 "io"
11 "log"
12 "os"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "time"
17
18 "github.com/sylvinus/agent-vm/internal/mobilelink"
19)
20
21// connectionFile is the only long-lived record exported to the phone.
22// Its token may claim a transport role, but cannot authenticate either peer.
23type connectionFile struct {
24 Version int `json:"version"`
25 Relay string `json:"relay"`
26 LookupToken string `json:"lookup_token"`
27 HostPin string `json:"host_pin"`
28}
29
30type hostSettings struct {
31 Relay string `json:"relay"`
32 AdminFile string `json:"admin_token_file"`
33 CageBinary string `json:"cage_binary"`
34 Config string `json:"config"`
35}
36
37type savedHost struct {
38 Connection connectionFile `json:"connection"`
39 Settings hostSettings `json:"host"`
40 PeerPin string `json:"peer_pin"`
41}
42
43func decodePrivateJSON(path string, result any) error {
44 data, err := readPrivate(path, 16<<10)
45 if err != nil {
46 return err
47 }
48 defer clear(data)
49 decoder := json.NewDecoder(bytes.NewReader(data))
50 decoder.DisallowUnknownFields()
51 if decoder.Decode(result) != nil || decoder.Decode(new(any)) != io.EOF {
52 return errors.New("invalid private connection record")
53 }
54 return nil
55}
56
57func (c connectionFile) valid() bool {
58 raw, err := base64.RawURLEncoding.DecodeString(c.LookupToken)
59 defer clear(raw)
60 return c.Version == 1 && mobilelink.ValidRelayOrigin(c.Relay) && validPin(c.HostPin) && err == nil && len(raw) == 32 && base64.RawURLEncoding.EncodeToString(raw) == c.LookupToken
61}
62
63func (s hostSettings) valid() bool {
64 return mobilelink.ValidRelayOrigin(s.Relay) && (s.AdminFile == "" || filepath.IsAbs(s.AdminFile)) && filepath.IsAbs(s.Config) && filepath.IsAbs(s.CageBinary)
65}
66
67func loadSavedHost(state, hostPin, peerPin string) (savedHost, error) {
68 var h savedHost
69 err := decodePrivateJSON(filepath.Join(state, "saved-host.json"), &h)
70 if err != nil {
71 return h, err
72 }
73 if !h.Connection.valid() || !h.Settings.valid() || h.Connection.Relay != h.Settings.Relay || h.Connection.HostPin != hostPin || h.PeerPin != peerPin {
74 return savedHost{}, errors.New("saved host settings no longer match this pairing; verify the device state")
75 }
76 return h, nil
77}
78
79func configureSavedHost(state, dest, hostPin, peerPin string, settings hostSettings) (savedHost, error) {
80 var h savedHost
81 if !settings.valid() {
82 return h, errors.New("saved host requires a trusted relay and absolute admin token, cage binary and config paths")
83 }
84 if info, err := os.Stat(settings.CageBinary); err != nil || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0111 == 0) {
85 return h, errors.New("saved Cage binary must be an executable file")
86 }
87 if _, err := readAdminToken(settings.AdminFile); err != nil {
88 return h, err
89 }
90 path := filepath.Join(state, "saved-host.json")
91 _, err := os.Lstat(path)
92 switch {
93 case err == nil:
94 h, err = loadSavedHost(state, hostPin, peerPin)
95 if err != nil {
96 return h, err
97 }
98 if h.Settings != settings {
99 return h, errors.New("existing saved host settings differ; revoke this pairing before replacing it")
100 }
101 case errors.Is(err, os.ErrNotExist):
102 raw := make([]byte, 32)
103 _, _ = rand.Read(raw)
104 h = savedHost{Connection: connectionFile{Version: 1, Relay: settings.Relay, LookupToken: base64.RawURLEncoding.EncodeToString(raw), HostPin: hostPin}, Settings: settings, PeerPin: peerPin}
105 clear(raw)
106 data, _ := json.Marshal(h)
107 err = writeNewPrivate(path, data)
108 clear(data)
109 if err != nil {
110 return savedHost{}, err
111 }
112 default:
113 return h, errors.New("cannot inspect saved host settings")
114 }
115 data, _ := json.Marshal(h.Connection)
116 err = writeNewPrivate(dest, data)
117 clear(data)
118 return h, err
119}
120
121func readAdminToken(path string) (string, error) {
122 if path == "" {
123 return "", nil
124 }
125 raw, err := readPrivate(path, 4098)
126 if err != nil {
127 return "", err
128 }
129 defer clear(raw)
130 token := string(raw)
131 if strings.HasSuffix(token, "\n") {
132 token = strings.TrimSuffix(strings.TrimSuffix(token, "\n"), "\r")
133 }
134 if len(token) < 32 || len(token) > 4096 {
135 return "", errors.New("invalid protected relay admin token")
136 }
137 for i := range len(token) {
138 if token[i] < 0x21 || token[i] > 0x7e {
139 return "", errors.New("invalid protected relay admin token")
140 }
141 }
142 return token, nil
143}
144
145func revoke(state string) error {
146 if _, err := loadIdentity(state); err != nil {
147 return err
148 }
149 // Remove peer trust first, so an active saved bridge refuses access even
150 // if a filesystem error interrupts deletion of the lookup credential.
151 for _, name := range []string{"trusted-peer", "saved-host.json"} {
152 if err := os.Remove(filepath.Join(state, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
153 return errors.New("could not revoke saved device state")
154 }
155 }
156 return nil
157}
158
159var errRevoked = errors.New("saved device trust changed; host bridge closed")
160
161func verifySaved(state string, h savedHost) bool {
162 peer, err := trustedPeer(state)
163 if err != nil || peer != h.PeerPin {
164 return false
165 }
166 current, err := loadSavedHost(state, h.Connection.HostPin, peer)
167 return err == nil && current == h
168}
169
170func monitorTrust(parent context.Context, verify func() bool) (context.Context, func()) {
171 ctx, cancel := context.WithCancelCause(parent)
172 // Blocked TLS handshakes and already connected clients must also notice
173 // revocation. A removed/replaced private trust record closes this bridge.
174 go func() {
175 ticker := time.NewTicker(time.Second)
176 defer ticker.Stop()
177 for {
178 select {
179 case <-ctx.Done():
180 return
181 case <-ticker.C:
182 if !verify() {
183 cancel(errRevoked)
184 return
185 }
186 }
187 }
188 }()
189 return ctx, func() { cancel(nil) }
190}
191
192func savedService(parent context.Context, state string, h savedHost, out io.Writer) error {
193 ctx, stop := monitorTrust(parent, func() bool { return verifySaved(state, h) })
194 defer stop()
195 logger := log.New(out, "", 0)
196 stopAwake := keepHostAwake(ctx, logger)
197 defer stopAwake()
198 delay := time.Second
199 for ctx.Err() == nil {
200 if !verifySaved(state, h) {
201 return errRevoked
202 }
203 retry, err := savedRoom(ctx, state, h)
204 if ctx.Err() != nil {
205 break
206 }
207 if !retry {
208 return err
209 }
210 if err == nil {
211 delay = time.Second
212 } else {
213 logger.Println("Room unavailable; retrying the saved connection in", delay.String())
214 }
215 timer := time.NewTimer(delay)
216 select {
217 case <-ctx.Done():
218 timer.Stop()
219 return context.Cause(ctx)
220 case <-timer.C:
221 }
222 if err != nil {
223 delay = min(30*time.Second, 2*delay)
224 }
225 }
226 return context.Cause(ctx)
227}
228
229func savedRoom(ctx context.Context, state string, h savedHost) (bool, error) {
230 // Issue a fresh short-lived certificate and local Cage session for each
231 // room. This also handles a restarted desktop control service.
232 id, err := loadIdentity(state)
233 if err != nil || id.Pin != h.Connection.HostPin {
234 return false, errors.New("device identity changed")
235 }
236 if info, err := os.Stat(h.Settings.CageBinary); err != nil || !info.Mode().IsRegular() {
237 return false, errors.New("saved Cage binary unavailable")
238 }
239 admin, err := readAdminToken(h.Settings.AdminFile)
240 if err != nil {
241 return false, err
242 }
243 b, err := localWorkbench(ctx, h.Settings.CageBinary, h.Settings.Config)
244 if err != nil {
245 return true, err
246 }
247 defer b.Close()
248 room, err := mobilelink.CreateDiscoverableRoom(ctx, h.Settings.Relay, admin, h.Connection.LookupToken)
249 if err != nil {
250 return mobilelink.Retryable(err), err
251 }
252 err = mobilelink.ServeHost(ctx, h.Settings.Relay, room.ID, room.HostToken, id, h.PeerPin, b)
253 if mobilelink.Retryable(err) && !time.Now().Before(room.ExpiresAt) {
254 // An unused room reaching its normal pairing deadline is healthy.
255 // Publish the next room without accumulating offline backoff.
256 return true, nil
257 }
258 return err == nil || mobilelink.Retryable(err), err
259}
260
261func resolveSaved(ctx context.Context, path, base, peer string) (clientInvitation, error) {
262 var c connectionFile
263 if err := decodePrivateJSON(path, &c); err != nil {
264 return clientInvitation{}, err
265 }
266 if !c.valid() || c.Relay != base || c.HostPin != peer {
267 return clientInvitation{}, errors.New("connection file differs from independently trusted host or relay")
268 }
269 found, err := mobilelink.LookupRoom(ctx, base, c.LookupToken)
270 if err != nil {
271 return clientInvitation{}, err
272 }
273 return clientInvitation{found.ID, found.ClientToken, found.ExpiresAt}, nil
274}