| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "maps" |
| 10 | "net/http" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "runtime" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/host" |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | |
| 21 | func trustedViewProof(token string) string { |
| 22 | digest := sha256.Sum256([]byte("trusted desktop view\x00" + token)) |
| 23 | return hex.EncodeToString(digest[:]) |
| 24 | } |
| 25 | func (s *Server) hasTrustedView(r *http.Request) bool { |
| 26 | c, err := r.Cookie(s.cookieName() + "-desktop") |
| 27 | return err == nil && equalSecret(c.Value, trustedViewProof(s.token)) |
| 28 | } |
| 29 | |
| 30 | func validTrustedID(id string) bool { |
| 31 | if id == "" { |
| 32 | return true |
| 33 | } |
| 34 | _, err := hex.DecodeString(id) |
| 35 | return len(id) == 64 && err == nil |
| 36 | } |
| 37 | |
| 38 | type trustedLoginRequest struct { |
| 39 | Action string `json:"action"` |
| 40 | ConnectionID string `json:"connection_id,omitempty"` |
| 41 | Token string `json:"token,omitempty"` |
| 42 | InstanceID string `json:"instance_id,omitempty"` |
| 43 | Password string `json:"password,omitempty"` |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | type trustedLoginReply struct { |
| 49 | Error string `json:"error,omitempty"` |
| 50 | } |
| 51 | |
| 52 | func (d *desktopGateway) trustedLogin(w http.ResponseWriter, r *http.Request) { |
| 53 | if r.Method != http.MethodPost { |
| 54 | http.Error(w, "需要 POST 请求", 405) |
| 55 | return |
| 56 | } |
| 57 | var in trustedLoginRequest |
| 58 | if !readJSON(w, r, &in) { |
| 59 | return |
| 60 | } |
| 61 | d.change.Lock() |
| 62 | defer d.change.Unlock() |
| 63 | session, remote, err := d.acquire(in.ConnectionID) |
| 64 | local, ok := d.local.(*desktopLocal) |
| 65 | if err != nil || remote || !ok { |
| 66 | http.Error(w, "请返回当前本机工作台", 409) |
| 67 | return |
| 68 | } |
| 69 | c, err := openController(local.profile) |
| 70 | if err != nil { |
| 71 | http.Error(w, "本机后台无法连接", 503) |
| 72 | return |
| 73 | } |
| 74 | defer c.close() |
| 75 | if c.origin != session.Origin { |
| 76 | http.Error(w, "本机后台已切换", 409) |
| 77 | return |
| 78 | } |
| 79 | in.Token, in.InstanceID = c.record.Token, session.Manifest.InstanceID |
| 80 | var reply trustedLoginReply |
| 81 | status, err := c.callContext(r.Context(), "POST", "/api/desktop-local/trusted-login", in, &reply) |
| 82 | if err != nil || status != http.StatusOK { |
| 83 | http.Error(w, "本机后台未接受登录请求,请确认已更新 Cage", 409) |
| 84 | return |
| 85 | } |
| 86 | if reply.Error != "" { |
| 87 | http.Error(w, reply.Error, 409) |
| 88 | return |
| 89 | } |
| 90 | jsonReply(w, map[string]bool{"ok": true}) |
| 91 | } |
| 92 | |
| 93 | func (s *Server) localTrustedLogin(w http.ResponseWriter, r *http.Request) { |
| 94 | var in trustedLoginRequest |
| 95 | if !readJSON(w, r, &in) { |
| 96 | return |
| 97 | } |
| 98 | if s.account == nil || !equalSecret(in.Token, s.token) || in.InstanceID != s.instanceID { |
| 99 | http.Error(w, "Launcher refused", http.StatusUnauthorized) |
| 100 | return |
| 101 | } |
| 102 | _, finish, err := s.beginActivity(r.Context()) |
| 103 | if err != nil { |
| 104 | http.Error(w, "后台正在更新", 503) |
| 105 | return |
| 106 | } |
| 107 | defer finish() |
| 108 | if in.Action == "create" { |
| 109 | jsonReply(w, trustedLoginReply{Error: "请先注册 Cage 用户名和密码,再开始安装"}) |
| 110 | return |
| 111 | } |
| 112 | base, err := os.UserConfigDir() |
| 113 | if runtime.GOOS == "windows" { |
| 114 | base = os.Getenv("LOCALAPPDATA") |
| 115 | } |
| 116 | if !filepath.IsAbs(base) { |
| 117 | err = errors.New("无法确定本机系统用户配置目录") |
| 118 | } |
| 119 | if err == nil { |
| 120 | err = s.account.trustedLogin(in.Action, in.Password, filepath.Join(base, "Cage", "trusted-local")) |
| 121 | } |
| 122 | reply := trustedLoginReply{} |
| 123 | if err != nil { |
| 124 | reply.Error = err.Error() |
| 125 | } |
| 126 | jsonReply(w, reply) |
| 127 | } |
| 128 | |
| 129 | func (a *localAccount) trustedLogin(action, password, devices string) error { |
| 130 | a.mu.Lock() |
| 131 | defer a.mu.Unlock() |
| 132 | switch action { |
| 133 | case "create": |
| 134 | if a.record != nil { |
| 135 | return errors.New("已有账户,请使用原登录方式") |
| 136 | } |
| 137 | record := &accountRecord{Version: 1, Username: "本机用户", TrustedDevice: randomToken()} |
| 138 | secret := randomToken() |
| 139 | key := make([]byte, 32) |
| 140 | if _, err := rand.Read(key); err != nil { |
| 141 | return err |
| 142 | } |
| 143 | defer clear(key) |
| 144 | if err := sealAccountKey(record, secret, key); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | path := filepath.Join(devices, record.TrustedDevice+".json") |
| 148 | |
| 149 | |
| 150 | if err := writePrivate(path, secret); err != nil { |
| 151 | return errors.New("无法保存当前系统用户的信任凭据") |
| 152 | } |
| 153 | if err := writePrivate(a.path, record); err != nil { |
| 154 | _ = os.Remove(path) |
| 155 | return errors.New("无法保存本机工作区") |
| 156 | } |
| 157 | a.record = record |
| 158 | a.setKey(append([]byte(nil), key...)) |
| 159 | a.trustedSession = true |
| 160 | case "enable": |
| 161 | if a.record == nil || a.record.TrustedDevice != "" || len(a.key) != 32 { |
| 162 | return errors.New("请先用本机账户登录") |
| 163 | } |
| 164 | if time.Now().Before(a.nextAttempt) { |
| 165 | return errors.New("请稍后再试") |
| 166 | } |
| 167 | key, err := openAccountKey(a.record, password) |
| 168 | if err != nil { |
| 169 | a.nextAttempt = time.Now().Add(time.Second) |
| 170 | return err |
| 171 | } |
| 172 | defer clear(key) |
| 173 | a.nextAttempt = time.Time{} |
| 174 | secret := randomToken() |
| 175 | raw, err := hex.DecodeString(secret) |
| 176 | if err != nil { |
| 177 | return err |
| 178 | } |
| 179 | defer clear(raw) |
| 180 | aead, err := deviceAEAD(raw) |
| 181 | if err != nil { |
| 182 | return err |
| 183 | } |
| 184 | device := accountDevice{ID: randomToken(), Nonce: make([]byte, aead.NonceSize())} |
| 185 | if _, err = rand.Read(device.Nonce); err != nil { |
| 186 | return err |
| 187 | } |
| 188 | device.SealedKey = aead.Seal(nil, device.Nonce, key, []byte("trusted:"+device.ID)) |
| 189 | record := *a.record |
| 190 | record.TrustedUnlock = &device |
| 191 | |
| 192 | |
| 193 | |
| 194 | record.Devices = maps.Clone(record.Devices) |
| 195 | delete(record.Devices, "automatic") |
| 196 | path := filepath.Join(devices, device.ID+".json") |
| 197 | if err = writePrivate(path, secret); err != nil { |
| 198 | return errors.New("无法保存本机信任凭据") |
| 199 | } |
| 200 | if err = writePrivate(a.path, &record); err != nil { |
| 201 | _ = os.Remove(path) |
| 202 | return errors.New("本机信任未能保存") |
| 203 | } |
| 204 | previous := a.record.TrustedUnlock |
| 205 | a.record = &record |
| 206 | if previous != nil { |
| 207 | _ = os.Remove(filepath.Join(devices, previous.ID+".json")) |
| 208 | } |
| 209 | case "disable": |
| 210 | if a.record == nil || len(a.key) != 32 { |
| 211 | return errors.New("请先解锁 Cage") |
| 212 | } |
| 213 | if a.record.TrustedUnlock == nil && a.record.Devices["automatic"].ID == "" { |
| 214 | return nil |
| 215 | } |
| 216 | record := *a.record |
| 217 | record.TrustedUnlock = nil |
| 218 | record.Devices = maps.Clone(record.Devices) |
| 219 | delete(record.Devices, "automatic") |
| 220 | if err := writePrivate(a.path, &record); err != nil { |
| 221 | return errors.New("本机信任未能关闭") |
| 222 | } |
| 223 | a.record = &record |
| 224 | case "resume": |
| 225 | if a.record == nil || (a.record.TrustedDevice == "" && a.record.TrustedUnlock == nil) || a.record.RequireAuthentication { |
| 226 | return errors.New("请使用原有账户验证方式") |
| 227 | } |
| 228 | if len(a.key) == 32 { |
| 229 | return nil |
| 230 | } |
| 231 | id := a.record.TrustedDevice |
| 232 | if a.record.TrustedUnlock != nil { |
| 233 | id = a.record.TrustedUnlock.ID |
| 234 | } |
| 235 | path := filepath.Join(devices, id+".json") |
| 236 | if err := host.CheckPrivateFile(path); err != nil { |
| 237 | return errors.New("找不到当前系统用户的私有信任凭据,请恢复备份") |
| 238 | } |
| 239 | data, err := os.ReadFile(path) |
| 240 | var secret string |
| 241 | if err != nil || len(data) > 128 || json.Unmarshal(data, &secret) != nil || len(secret) != 64 { |
| 242 | return errors.New("本机信任凭据无法读取,请恢复备份") |
| 243 | } |
| 244 | var key []byte |
| 245 | if device := a.record.TrustedUnlock; device != nil { |
| 246 | raw, decodeErr := hex.DecodeString(secret) |
| 247 | if decodeErr != nil { |
| 248 | return errors.New("本机信任凭据无效") |
| 249 | } |
| 250 | defer clear(raw) |
| 251 | aead, cipherErr := deviceAEAD(raw) |
| 252 | if cipherErr != nil { |
| 253 | return cipherErr |
| 254 | } |
| 255 | key, err = aead.Open(nil, device.Nonce, device.SealedKey, []byte("trusted:"+device.ID)) |
| 256 | } else { |
| 257 | key, err = openAccountKey(a.record, secret) |
| 258 | } |
| 259 | if err != nil { |
| 260 | return errors.New("信任凭据与工作区不匹配,请恢复备份") |
| 261 | } |
| 262 | a.setKey(key) |
| 263 | a.trustedSession = true |
| 264 | case "protect": |
| 265 | if a.record == nil || a.record.TrustedDevice == "" || len(a.key) != 32 { |
| 266 | return errors.New("请先在受信任的本机进入工作区") |
| 267 | } |
| 268 | if err := validAccountPassword(password); err != nil { |
| 269 | return err |
| 270 | } |
| 271 | record := *a.record |
| 272 | record.TrustedDevice = "" |
| 273 | if err := sealAccountKey(&record, password, a.key); err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if err := writePrivate(a.path, &record); err != nil { |
| 277 | return errors.New("密码未能保存,仍可使用本机登录") |
| 278 | } |
| 279 | a.record = &record |
| 280 | default: |
| 281 | return errors.New("未知的信任登录操作") |
| 282 | } |
| 283 | return nil |
| 284 | } |