跳到主要内容

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

提交记录
修改docs/getting-started.md+6 −0看文件
@@ -47,6 +47,12 @@ Windows 安装器中选择的是程序目录。如果希望镜像下载和虚拟
4747
4848首次安装和工具升级会自动选择下载来源,无需手动补缓存。中科大的 code-server 镜像只保留最近版本;Cage 固定的版本缺失时,会直接从 GitHub 下载该版本。下载仍经过当前选择的 Cage 代理。初始虚拟磁盘的容量上限为 24 GiB,下载流量与实际占用取决于架构、软件包版本和已有缓存。以后启动会复用已安装的环境。需要 Claude Desktop 时,在工作台单独安装,届时才访问 Anthropic 的软件源。
4949
50新增:### 受信任的本机登录
51新增:
52新增:首次在完整桌面版打开空配置,选择「信任此电脑并进入」,以后同一系统用户打开 Cage 可自动进入。也可以选择「使用用户名和密码」。已有密码账户沿用原来的登录方式,也可在「设置 → 账户 → 信任此电脑」验证原密码后开启自动登录;手动锁定仍需验证,退出账户会撤销此项信任。远程连接不能使用本机信任登录;Claude 服务仍需自己的授权。
53新增:
54新增:受信任模式依赖操作系统的用户登录。离开电脑时请锁定系统。需要 Cage 独立锁屏、远程密码登录,或查看、复制保险箱密码时,在「设置 → 账户」设置密码即可转换;工作区内部密钥和已有数据继续使用。备份免账号工作区时,还需备份系统用户配置目录(Windows 使用 `%LOCALAPPDATA%`)下的 `Cage/trusted-local` 私有信任凭据,并以私有权限保存。
55新增:
5056## 2. 导入并选择代理
5157
5258进入工作台后点击“配置网络与代理”。之后也可以从左下角“设置 → 网络与代理”进入。没有节点时点击“添加来源”,选择一种导入方式:
修改internal/workbench/account.go+6 −2看文件
@@ -5,7 +5,7 @@ import (
55)
66
77func (s *Server) accountStatus(w http.ResponseWriter, r *http.Request) {
8删除: v := s.account.view()
8新增: v := s.account.viewFor(s.hasTrustedView(r))
99 v.BackgroundRunning = s.vmRunning()
1010 jsonReply(w, v)
1111}
@@ -21,11 +21,15 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) {
2121 return
2222 }
2323 if action != "create" && action != "unlock" && action != "device-unlock" {
24删除: if _, ok := s.account.access(); !ok {
24新增: if _, ok := s.account.accessFor(s.hasTrustedView(r)); !ok {
2525 http.Error(w, "请先解锁 Cage", http.StatusLocked)
2626 return
2727 }
2828 }
29新增: if (action == "lock" || action == "logout" || action == "device-enroll") && s.account.view().TrustedLocal {
30新增: http.Error(w, "请先在本机的「设置 → 账户」设置密码", http.StatusConflict)
31新增: return
32新增: }
2933 var input struct {
3034 Username string `json:"username"`
3135 Password string `json:"password"`
修改internal/workbench/account_device.go+1 −0看文件
@@ -136,6 +136,7 @@ func (a *localAccount) lockAccess(logout bool) error {
136136 record.RequireAuthentication = true
137137 if logout {
138138 record.Devices = nil
139新增: record.TrustedUnlock = nil
139140 }
140141 if err := writePrivate(a.path, record); err != nil {
141142 return errors.New("无法保存账户锁定状态,请重试")
修改internal/workbench/account_store.go+28 −13看文件
@@ -24,6 +24,8 @@ import (
2424)
2525
2626type accountRecord struct {
27新增: TrustedDevice string `json:"trusted_device,omitempty"`
28新增: TrustedUnlock *accountDevice `json:"trusted_unlock,omitempty"`
2729 Version int `json:"version"`
2830 Username string `json:"username"`
2931 Avatar string `json:"avatar,omitempty"`
@@ -35,17 +37,20 @@ type accountRecord struct {
3537}
3638
3739type localAccount struct {
38删除: mu sync.Mutex
39删除: path string
40删除: record *accountRecord
41删除: key []byte
42删除: vaultLease string
43删除: epoch context.Context
44删除: cancel context.CancelFunc
45删除: nextAttempt time.Time
40新增: mu sync.Mutex
41新增: path string
42新增: record *accountRecord
43新增: trustedSession bool
44新增: key []byte
45新增: vaultLease string
46新增: epoch context.Context
47新增: cancel context.CancelFunc
48新增: nextAttempt time.Time
4649}
4750
4851type accountView struct {
52新增: TrustedLocal bool `json:"trusted_local,omitempty"`
53新增: TrustedLogin bool `json:"trusted_login,omitempty"`
4954 Exists bool `json:"exists"`
5055 Unlocked bool `json:"unlocked"`
5156 Username string `json:"username"`
@@ -69,9 +74,12 @@ func loadLocalAccount(profile string) (*localAccount, error) {
6974 return nil, errors.New("本地账户文件权限不安全,请恢复私有文件权限")
7075 }
7176 var record accountRecord
72删除: if len(b) > 256<<10 || json.Unmarshal(b, &record) != nil || record.Version != 1 || len(record.Salt) != 16 || len(record.Nonce) != 12 || len(record.SealedKey) != 48 || validAccountName(record.Username) != nil {
77新增: if len(b) > 256<<10 || json.Unmarshal(b, &record) != nil || record.Version != 1 || !validTrustedID(record.TrustedDevice) || len(record.Salt) != 16 || len(record.Nonce) != 12 || len(record.SealedKey) != 48 || validAccountName(record.Username) != nil {
7378 return nil, errors.New("本地账户文件损坏,请从备份恢复;已有数据未修改")
7479 }
80新增: if device := record.TrustedUnlock; device != nil && (len(device.ID) != 64 || !validTrustedID(device.ID) || len(device.Nonce) != 12 || len(device.SealedKey) != 48 || record.TrustedDevice != "") {
81新增: return nil, errors.New("本机信任记录损坏,请从备份恢复")
82新增: }
7583 a.record = &record
7684 for kind, device := range record.Devices {
7785 if !validDeviceKind(kind) || len(device.ID) != 32 || len(device.Nonce) != 12 || len(device.SealedKey) != 48 {
@@ -133,15 +141,19 @@ func openAccountKey(record *accountRecord, password string) ([]byte, error) {
133141 return key, nil
134142}
135143
136删除:func (a *localAccount) view() accountView {
144新增:func (a *localAccount) view() accountView { return a.viewFor(true) }
145新增:
146新增:func (a *localAccount) viewFor(desktop bool) accountView {
137147 if a == nil {
138148 return accountView{}
139149 }
140150 a.mu.Lock()
141151 defer a.mu.Unlock()
142删除: v := accountView{Exists: a.record != nil, Unlocked: len(a.key) == 32}
152新增: v := accountView{Exists: a.record != nil, Unlocked: len(a.key) == 32 && (!a.trustedSession || desktop)}
143153 v.DeviceBinding = fmtAccountBinding(a.path)
144154 if a.record != nil {
155新增: v.TrustedLocal = a.record.TrustedDevice != ""
156新增: v.TrustedLogin = a.record.TrustedUnlock != nil
145157 v.Username = a.record.Username
146158 v.Avatar = a.record.Avatar
147159 v.RequireAuthentication = a.record.RequireAuthentication
@@ -153,13 +165,15 @@ func (a *localAccount) view() accountView {
153165 return v
154166}
155167
156删除:func (a *localAccount) access() (context.Context, bool) {
168新增:func (a *localAccount) access() (context.Context, bool) { return a.accessFor(true) }
169新增:
170新增:func (a *localAccount) accessFor(desktop bool) (context.Context, bool) {
157171 if a == nil {
158172 return nil, false
159173 }
160174 a.mu.Lock()
161175 defer a.mu.Unlock()
162删除: return a.epoch, len(a.key) == 32
176新增: return a.epoch, len(a.key) == 32 && (!a.trustedSession || desktop)
163177}
164178
165179func (a *localAccount) setKey(key []byte) {
@@ -168,6 +182,7 @@ func (a *localAccount) setKey(key []byte) {
168182 }
169183 clear(a.key)
170184 a.key = key
185新增: a.trustedSession = false
171186 a.vaultLease = randomToken()
172187 a.epoch, a.cancel = context.WithCancel(context.Background())
173188}
修改internal/workbench/desktop_gateway.go+4 −0看文件
@@ -465,6 +465,10 @@ func (d *desktopGateway) close() {
465465}
466466
467467func (d *desktopGateway) handle(path string, w http.ResponseWriter, r *http.Request) bool {
468新增: if path == "trusted-login" {
469新增: d.trustedLogin(w, r)
470新增: return true
471新增: }
468472 if path == "local-status" && r.Method == http.MethodGet {
469473 if d.local == nil {
470474 jsonReply(w, DesktopLocalStatus{Known: true})
修改internal/workbench/desktop_local.go+4 −0看文件
@@ -307,6 +307,10 @@ func (d *desktopLocal) localSession(life, bootstrap context.Context, c *controll
307307 return nil, errors.New("本机工作台版本或环境身份不符")
308308 }
309309 manifest := remotehost.PublicManifest{APIProtocol: m.APIProtocol, InstanceID: m.InstanceID, Version: m.Version, Platform: m.Platform, Runtime: m.Runtime, Capabilities: m.Capabilities}
310新增: c.client.Jar.SetCookies(u, []*http.Cookie{{
311新增: Name: cookieName + "_" + u.Port() + "-desktop",
312新增: Value: trustedViewProof(c.record.Token), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode,
313新增: }})
310314 return remotehost.LocalSession(life, c.origin, manifest, c.client.Jar)
311315}
312316
修改internal/workbench/server.go+2 −1看文件
@@ -264,6 +264,7 @@ func (s *Server) handler() http.Handler {
264264 mux.HandleFunc("POST /api/handoff", s.handoffEntry)
265265 } else {
266266 mux.HandleFunc("POST /api/handoff", s.handoff)
267新增: mux.HandleFunc("POST /api/desktop-local/trusted-login", s.localTrustedLogin)
267268 mux.HandleFunc("POST /api/desktop-local/{action}", s.desktopLocalControl)
268269 }
269270 if s.desktopEntry {
@@ -410,7 +411,7 @@ func (s *Server) handler() http.Handler {
410411 accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/")
411412 bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" || r.URL.Path == "/api/remote/manifest"
412413 if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !strings.HasPrefix(r.URL.Path, "/api/diagnostics") && !(r.Method == "GET" && r.URL.Path == "/api/appearance") {
413删除: epoch, unlocked := s.account.access()
414新增: epoch, unlocked := s.account.accessFor(s.hasTrustedView(r))
414415 if !unlocked {
415416 http.Error(w, "Cage 已锁定,请先登录", http.StatusLocked)
416417 return
新增internal/workbench/trusted_login.go+271 −0看文件
@@ -0,0 +1,271 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "crypto/rand"
5新增: "crypto/sha256"
6新增: "encoding/hex"
7新增: "encoding/json"
8新增: "errors"
9新增: "net/http"
10新增: "os"
11新增: "path/filepath"
12新增: "runtime"
13新增: "time"
14新增:
15新增: "github.com/sylvinus/agent-vm/internal/host"
16新增:)
17新增:
18新增:// Only the local launcher possesses the controller token. Its independent
19新增:// cookie jar carries this proof; the browser and SSH tickets never receive it.
20新增:func trustedViewProof(token string) string {
21新增: digest := sha256.Sum256([]byte("trusted desktop view\x00" + token))
22新增: return hex.EncodeToString(digest[:])
23新增:}
24新增:func (s *Server) hasTrustedView(r *http.Request) bool {
25新增: c, err := r.Cookie(s.cookieName() + "-desktop")
26新增: return err == nil && equalSecret(c.Value, trustedViewProof(s.token))
27新增:}
28新增:
29新增:func validTrustedID(id string) bool {
30新增: if id == "" {
31新增: return true
32新增: }
33新增: _, err := hex.DecodeString(id)
34新增: return len(id) == 64 && err == nil
35新增:}
36新增:
37新增:type trustedLoginRequest struct {
38新增: Action string `json:"action"`
39新增: ConnectionID string `json:"connection_id,omitempty"`
40新增: Token string `json:"token,omitempty"`
41新增: InstanceID string `json:"instance_id,omitempty"`
42新增: Password string `json:"password,omitempty"`
43新增:}
44新增:
45新增:// Domain errors travel as data through the authenticated launcher client, which
46新增:// deliberately discards HTTP error bodies. Neither credential reaches the web UI.
47新增:type trustedLoginReply struct {
48新增: Error string `json:"error,omitempty"`
49新增:}
50新增:
51新增:func (d *desktopGateway) trustedLogin(w http.ResponseWriter, r *http.Request) {
52新增: if r.Method != http.MethodPost {
53新增: http.Error(w, "需要 POST 请求", 405)
54新增: return
55新增: }
56新增: var in trustedLoginRequest
57新增: if !readJSON(w, r, &in) {
58新增: return
59新增: }
60新增: d.change.Lock()
61新增: defer d.change.Unlock()
62新增: session, remote, err := d.acquire(in.ConnectionID)
63新增: local, ok := d.local.(*desktopLocal)
64新增: if err != nil || remote || !ok {
65新增: http.Error(w, "请返回当前本机工作台", 409)
66新增: return
67新增: }
68新增: c, err := openController(local.profile)
69新增: if err != nil {
70新增: http.Error(w, "本机后台无法连接", 503)
71新增: return
72新增: }
73新增: defer c.close()
74新增: if c.origin != session.Origin {
75新增: http.Error(w, "本机后台已切换", 409)
76新增: return
77新增: }
78新增: in.Token, in.InstanceID = c.record.Token, session.Manifest.InstanceID
79新增: var reply trustedLoginReply
80新增: status, err := c.callContext(r.Context(), "POST", "/api/desktop-local/trusted-login", in, &reply)
81新增: if err != nil || status != http.StatusOK {
82新增: http.Error(w, "本机后台未接受登录请求,请确认已更新 Cage", 409)
83新增: return
84新增: }
85新增: if reply.Error != "" {
86新增: http.Error(w, reply.Error, 409)
87新增: return
88新增: }
89新增: jsonReply(w, map[string]bool{"ok": true})
90新增:}
91新增:
92新增:func (s *Server) localTrustedLogin(w http.ResponseWriter, r *http.Request) {
93新增: var in trustedLoginRequest
94新增: if !readJSON(w, r, &in) {
95新增: return
96新增: }
97新增: if s.account == nil || !equalSecret(in.Token, s.token) || in.InstanceID != s.instanceID {
98新增: http.Error(w, "Launcher refused", http.StatusUnauthorized)
99新增: return
100新增: }
101新增: _, finish, err := s.beginActivity(r.Context())
102新增: if err != nil {
103新增: http.Error(w, "后台正在更新", 503)
104新增: return
105新增: }
106新增: defer finish()
107新增: base, err := os.UserConfigDir()
108新增: if runtime.GOOS == "windows" {
109新增: base = os.Getenv("LOCALAPPDATA")
110新增: }
111新增: if !filepath.IsAbs(base) {
112新增: err = errors.New("无法确定本机系统用户配置目录")
113新增: }
114新增: if err == nil {
115新增: err = s.account.trustedLogin(in.Action, in.Password, filepath.Join(base, "Cage", "trusted-local"))
116新增: }
117新增: reply := trustedLoginReply{}
118新增: if err != nil {
119新增: reply.Error = err.Error()
120新增: }
121新增: jsonReply(w, reply)
122新增:}
123新增:
124新增:func (a *localAccount) trustedLogin(action, password, devices string) error {
125新增: a.mu.Lock()
126新增: defer a.mu.Unlock()
127新增: switch action {
128新增: case "create":
129新增: if a.record != nil {
130新增: return errors.New("已有账户,请使用原登录方式")
131新增: }
132新增: record := &accountRecord{Version: 1, Username: "本机用户", TrustedDevice: randomToken()}
133新增: secret := randomToken()
134新增: key := make([]byte, 32)
135新增: if _, err := rand.Read(key); err != nil {
136新增: return err
137新增: }
138新增: defer clear(key)
139新增: if err := sealAccountKey(record, secret, key); err != nil {
140新增: return err
141新增: }
142新增: path := filepath.Join(devices, record.TrustedDevice+".json")
143新增: // Store the wrapping credential first. A crash cannot publish a record
144新增: // whose credential has not been persisted.
145新增: if err := writePrivate(path, secret); err != nil {
146新增: return errors.New("无法保存当前系统用户的信任凭据")
147新增: }
148新增: if err := writePrivate(a.path, record); err != nil {
149新增: _ = os.Remove(path)
150新增: return errors.New("无法保存本机工作区")
151新增: }
152新增: a.record = record
153新增: a.setKey(append([]byte(nil), key...))
154新增: a.trustedSession = true
155新增: case "enable":
156新增: if a.record == nil || a.record.TrustedDevice != "" || len(a.key) != 32 {
157新增: return errors.New("请先用本机账户登录")
158新增: }
159新增: if time.Now().Before(a.nextAttempt) {
160新增: return errors.New("请稍后再试")
161新增: }
162新增: key, err := openAccountKey(a.record, password)
163新增: if err != nil {
164新增: a.nextAttempt = time.Now().Add(time.Second)
165新增: return err
166新增: }
167新增: defer clear(key)
168新增: a.nextAttempt = time.Time{}
169新增: if a.record.TrustedUnlock != nil {
170新增: return nil
171新增: }
172新增: secret := randomToken()
173新增: raw, err := hex.DecodeString(secret)
174新增: if err != nil {
175新增: return err
176新增: }
177新增: defer clear(raw)
178新增: aead, err := deviceAEAD(raw)
179新增: if err != nil {
180新增: return err
181新增: }
182新增: device := accountDevice{ID: randomToken(), Nonce: make([]byte, aead.NonceSize())}
183新增: if _, err = rand.Read(device.Nonce); err != nil {
184新增: return err
185新增: }
186新增: device.SealedKey = aead.Seal(nil, device.Nonce, key, []byte("trusted:"+device.ID))
187新增: record := *a.record
188新增: record.TrustedUnlock = &device
189新增: path := filepath.Join(devices, device.ID+".json")
190新增: if err = writePrivate(path, secret); err != nil {
191新增: return errors.New("无法保存本机信任凭据")
192新增: }
193新增: if err = writePrivate(a.path, &record); err != nil {
194新增: _ = os.Remove(path)
195新增: return errors.New("本机信任未能保存")
196新增: }
197新增: a.record = &record
198新增: case "disable":
199新增: if a.record == nil || len(a.key) != 32 {
200新增: return errors.New("请先解锁 Cage")
201新增: }
202新增: if a.record.TrustedUnlock == nil {
203新增: return nil
204新增: }
205新增: record := *a.record
206新增: record.TrustedUnlock = nil
207新增: if err := writePrivate(a.path, &record); err != nil {
208新增: return errors.New("本机信任未能关闭")
209新增: }
210新增: a.record = &record
211新增: case "resume":
212新增: if a.record == nil || (a.record.TrustedDevice == "" && a.record.TrustedUnlock == nil) || a.record.RequireAuthentication {
213新增: return errors.New("请使用原有账户验证方式")
214新增: }
215新增: if len(a.key) == 32 {
216新增: return nil
217新增: }
218新增: id := a.record.TrustedDevice
219新增: if a.record.TrustedUnlock != nil {
220新增: id = a.record.TrustedUnlock.ID
221新增: }
222新增: path := filepath.Join(devices, id+".json")
223新增: if err := host.CheckPrivateFile(path); err != nil {
224新增: return errors.New("找不到当前系统用户的私有信任凭据,请恢复备份")
225新增: }
226新增: data, err := os.ReadFile(path)
227新增: var secret string
228新增: if err != nil || len(data) > 128 || json.Unmarshal(data, &secret) != nil || len(secret) != 64 {
229新增: return errors.New("本机信任凭据无法读取,请恢复备份")
230新增: }
231新增: var key []byte
232新增: if device := a.record.TrustedUnlock; device != nil {
233新增: raw, decodeErr := hex.DecodeString(secret)
234新增: if decodeErr != nil {
235新增: return errors.New("本机信任凭据无效")
236新增: }
237新增: defer clear(raw)
238新增: aead, cipherErr := deviceAEAD(raw)
239新增: if cipherErr != nil {
240新增: return cipherErr
241新增: }
242新增: key, err = aead.Open(nil, device.Nonce, device.SealedKey, []byte("trusted:"+device.ID))
243新增: } else {
244新增: key, err = openAccountKey(a.record, secret)
245新增: }
246新增: if err != nil {
247新增: return errors.New("信任凭据与工作区不匹配,请恢复备份")
248新增: }
249新增: a.setKey(key)
250新增: a.trustedSession = true
251新增: case "protect":
252新增: if a.record == nil || a.record.TrustedDevice == "" || len(a.key) != 32 {
253新增: return errors.New("请先在受信任的本机进入工作区")
254新增: }
255新增: if err := validAccountPassword(password); err != nil {
256新增: return err
257新增: }
258新增: record := *a.record
259新增: record.TrustedDevice = ""
260新增: if err := sealAccountKey(&record, password, a.key); err != nil {
261新增: return err
262新增: }
263新增: if err := writePrivate(a.path, &record); err != nil {
264新增: return errors.New("密码未能保存,仍可使用本机登录")
265新增: }
266新增: a.record = &record
267新增: default:
268新增: return errors.New("未知的信任登录操作")
269新增: }
270新增: return nil
271新增:}
新增internal/workbench/trusted_login_test.go+171 −0看文件
@@ -0,0 +1,171 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "encoding/json"
7新增: "net"
8新增: "net/http"
9新增: "net/http/httptest"
10新增: "os"
11新增: "path/filepath"
12新增: "strconv"
13新增: "testing"
14新增: "time"
15新增:)
16新增:
17新增:func TestTrustedLocalLifecycle(t *testing.T) {
18新增: profile, devices := t.TempDir(), t.TempDir()
19新增: a, err := loadLocalAccount(profile)
20新增: if err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: if err = a.trustedLogin("create", "", devices); err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: original := bytes.Clone(a.key)
27新增: a.lock()
28新增: a, err = loadLocalAccount(profile)
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: if err = a.trustedLogin("resume", "", t.TempDir()); err == nil {
33新增: t.Fatal("untrusted OS profile opened workspace")
34新增: }
35新增: if err = a.trustedLogin("resume", "", devices); err != nil || !bytes.Equal(original, a.key) {
36新增: t.Fatal("restart lost workspace", err)
37新增: }
38新增: if err = a.trustedLogin("protect", "123", devices); err == nil {
39新增: t.Fatal("accepted short password")
40新增: }
41新增: if err = a.trustedLogin("protect", "first-password", devices); err != nil {
42新增: t.Fatal(err)
43新增: }
44新增: if err = a.trustedLogin("create", "", devices); err == nil {
45新增: t.Fatal("overwrote password account")
46新增: }
47新增: a.lock()
48新增: if err = a.trustedLogin("resume", "", devices); err == nil {
49新增: t.Fatal("stale device grant")
50新增: }
51新增: if err = a.unlock("first-password"); err != nil || !bytes.Equal(original, a.key) {
52新增: t.Fatal("password conversion lost workspace", err)
53新增: }
54新增: if err = a.trustedLogin("enable", "first-password", devices); err != nil {
55新增: t.Fatal(err)
56新增: }
57新增: a.lock()
58新增: if err = a.trustedLogin("resume", "", devices); err != nil || !bytes.Equal(original, a.key) {
59新增: t.Fatal("password account failed automatic unlock", err)
60新增: }
61新增: if err = a.lockAccess(false); err != nil {
62新增: t.Fatal(err)
63新增: }
64新增: if err = a.trustedLogin("resume", "", devices); err == nil {
65新增: t.Fatal("ignored explicit lock")
66新增: }
67新增: if err = a.unlock("first-password"); err != nil {
68新增: t.Fatal(err)
69新增: }
70新增: if err = a.lockAccess(true); err != nil {
71新增: t.Fatal(err)
72新增: }
73新增: a, err = loadLocalAccount(profile)
74新增: if err != nil {
75新增: t.Fatal(err)
76新增: }
77新增: if a.view().TrustedLogin || a.trustedLogin("resume", "", devices) == nil {
78新增: t.Fatal("logout retained trust")
79新增: }
80新增:}
81新增:
82新增:func TestTrustedLocalLauncherBoundary(t *testing.T) {
83新增: s := testServer(t)
84新增: if w := request(s, "POST", "/api/desktop-local/trusted-login", s.origin, `{"action":"resume"}`, true); w.Code != http.StatusUnauthorized {
85新增: t.Fatalf("ordinary session reached launcher action: %d", w.Code)
86新增: }
87新增: if w := request(s, "POST", "/api/account/trusted-login", s.origin, `{}`, true); w.Code != http.StatusNotFound {
88新增: t.Fatalf("ordinary account route accepted trusted action: %d", w.Code)
89新增: }
90新增:}
91新增:
92新增:func TestTrustedLocalUnlockIsPrivateToDesktop(t *testing.T) {
93新增: s := testServer(t)
94新增: a, err := loadLocalAccount(s.profile)
95新增: if err != nil {
96新增: t.Fatal(err)
97新增: }
98新增: s.account = a
99新增: if err = a.trustedLogin("create", "", t.TempDir()); err != nil {
100新增: t.Fatal(err)
101新增: }
102新增: if !a.viewFor(true).Unlocked || a.viewFor(false).Unlocked {
103新增: t.Fatal("trusted login escaped desktop view")
104新增: }
105新增: if response := request(s, "GET", "/api/favorites", "", "", true); response.Code != http.StatusLocked {
106新增: t.Fatalf("session cookie alone opened favorites: %d", response.Code)
107新增: }
108新增: if response := request(s, "POST", "/api/account/profile", s.origin, `{"username":"Different"}`, true); response.Code != http.StatusLocked {
109新增: t.Fatalf("session cookie alone changed profile: %d", response.Code)
110新增: }
111新增: req, _ := http.NewRequest("GET", s.origin, nil)
112新增: req.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
113新增: if !s.hasTrustedView(req) {
114新增: t.Fatal("local launcher proof was refused")
115新增: }
116新增:}
117新增:
118新增:func TestTrustedLocalDesktopEntryAndWorkload(t *testing.T) {
119新增: for _, env := range []string{"LOCALAPPDATA", "XDG_CONFIG_HOME", "HOME"} {
120新增: t.Setenv(env, t.TempDir())
121新增: }
122新增: workload := testServer(t)
123新增: var err error
124新增: workload.account, err = loadLocalAccount(workload.profile)
125新增: if err != nil {
126新增: t.Fatal(err)
127新增: }
128新增: workload.instanceID = randomToken()
129新增: server := httptest.NewUnstartedServer(workload.handler())
130新增: port := server.Listener.Addr().(*net.TCPAddr).Port
131新增: workload.origin = "http://localhost:" + strconv.Itoa(port)
132新增: server.Start()
133新增: defer server.Close()
134新增: record := controlFile{Port: port, PID: os.Getpid(), Token: workload.token}
135新增: if err = writePrivate(filepath.Join(workload.profile, "control.json"), record); err != nil {
136新增: t.Fatal(err)
137新增: }
138新增: c, err := openController(workload.profile)
139新增: if err != nil {
140新增: t.Fatal(err)
141新增: }
142新增: defer c.close()
143新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
144新增: defer cancel()
145新增: local := &desktopLocal{profile: workload.profile}
146新增: session, err := local.localSession(ctx, ctx, c, desktopLocalReply{Identity: workload.identity, InstanceID: workload.instanceID})
147新增: if err != nil {
148新增: t.Fatal(err)
149新增: }
150新增: defer session.Close()
151新增: gateway := testServer(t)
152新增: gateway.remote = newDesktopGateway(gateway.profile, local)
153新增: d := gateway.remote.desktop
154新增: d.active = &desktopTarget{id: d.generation, mode: "local", ctx: ctx, session: session}
155新增: body, _ := json.Marshal(trustedLoginRequest{Action: "create", ConnectionID: d.generation})
156新增: w := request(gateway, "POST", "/api/client/trusted-login", gateway.origin, string(body), true)
157新增: if w.Code != http.StatusOK {
158新增: t.Fatalf("trust creation through gateway: %d %s", w.Code, w.Body.String())
159新增: }
160新增: read := gatewayRequest(gateway, "/api/account", d.generation)
161新增: var view accountView
162新增: if read.Code != 200 || json.Unmarshal(read.Body.Bytes(), &view) != nil || !view.Unlocked || !view.TrustedLocal {
163新增: t.Fatalf("local gateway cannot see unlocked account: %s", read.Body.String())
164新增: }
165新增: workload.account.lock()
166新增: body, _ = json.Marshal(trustedLoginRequest{Action: "resume", ConnectionID: d.generation})
167新增: w = request(gateway, "POST", "/api/client/trusted-login", gateway.origin, string(body), true)
168新增: if w.Code != http.StatusOK || !workload.account.view().Unlocked {
169新增: t.Fatalf("local resume failed: %d %s", w.Code, w.Body.String())
170新增: }
171新增:}
修改internal/workbench/vault_store.go+3 −0看文件
@@ -163,6 +163,9 @@ func (db *vaultData) save(entry vaultEntry) error {
163163func (a *localAccount) verifyVaultPassword(password string) error {
164164 a.mu.Lock()
165165 defer a.mu.Unlock()
166新增: if a.record != nil && a.record.TrustedDevice != "" {
167新增: return errors.New("查看或复制密码前,请在本机的「设置 → 账户」设置密码")
168新增: }
166169 if len(a.key) != 32 {
167170 return errors.New("请先解锁 Cage")
168171 }
修改ui/src/account.css+2 −0看文件
@@ -321,3 +321,5 @@
321321.account-device-option small { color: var(--muted); font-size: 12px; line-height: 1.6; }
322322
323323.account-trigger[aria-expanded="false"] > svg { transform: rotate(180deg); }
324新增:
325新增:.account-trust-choice { display: grid; gap: 12px; margin: 16px 0; }
修改ui/src/account.jsx+86 −15看文件
@@ -18,12 +18,16 @@ import {
1818 Settings2,
1919} from "lucide-react";
2020import { api, native, nativeAvailable } from "./api";
21删除:import { isRemoteClient } from "./client-context.mjs";
21新增:import { getClientContext, isRemoteClient } from "./client-context.mjs";
2222import logo from "./logo.png";
2323import "./account.css";
2424
2525const AccountContext = createContext(null);
2626export const useAccount = () => useContext(AccountContext);
27新增:const localDesktop = () => getClientContext().desktop_gateway && !isRemoteClient();
28新增:const trustedLogin = (action, password) => api("/client/trusted-login", {
29新增: action, password, connection_id: getClientContext().connection_id,
30新增:});
2731const credentialPresent = (status) => status === "available" || status === "authentication_required";
2832
2933export function AccountProvider({ children }) {
@@ -180,6 +184,20 @@ export function AccountGate({ children }) {
180184 const [error, setError] = useState("");
181185 const automaticAttempt = useRef("");
182186 const gateAcknowledged = useRef(false);
187新增: const [passwordSetup, setPasswordSetup] = useState(false);
188新增: const trustedAttempt = useRef(false);
189新增: const enterTrusted = async (action) => {
190新增: setBusy(true); setError("");
191新增: try { await trustedLogin(action); await refresh(); }
192新增: catch (e) { setError(e.message); }
193新增: finally { setBusy(false); }
194新增: };
195新增: useEffect(() => {
196新增: if (account?.unlocked) { trustedAttempt.current = false; return; }
197新增: if (!(account?.trusted_local || account?.trusted_login) || !localDesktop() || trustedAttempt.current || account.require_authentication) return;
198新增: trustedAttempt.current = true;
199新增: void enterTrusted("resume");
200新增: }, [account?.unlocked, account?.trusted_local, account?.trusted_login, account?.require_authentication]);
183201 useEffect(() => {
184202 if (!account || account.unlocked || connectionError || gateAcknowledged.current || !nativeAvailable()) return;
185203 // A working lock/setup screen is a valid upgraded UI. Waiting for the
@@ -190,7 +208,7 @@ export function AccountGate({ children }) {
190208 }, [Boolean(account), account?.unlocked, connectionError]);
191209 useEffect(() => {
192210 const id = account?.devices?.automatic;
193删除: if (!id || account.unlocked || account.require_authentication || !deviceSupport?.supported || deviceSupport.device_status?.automatic !== "available" || automaticAttempt.current === id) return;
211新增: if ((account?.trusted_login && localDesktop()) || !id || account.unlocked || account.require_authentication || !deviceSupport?.supported || deviceSupport.device_status?.automatic !== "available" || automaticAttempt.current === id) return;
194212 automaticAttempt.current = id;
195213 setBusy(true);
196214 deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false));
@@ -258,9 +276,9 @@ export function AccountGate({ children }) {
258276 </h1>
259277 <p className="account-entry-intro">
260278 {creating
261删除: ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : "创建一个本地账户,收好你的工作与登录状态。"
279新增: ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : localDesktop() && !passwordSetup ? "选择这台电脑的登录方式。" : "创建一个本地账户,收好你的工作与登录状态。"
262280 : account
263删除: ? "输入密码,继续你的工作。"
281新增: ? account.trusted_local ? "本机工作区" : "输入密码,继续你的工作。"
264282 : isRemoteClient() ? "正在读取云端账户…" : "正在读取本机账户…"}
265283 </p>
266284 {account?.background_running && (
@@ -269,7 +287,23 @@ export function AccountGate({ children }) {
269287 后台环境仍在运行,任务没有停止
270288 </div>
271289 )}
272删除: {account && (
290新增: {localDesktop() && creating && (
291新增: <div className="account-trust-choice">
292新增: {!passwordSetup && <>
293新增: <p>信任此电脑后,下次使用当前系统用户打开 Cage 会直接进入。</p>
294新增: <button className="primary account-submit" disabled={busy} onClick={() => enterTrusted("create")}>信任此电脑并进入</button>
295新增: </>}
296新增: <button className="text-button" disabled={busy} onClick={() => setPasswordSetup(!passwordSetup)}>
297新增: {passwordSetup ? "返回本机免账号登录" : "使用用户名和密码"}
298新增: </button>
299新增: </div>
300新增: )}
301新增: {account?.trusted_local && <div className="account-trust-choice">
302新增: <p>{localDesktop() ? "使用当前系统用户的本机信任凭据进入工作区。" : "请回到受信任的桌面设置账户密码,再从此处登录。"}</p>
303新增: {localDesktop() && <button className="quiet-button" disabled={busy} onClick={() => enterTrusted("resume")}>{busy ? "正在进入…" : "重新进入本机工作区"}</button>}
304新增: </div>}
305新增: {(account?.trusted_local || (creating && localDesktop() && !passwordSetup)) && error && <p className="account-error" role="alert">{error}</p>}
306新增: {account && !account.trusted_local && (!creating || !localDesktop() || passwordSetup) && (
273307 <form onSubmit={submit}>
274308 <fieldset disabled={busy}>
275309 {creating && (
@@ -352,11 +386,11 @@ export function AccountGate({ children }) {
352386 <LockKeyhole size={14} />
353387 {isRemoteClient() ? "账户资料保存在当前云端主机" : "账户资料仅保存在这台设备上"}
354388 </p>
355删除: <p className="account-recovery-note">
389新增: {(!localDesktop() || passwordSetup || account?.exists) && !account?.trusted_local && <p className="account-recovery-note">
356390 {creating
357391 ? "密码至少 8 个字符,用于保护应用登录凭据。请妥善保存,当前不支持在线找回。"
358392 : isRemoteClient() ? "请输入云端 Cage 账户密码;当前不支持在线找回。" : "请输入本地账户密码;当前不支持在线找回。"}
359删除: </p>
393新增: </p>}
360394 </section>
361395 {nativeAvailable() && (
362396 <button
@@ -425,7 +459,7 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) {
425459 <AccountAvatar account={account} />
426460 <span className="account-trigger-name">
427461 <strong>{account.username}</strong>
428删除: <small>{isRemoteClient() ? "云端账户" : "本地账户"}</small>
462新增: <small>{account.trusted_local ? "受信任的本机" : isRemoteClient() ? "云端账户" : "本地账户"}</small>
429463 </span>
430464 <ChevronDown size={15} />
431465 </button>
@@ -450,6 +484,9 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) {
450484 <Settings2 size={16} />
451485 设置
452486 </button>
487新增: {account.trusted_local ? <button role="menuitem" onClick={() => { setOpen(false); onSettings("account"); }}>
488新增: <LockKeyhole size={16} /> 设置账户密码
489新增: </button> : <>
453490 <div className="account-menu-divider" />
454491 <button role="menuitem" onClick={() => perform("lock")}>
455492 <LockKeyhole size={16} />
@@ -462,7 +499,7 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) {
462499 >
463500 <LogOut size={16} />
464501 退出账户
465删除: </button>
502新增: </button></>}
466503 </div>
467504 )}
468505 </div>
@@ -470,7 +507,7 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) {
470507}
471508
472509export function AccountSettings({ busy: environmentBusy, onDirty }) {
473删除: const { account, act } = useAccount();
510新增: const { account, act, refresh } = useAccount();
474511 const [name, setName] = useState(account.username),
475512 [avatar, setAvatar] = useState(account.avatar || "");
476513 const [oldPassword, setOldPassword] = useState(""),
@@ -519,6 +556,13 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) {
519556 setError("");
520557 setMessage("");
521558 try {
559新增: if (changingPassword && account.trusted_local) {
560新增: await trustedLogin("protect", password);
561新增: await refresh();
562新增: setPassword(""); setConfirmation("");
563新增: setMessage("已设置密码,下次打开 Cage 时使用密码登录。");
564新增: return;
565新增: }
522566 const value = await act(
523567 changingPassword ? "password" : "profile",
524568 changingPassword
@@ -628,11 +672,11 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) {
628672 <p className="field-help">
629673 修改密码不会清除 Claude 的登录状态。{isRemoteClient() ? "密码用于解锁当前云端 Cage,没有在线找回。" : "密码仅用于本机解锁,没有在线找回。"}
630674 </p>
631删除: <PasswordField
675新增: {!account.trusted_local && <PasswordField
632676 label="当前密码"
633677 value={oldPassword}
634678 onChange={setOldPassword}
635删除: />
679新增: />}
636680 <PasswordField
637681 label="新密码"
638682 value={password}
@@ -647,15 +691,16 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) {
647691 />
648692 <button
649693 className="quiet-button"
650删除: disabled={busy || !oldPassword || !password || !confirmation}
694新增: disabled={busy || (!account.trusted_local && !oldPassword) || !password || !confirmation}
651695 >
652删除: 修改密码
696新增: {account.trusted_local ? "设置密码并关闭免账号登录" : "修改密码"}
653697 </button>
654698 </fieldset>
655699 </form>
656700
657701 {feedbackTarget === "password" && feedback}
658删除: <AccountDeviceSettings />
702新增: {localDesktop() && !account.trusted_local && <TrustedDeviceSettings />}
703新增: {!account.trusted_local && <AccountDeviceSettings />}
659704 <p className="account-settings-note">
660705 <LockKeyhole size={15} />
661706 {isRemoteClient() ? "账户、应用资料与登录凭据保存在当前云端主机。" : "一个本地账户,一个持久工作环境。资料与凭据不上传到 Cage 服务器。"}
@@ -664,6 +709,32 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) {
664709 );
665710}
666711
712新增:function TrustedDeviceSettings() {
713新增: const { account, refresh } = useAccount();
714新增: const [password, setPassword] = useState("");
715新增: const [message, setMessage] = useState("");
716新增: const [busy, setBusy] = useState(false);
717新增: const update = async (event) => {
718新增: event.preventDefault();
719新增: setBusy(true); setMessage("");
720新增: try {
721新增: await trustedLogin(account.trusted_login ? "disable" : "enable", password);
722新增: setPassword("");
723新增: await refresh();
724新增: } catch (error) { setMessage(error.message); }
725新增: finally { setBusy(false); }
726新增: };
727新增: return <form onSubmit={update}>
728新增: <fieldset disabled={busy}>
729新增: <h4>信任此电脑</h4>
730新增: <p className="field-help">{account.trusted_login ? "已开启本机自动登录。手动锁定仍需验证,退出账户会撤销信任。" : "验证一次账户密码,下次用当前系统用户打开时自动进入。"}</p>
731新增: {!account.trusted_login && <PasswordField label="验证账户密码" value={password} onChange={setPassword} autoComplete="current-password" />}
732新增: <button className="quiet-button" disabled={!account.trusted_login && !password}>{account.trusted_login ? "关闭本机信任" : "信任此电脑"}</button>
733新增: {message && <p className="account-error" role="alert">{message}</p>}
734新增: </fieldset>
735新增: </form>;
736新增:}
737新增:
667738function AccountDeviceSettings() {
668739 const { account, deviceSupport, deviceAction, recheckDevices } = useAccount();
669740 const [busy, setBusy] = useState(false);