跳到主要内容

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

浏览文件

macos_profile.go

212 行 · 6.2 KB历史下载
1package guestos
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "github.com/google/uuid"
11 "os"
12 "path/filepath"
13 "regexp"
14
15 "golang.org/x/crypto/ssh"
16)
17
18// MacOSProfile binds one prepared local VZ guest to its ordinary development account.
19type MacOSProfile struct {
20 Version int `json:"version"`
21 Instance string `json:"instance"`
22 User string `json:"user"`
23 MachineID string `json:"machineID"`
24 SetupID string `json:"initial_setup,omitempty"`
25}
26
27var macUser = regexp.MustCompile(`^[a-z][a-z0-9_]{0,30}$`)
28
29// New accounts must not collide with macOS or Cage's provisioning identities.
30func ValidMacOSAccountName(name string) bool {
31 if !macUser.MatchString(name) {
32 return false
33 }
34 switch name {
35 case "root", "daemon", "nobody", "guest", "cageprovision", "cagesetup":
36 return false
37 }
38 return true
39}
40
41func macMachineID(profile string) (string, error) {
42 path := filepath.Join(profile, "state", "lima", "mac", "vz-identifier")
43 info, err := os.Lstat(path)
44 if err != nil {
45 return "", err
46 }
47 if !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > 4096 {
48 return "", errors.New("invalid Apple virtual machine identifier")
49 }
50 data, err := os.ReadFile(path)
51 if err != nil {
52 return "", err
53 }
54 sum := sha256.Sum256(data)
55 return hex.EncodeToString(sum[:]), nil
56}
57
58func LoadMacOSProfile(profile string) (*MacOSProfile, error) {
59 path := filepath.Join(profile, "macos-guest.json")
60 info, err := os.Lstat(path)
61 if errors.Is(err, os.ErrNotExist) {
62 return nil, nil
63 }
64 if err != nil {
65 return nil, err
66 }
67 if !info.Mode().IsRegular() || info.Size() > 4096 {
68 return nil, errors.New("invalid macOS guest profile")
69 }
70 data, err := os.ReadFile(path)
71 if err != nil {
72 return nil, err
73 }
74 var m MacOSProfile
75 if err := json.Unmarshal(data, &m); err != nil {
76 return nil, err
77 }
78 if m.Version != 1 || m.Instance != "mac" || !macUser.MatchString(m.User) || m.User == "root" {
79 return nil, errors.New("invalid macOS guest profile or login")
80 }
81 if m.SetupID != "" && !validSetupID(m.SetupID) {
82 return nil, errors.New("invalid first setup identity")
83 }
84 id, err := macMachineID(profile)
85 if err != nil {
86 return nil, err
87 }
88 if id != m.MachineID {
89 return nil, errors.New("the macOS guest differs from the machine bound to this profile")
90 }
91 return &m, nil
92}
93
94// BindMacOSProfile takes an independently obtained guest host public key. Do
95// not discover this key by scanning an unverified localhost SSH port.
96func BindMacOSProfile(profile, user string, hostKey []byte) error {
97 return bindMacOSProfile(profile, user, hostKey, "")
98}
99
100// BindNewMacOSProfile is called only by the fresh, resumable installer.
101func BindNewMacOSProfile(profile, user string, hostKey []byte, id uuid.UUID) error {
102 install, err := LoadInstallation(profile)
103 if err != nil {
104 return err
105 }
106 if install == nil || id == uuid.Nil || install.ID != id || install.System != MacOS {
107 return errors.New("首次设置与当前安装记录不匹配")
108 }
109 return bindMacOSProfile(profile, user, hostKey, id.String())
110}
111
112func validSetupID(id string) bool {
113 value, err := uuid.Parse(id)
114 return err == nil && value != uuid.Nil && value.String() == id
115}
116
117func bindMacOSProfile(profile, user string, hostKey []byte, setupID string) error {
118 if !macUser.MatchString(user) || user == "root" {
119 return errors.New("supply the short name of the ordinary macOS guest account")
120 }
121 key, _, options, rest, err := ssh.ParseAuthorizedKey(hostKey)
122 if err != nil || len(options) != 0 || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 {
123 return errors.New("expected one Ed25519 guest SSH host public key")
124 }
125 id, err := macMachineID(profile)
126 if err != nil {
127 return err
128 }
129 m := MacOSProfile{Version: 1, Instance: "mac", User: user, MachineID: id, SetupID: setupID}
130 data, err := json.Marshal(m)
131 if err != nil {
132 return err
133 }
134 if current, err := LoadMacOSProfile(profile); err != nil {
135 return err
136 } else if current != nil && *current != m {
137 return errors.New("this profile is already bound to another macOS guest account")
138 }
139 if err := publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), ssh.MarshalAuthorizedKey(key)...)); err != nil {
140 return err
141 }
142 return publishBinding(profile, "macos-guest.json", append(data, '\n'))
143}
144
145func publishBinding(profile, name string, data []byte) error {
146 temp, err := os.CreateTemp(profile, ".guest-binding-*")
147 if err != nil {
148 return err
149 }
150 defer os.Remove(temp.Name())
151 _, writeErr := temp.Write(data)
152 if err := errors.Join(writeErr, temp.Close()); err != nil {
153 return err
154 }
155 path := filepath.Join(profile, name)
156 if err := os.Link(temp.Name(), path); !errors.Is(err, os.ErrExist) {
157 return err
158 }
159 info, err := os.Lstat(path)
160 if err != nil || !info.Mode().IsRegular() || info.Size() != int64(len(data)) {
161 return fmt.Errorf("unexpected existing %s", name)
162 }
163 prior, err := os.ReadFile(path)
164 if err != nil || !bytes.Equal(data, prior) {
165 return fmt.Errorf("refusing to replace existing %s", name)
166 }
167 return nil
168}
169
170// PinMacOSInstallHostKey persists only the host key, without enabling the workbench.
171func PinMacOSInstallHostKey(profile string) error {
172 key, err := MacOSInstallHostKey(profile)
173 if err != nil {
174 return err
175 }
176 return publishBinding(profile, "macos-known-hosts", append([]byte("cage-macos "), key...))
177}
178
179// FinishMacOSSetup removes the installation identity from the existing binding.
180// Binding publication is create-only, so retrying an installer cannot reopen it.
181func FinishMacOSSetup(profile, setupID string) error {
182 bound, err := LoadMacOSProfile(profile)
183 if err != nil {
184 return err
185 }
186 if bound == nil || !validSetupID(setupID) || bound.SetupID != setupID {
187 return errors.New("首次设置已关闭或安装实例已变更")
188 }
189 bound.SetupID = ""
190 data, err := json.Marshal(bound)
191 if err != nil {
192 return err
193 }
194 f, err := os.CreateTemp(profile, ".finish-guest-setup-*")
195 if err != nil {
196 return err
197 }
198 defer os.Remove(f.Name())
199 _, writeErr := f.Write(append(data, '\n'))
200 if err = errors.Join(writeErr, f.Sync(), f.Close()); err != nil {
201 return err
202 }
203 if err = os.Rename(f.Name(), filepath.Join(profile, "macos-guest.json")); err != nil {
204 return err
205 }
206 dir, err := os.Open(profile)
207 if err != nil {
208 return err
209 }
210 defer dir.Close()
211 return dir.Sync()
212}