| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/aes" |
| 7 | "crypto/cipher" |
| 8 | "crypto/rand" |
| 9 | "encoding/base64" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "image" |
| 13 | _ "image/jpeg" |
| 14 | "image/png" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | "unicode/utf8" |
| 21 | |
| 22 | "github.com/sylvinus/agent-vm/internal/host" |
| 23 | "golang.org/x/crypto/argon2" |
| 24 | ) |
| 25 | |
| 26 | type accountRecord struct { |
| 27 | MacLogin *macAccountEnvelope `json:"mac_login,omitempty"` |
| 28 | TrustedDevice string `json:"trusted_device,omitempty"` |
| 29 | TrustedUnlock *accountDevice `json:"trusted_unlock,omitempty"` |
| 30 | Version int `json:"version"` |
| 31 | Username string `json:"username"` |
| 32 | Avatar string `json:"avatar,omitempty"` |
| 33 | Salt []byte `json:"salt"` |
| 34 | Nonce []byte `json:"nonce"` |
| 35 | SealedKey []byte `json:"sealed_key"` |
| 36 | Devices map[string]accountDevice `json:"devices,omitempty"` |
| 37 | RequireAuthentication bool `json:"require_authentication,omitempty"` |
| 38 | } |
| 39 | |
| 40 | type localAccount struct { |
| 41 | macSync sync.Mutex |
| 42 | mu sync.Mutex |
| 43 | path string |
| 44 | record *accountRecord |
| 45 | trustedSession bool |
| 46 | key []byte |
| 47 | vaultLease string |
| 48 | epoch context.Context |
| 49 | cancel context.CancelFunc |
| 50 | nextAttempt time.Time |
| 51 | } |
| 52 | |
| 53 | type accountView struct { |
| 54 | MacOSAccountHost bool `json:"macos_account_host,omitempty"` |
| 55 | MacOSCredentialsReady bool `json:"macos_credentials_ready,omitempty"` |
| 56 | MacOSUsernameBound bool `json:"macos_username_bound,omitempty"` |
| 57 | MacOSPasswordPending bool `json:"macos_password_pending,omitempty"` |
| 58 | MacOSGuestUser string `json:"macos_guest_user,omitempty"` |
| 59 | InitialMacSetup bool `json:"initial_mac_setup,omitempty"` |
| 60 | GuestSystem string `json:"guest_system,omitempty"` |
| 61 | TrustedLocal bool `json:"trusted_local,omitempty"` |
| 62 | TrustedLogin bool `json:"trusted_login,omitempty"` |
| 63 | Exists bool `json:"exists"` |
| 64 | Unlocked bool `json:"unlocked"` |
| 65 | Username string `json:"username"` |
| 66 | Avatar string `json:"avatar,omitempty"` |
| 67 | BackgroundRunning bool `json:"background_running"` |
| 68 | DeviceBinding string `json:"device_binding"` |
| 69 | Devices map[string]string `json:"devices,omitempty"` |
| 70 | RequireAuthentication bool `json:"require_authentication"` |
| 71 | } |
| 72 | |
| 73 | func loadLocalAccount(profile string) (*localAccount, error) { |
| 74 | a := &localAccount{path: filepath.Join(profile, "account.json")} |
| 75 | b, err := os.ReadFile(a.path) |
| 76 | if os.IsNotExist(err) { |
| 77 | return a, nil |
| 78 | } |
| 79 | if err != nil { |
| 80 | return nil, errors.New("无法读取本地账户,请检查配置目录") |
| 81 | } |
| 82 | if err = host.CheckPrivateFile(a.path); err != nil { |
| 83 | return nil, errors.New("本地账户文件权限不安全,请恢复私有文件权限") |
| 84 | } |
| 85 | var record accountRecord |
| 86 | 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 { |
| 87 | return nil, errors.New("本地账户文件损坏,请从备份恢复;已有数据未修改") |
| 88 | } |
| 89 | if device := record.TrustedUnlock; device != nil && (len(device.ID) != 64 || !validTrustedID(device.ID) || len(device.Nonce) != 12 || len(device.SealedKey) != 48 || record.TrustedDevice != "") { |
| 90 | return nil, errors.New("本机信任记录损坏,请从备份恢复") |
| 91 | } |
| 92 | a.record = &record |
| 93 | for kind, device := range record.Devices { |
| 94 | if !validDeviceKind(kind) || len(device.ID) != 32 || len(device.Nonce) != 12 || len(device.SealedKey) != 48 { |
| 95 | return nil, errors.New("本地账户快捷登录记录损坏,请从备份恢复") |
| 96 | } |
| 97 | } |
| 98 | return a, nil |
| 99 | } |
| 100 | |
| 101 | func validAccountName(name string) error { |
| 102 | if strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 40 || strings.ContainsAny(name, "\x00\r\n") { |
| 103 | return errors.New("用户名需要 1–40 个字符,不能包含换行") |
| 104 | } |
| 105 | return nil |
| 106 | } |
| 107 | |
| 108 | func validAccountPassword(password string) error { |
| 109 | if utf8.RuneCountInString(password) < 8 || len(password) > 1024 || strings.ContainsRune(password, 0) { |
| 110 | return errors.New("密码至少 8 个字符,最多 1024 字节") |
| 111 | } |
| 112 | return nil |
| 113 | } |
| 114 | |
| 115 | func sealAccountKey(record *accountRecord, password string, key []byte) error { |
| 116 | record.Salt = make([]byte, 16) |
| 117 | if _, err := rand.Read(record.Salt); err != nil { |
| 118 | return err |
| 119 | } |
| 120 | derived := argon2.IDKey([]byte(password), record.Salt, 3, 64*1024, 2, 32) |
| 121 | defer clear(derived) |
| 122 | block, err := aes.NewCipher(derived) |
| 123 | if err != nil { |
| 124 | return err |
| 125 | } |
| 126 | aead, err := cipher.NewGCM(block) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | record.Nonce = make([]byte, aead.NonceSize()) |
| 131 | if _, err = rand.Read(record.Nonce); err != nil { |
| 132 | return err |
| 133 | } |
| 134 | record.SealedKey = aead.Seal(nil, record.Nonce, key, []byte("Cage local account v1")) |
| 135 | return nil |
| 136 | } |
| 137 | |
| 138 | func openAccountKey(record *accountRecord, password string) ([]byte, error) { |
| 139 | if len(password) > 1024 { |
| 140 | return nil, errors.New("密码不正确") |
| 141 | } |
| 142 | derived := argon2.IDKey([]byte(password), record.Salt, 3, 64*1024, 2, 32) |
| 143 | defer clear(derived) |
| 144 | block, _ := aes.NewCipher(derived) |
| 145 | aead, _ := cipher.NewGCM(block) |
| 146 | key, err := aead.Open(nil, record.Nonce, record.SealedKey, []byte("Cage local account v1")) |
| 147 | if err != nil { |
| 148 | return nil, errors.New("密码不正确") |
| 149 | } |
| 150 | return key, nil |
| 151 | } |
| 152 | |
| 153 | func (a *localAccount) view() accountView { return a.viewFor(true) } |
| 154 | |
| 155 | func (a *localAccount) viewFor(desktop bool) accountView { |
| 156 | if a == nil { |
| 157 | return accountView{} |
| 158 | } |
| 159 | a.mu.Lock() |
| 160 | defer a.mu.Unlock() |
| 161 | v := accountView{Exists: a.record != nil, Unlocked: len(a.key) == 32 && (!a.trustedSession || desktop)} |
| 162 | v.DeviceBinding = fmtAccountBinding(a.path) |
| 163 | if a.record != nil { |
| 164 | if a.record.MacLogin != nil && v.Unlocked { |
| 165 | if login, err := a.openMacAccount(); err == nil { |
| 166 | v.MacOSCredentialsReady = true |
| 167 | v.MacOSUsernameBound = len(login.Guests) != 0 |
| 168 | for _, guest := range login.Guests { |
| 169 | v.MacOSPasswordPending = v.MacOSPasswordPending || guest.Password != login.Password |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | v.TrustedLocal = a.record.TrustedDevice != "" |
| 174 | v.TrustedLogin = a.record.TrustedUnlock != nil |
| 175 | v.Username = a.record.Username |
| 176 | v.Avatar = a.record.Avatar |
| 177 | v.RequireAuthentication = a.record.RequireAuthentication |
| 178 | v.Devices = make(map[string]string) |
| 179 | for kind, device := range a.record.Devices { |
| 180 | v.Devices[kind] = device.ID |
| 181 | } |
| 182 | } |
| 183 | return v |
| 184 | } |
| 185 | |
| 186 | func (a *localAccount) access() (context.Context, bool) { return a.accessFor(true) } |
| 187 | |
| 188 | func (a *localAccount) accessFor(desktop bool) (context.Context, bool) { |
| 189 | if a == nil { |
| 190 | return nil, false |
| 191 | } |
| 192 | a.mu.Lock() |
| 193 | defer a.mu.Unlock() |
| 194 | return a.epoch, len(a.key) == 32 && (!a.trustedSession || desktop) |
| 195 | } |
| 196 | |
| 197 | func (a *localAccount) setKey(key []byte) { |
| 198 | if a.cancel != nil { |
| 199 | a.cancel() |
| 200 | } |
| 201 | clear(a.key) |
| 202 | a.key = key |
| 203 | a.trustedSession = false |
| 204 | a.vaultLease = randomToken() |
| 205 | a.epoch, a.cancel = context.WithCancel(context.Background()) |
| 206 | } |
| 207 | |
| 208 | func (a *localAccount) lock() { |
| 209 | if a == nil { |
| 210 | return |
| 211 | } |
| 212 | a.mu.Lock() |
| 213 | defer a.mu.Unlock() |
| 214 | if a.cancel != nil { |
| 215 | a.cancel() |
| 216 | a.cancel = nil |
| 217 | } |
| 218 | clear(a.key) |
| 219 | a.key = nil |
| 220 | } |
| 221 | |
| 222 | func (a *localAccount) create(name, password, avatar string) error { |
| 223 | return a.createAccount(name, password, avatar, false) |
| 224 | } |
| 225 | |
| 226 | func (a *localAccount) createAccount(name, password, avatar string, mac bool) error { |
| 227 | name = strings.TrimSpace(name) |
| 228 | if mac { |
| 229 | if err := validMacAccount(name, password); err != nil { |
| 230 | return err |
| 231 | } |
| 232 | } |
| 233 | if err := validAccountName(name); err != nil { |
| 234 | return err |
| 235 | } |
| 236 | if err := validAccountPassword(password); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | normalized, err := normalizeAccountAvatar(avatar) |
| 240 | if err != nil { |
| 241 | return err |
| 242 | } |
| 243 | a.mu.Lock() |
| 244 | defer a.mu.Unlock() |
| 245 | if a.record != nil { |
| 246 | return errors.New("此配置已创建本地账户,请登录") |
| 247 | } |
| 248 | key := make([]byte, 32) |
| 249 | if _, err = rand.Read(key); err != nil { |
| 250 | return err |
| 251 | } |
| 252 | defer clear(key) |
| 253 | record := &accountRecord{Version: 1, Username: name, Avatar: normalized} |
| 254 | if err = sealAccountKey(record, password, key); err != nil { |
| 255 | return err |
| 256 | } |
| 257 | if mac { |
| 258 | if err = sealMacAccount(record, key, macAccountData{Password: password}); err != nil { |
| 259 | return err |
| 260 | } |
| 261 | } |
| 262 | if err = writePrivate(a.path, record); err != nil { |
| 263 | return errors.New("账户未能保存,请检查磁盘空间与目录权限") |
| 264 | } |
| 265 | a.record = record |
| 266 | a.setKey(append([]byte(nil), key...)) |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | func (a *localAccount) unlock(password string) error { |
| 271 | a.mu.Lock() |
| 272 | defer a.mu.Unlock() |
| 273 | if a.record == nil { |
| 274 | return errors.New("请先创建本地账户") |
| 275 | } |
| 276 | if time.Now().Before(a.nextAttempt) { |
| 277 | return errors.New("请稍后再试") |
| 278 | } |
| 279 | key, err := openAccountKey(a.record, password) |
| 280 | if err != nil { |
| 281 | a.nextAttempt = time.Now().Add(time.Second) |
| 282 | return err |
| 283 | } |
| 284 | a.nextAttempt = time.Time{} |
| 285 | if err = a.clearAuthenticationRequirement(); err != nil { |
| 286 | clear(key) |
| 287 | return err |
| 288 | } |
| 289 | a.setKey(key) |
| 290 | return nil |
| 291 | } |
| 292 | |
| 293 | func (a *localAccount) updateProfile(name, avatar string) error { |
| 294 | name = strings.TrimSpace(name) |
| 295 | if err := validAccountName(name); err != nil { |
| 296 | return err |
| 297 | } |
| 298 | normalized, err := normalizeAccountAvatar(avatar) |
| 299 | if err != nil { |
| 300 | return err |
| 301 | } |
| 302 | a.mu.Lock() |
| 303 | defer a.mu.Unlock() |
| 304 | if len(a.key) != 32 { |
| 305 | return errors.New("请先解锁 Cage") |
| 306 | } |
| 307 | if a.record.MacLogin != nil && name != a.record.Username { |
| 308 | login, err := a.openMacAccount() |
| 309 | if err != nil { |
| 310 | return err |
| 311 | } |
| 312 | if len(login.Guests) != 0 { |
| 313 | return errors.New("用户名已用于 macOS 客机,保留该名称以继续使用原账户和文件") |
| 314 | } |
| 315 | if err := validMacAccount(name, login.Password); err != nil { |
| 316 | return err |
| 317 | } |
| 318 | } |
| 319 | record := *a.record |
| 320 | record.Username = name |
| 321 | record.Avatar = normalized |
| 322 | if err = writePrivate(a.path, record); err != nil { |
| 323 | return errors.New("资料未能保存,请重试") |
| 324 | } |
| 325 | a.record = &record |
| 326 | return nil |
| 327 | } |
| 328 | |
| 329 | func (a *localAccount) changePassword(oldPassword, newPassword string) error { |
| 330 | if err := validAccountPassword(newPassword); err != nil { |
| 331 | return err |
| 332 | } |
| 333 | a.mu.Lock() |
| 334 | defer a.mu.Unlock() |
| 335 | if len(a.key) != 32 { |
| 336 | return errors.New("请先解锁 Cage") |
| 337 | } |
| 338 | if time.Now().Before(a.nextAttempt) { |
| 339 | return errors.New("请稍后再试") |
| 340 | } |
| 341 | key, err := openAccountKey(a.record, oldPassword) |
| 342 | if err != nil { |
| 343 | a.nextAttempt = time.Now().Add(time.Second) |
| 344 | return err |
| 345 | } |
| 346 | defer clear(key) |
| 347 | record := *a.record |
| 348 | if record.MacLogin != nil { |
| 349 | login, err := a.openMacAccount() |
| 350 | if err != nil { |
| 351 | return err |
| 352 | } |
| 353 | if err = validMacAccount(record.Username, newPassword); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | for _, guest := range login.Guests { |
| 357 | if guest.Password != login.Password { |
| 358 | return errors.New("客机密码仍待同步,请先启动 macOS 客机并完成同步后再改密") |
| 359 | } |
| 360 | } |
| 361 | login.Password = newPassword |
| 362 | if err = sealMacAccount(&record, key, login); err != nil { |
| 363 | return err |
| 364 | } |
| 365 | } |
| 366 | if err = sealAccountKey(&record, newPassword, key); err != nil { |
| 367 | return err |
| 368 | } |
| 369 | if err = writePrivate(a.path, record); err != nil { |
| 370 | return errors.New("新密码未能保存,原密码仍然有效") |
| 371 | } |
| 372 | a.record = &record |
| 373 | a.nextAttempt = time.Time{} |
| 374 | return nil |
| 375 | } |
| 376 | |
| 377 | func (a *localAccount) desktopKey() ([]byte, error) { |
| 378 | a.mu.Lock() |
| 379 | defer a.mu.Unlock() |
| 380 | if len(a.key) != 32 { |
| 381 | return nil, errors.New("请先登录 Cage,再打开 Claude Desktop") |
| 382 | } |
| 383 | |
| 384 | encoded := make([]byte, base64.RawStdEncoding.EncodedLen(len(a.key))) |
| 385 | base64.RawStdEncoding.Encode(encoded, a.key) |
| 386 | return encoded, nil |
| 387 | } |
| 388 | |
| 389 | func normalizeAccountAvatar(value string) (string, error) { |
| 390 | if value == "" { |
| 391 | return "", nil |
| 392 | } |
| 393 | const maxBytes = 2 << 20 |
| 394 | if len(value) > maxBytes*4/3+100 { |
| 395 | return "", errors.New("头像图片不能超过 2 MB") |
| 396 | } |
| 397 | _, payload, ok := strings.Cut(value, ",") |
| 398 | if !ok || (!strings.HasPrefix(value, "data:image/png;base64,") && !strings.HasPrefix(value, "data:image/jpeg;base64,")) { |
| 399 | return "", errors.New("请选择 PNG 或 JPEG 图片") |
| 400 | } |
| 401 | b, err := base64.StdEncoding.DecodeString(payload) |
| 402 | if err != nil || len(b) > maxBytes { |
| 403 | return "", errors.New("头像图片无效") |
| 404 | } |
| 405 | cfg, _, err := image.DecodeConfig(bytes.NewReader(b)) |
| 406 | if err != nil || cfg.Width < 1 || cfg.Height < 1 || cfg.Width > 4096 || cfg.Height > 4096 || cfg.Width*cfg.Height > 8_000_000 { |
| 407 | return "", errors.New("头像图片尺寸无效或过大") |
| 408 | } |
| 409 | src, _, err := image.Decode(bytes.NewReader(b)) |
| 410 | if err != nil { |
| 411 | return "", errors.New("无法读取头像图片") |
| 412 | } |
| 413 | size := min(cfg.Width, cfg.Height) |
| 414 | x0, y0 := (cfg.Width-size)/2, (cfg.Height-size)/2 |
| 415 | dst := image.NewRGBA(image.Rect(0, 0, 128, 128)) |
| 416 | for y := 0; y < 128; y++ { |
| 417 | for x := 0; x < 128; x++ { |
| 418 | dst.Set(x, y, src.At(x0+x*size/128, y0+y*size/128)) |
| 419 | } |
| 420 | } |
| 421 | var out bytes.Buffer |
| 422 | if err = png.Encode(&out, dst); err != nil { |
| 423 | return "", err |
| 424 | } |
| 425 | return "data:image/png;base64," + base64.StdEncoding.EncodeToString(out.Bytes()), nil |
| 426 | } |