| 1 | |
| 2 | package workbench |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/exitpolicy" |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 20 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 21 | "github.com/sylvinus/agent-vm/internal/paths" |
| 22 | ) |
| 23 | |
| 24 | type Preferences struct { |
| 25 | BalancedDisplay bool `json:"balanced_display"` |
| 26 | MobileRelay string `json:"mobile_relay,omitempty"` |
| 27 | Workspace string `json:"workspace"` |
| 28 | BrowserHomeURL string `json:"browser_home_url"` |
| 29 | ClaudeTerminalCommand string `json:"claude_terminal_command"` |
| 30 | Keyboard string `json:"keyboard"` |
| 31 | AutoTimezone bool `json:"auto_timezone"` |
| 32 | AutoLanguage bool `json:"auto_language"` |
| 33 | } |
| 34 | |
| 35 | const defaultBrowserHomeURL = "https://www.bing.com/" |
| 36 | |
| 37 | func claudeTerminalCommand(p Preferences) string { |
| 38 | if strings.TrimSpace(p.ClaudeTerminalCommand) == "" { |
| 39 | return "claude" |
| 40 | } |
| 41 | return strings.TrimSpace(p.ClaudeTerminalCommand) |
| 42 | } |
| 43 | |
| 44 | func browserHomeURL(p Preferences) string { |
| 45 | if p.BrowserHomeURL == "" { |
| 46 | return defaultBrowserHomeURL |
| 47 | } |
| 48 | return p.BrowserHomeURL |
| 49 | } |
| 50 | |
| 51 | |
| 52 | func environmentWorkspace(profile string) string { return cage.EnvironmentDir(profile) } |
| 53 | |
| 54 | func guestPath(path string) string { return paths.Guest(paths.Host(path)) } |
| 55 | |
| 56 | func (s *Server) prepareEnvironment() error { |
| 57 | record, err := cage.LoadEnvironmentRecord(s.profile) |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | s.mu.Lock() |
| 62 | p := s.preferences |
| 63 | s.mu.Unlock() |
| 64 | path := environmentWorkspace(s.profile) |
| 65 | |
| 66 | if _, err := os.Stat(filepath.Join(s.profile, "environment.json")); os.IsNotExist(err) { |
| 67 | previous := s.workspace() |
| 68 | if previous != "" { |
| 69 | if _, err := os.Stat(filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, previous), "lima.yaml")); err == nil { |
| 70 | path = previous |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | if err := os.MkdirAll(path, 0700); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | previous := path |
| 78 | path, err = validateWorkspace(path, s.profile) |
| 79 | if err != nil { |
| 80 | |
| 81 | |
| 82 | |
| 83 | path, err = validateWorkspace(p.Workspace, s.profile) |
| 84 | if p.Workspace == "" || err != nil { |
| 85 | path = cage.DefaultEnvironmentDir(s.profile) |
| 86 | if err = os.MkdirAll(path, 0700); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | path, err = validateWorkspace(path, s.profile) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | } |
| 94 | if record.IdentityDirectory == "" { |
| 95 | record.IdentityDirectory = previous |
| 96 | } |
| 97 | } |
| 98 | record.Directory = path |
| 99 | if err = writePrivate(filepath.Join(s.profile, "environment.json"), record); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if p.Workspace == "" || paths.Equal(paths.Host(p.Workspace), paths.Host(previous)) || |
| 103 | record.IdentityDirectory != "" && paths.Equal(paths.Host(p.Workspace), paths.Host(record.IdentityDirectory)) { |
| 104 | p.Workspace = path |
| 105 | } |
| 106 | if err := writePrivate(filepath.Join(s.profile, "workbench.json"), p); err != nil { |
| 107 | return err |
| 108 | } |
| 109 | s.mu.Lock() |
| 110 | s.preferences = p |
| 111 | s.mu.Unlock() |
| 112 | return nil |
| 113 | } |
| 114 | |
| 115 | type Settings struct { |
| 116 | Preferences |
| 117 | DNSURL string `json:"dns_url"` |
| 118 | Timezone string `json:"timezone"` |
| 119 | Locale string `json:"locale"` |
| 120 | BrowserLanguage string `json:"browser_language"` |
| 121 | ExitPolicy cage.ExitPolicy `json:"exit_policy"` |
| 122 | } |
| 123 | type Location struct { |
| 124 | IP string `json:"ip"` |
| 125 | Country string `json:"country"` |
| 126 | CountryCode string `json:"country_code"` |
| 127 | Region string `json:"region"` |
| 128 | RegionCode string `json:"region_code,omitempty"` |
| 129 | SuggestedLocale string `json:"suggested_locale,omitempty"` |
| 130 | SuggestedBrowserLanguage string `json:"suggested_browser_language,omitempty"` |
| 131 | City string `json:"city"` |
| 132 | Timezone string `json:"timezone"` |
| 133 | CheckedAt time.Time `json:"checked_at"` |
| 134 | } |
| 135 | type savedProfile struct { |
| 136 | Config cage.Config `json:"config"` |
| 137 | Preferences Preferences `json:"preferences"` |
| 138 | } |
| 139 | |
| 140 | func writePrivate(path string, v any) error { |
| 141 | b, err := json.MarshalIndent(v, "", " ") |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | if err = host.EnsurePrivateDir(filepath.Dir(path)); err != nil { |
| 146 | return err |
| 147 | } |
| 148 | f, err := os.CreateTemp(filepath.Dir(path), ".cage-write-*") |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | defer os.Remove(f.Name()) |
| 153 | if err = host.ProtectFile(f.Name()); err == nil { |
| 154 | _, err = f.Write(append(b, '\n')) |
| 155 | } |
| 156 | if err == nil { |
| 157 | err = f.Sync() |
| 158 | } |
| 159 | closeErr := f.Close() |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | if closeErr != nil { |
| 164 | return closeErr |
| 165 | } |
| 166 | return os.Rename(f.Name(), path) |
| 167 | } |
| 168 | func settingsView(c cage.Config, p Preferences) Settings { |
| 169 | if p.MobileRelay == mobilelink.OfficialRelay { |
| 170 | p.MobileRelay = "" |
| 171 | } |
| 172 | p.BrowserHomeURL = browserHomeURL(p) |
| 173 | p.ClaudeTerminalCommand = claudeTerminalCommand(p) |
| 174 | return Settings{Preferences: p, DNSURL: c.DNSURL, Timezone: c.Timezone, Locale: c.Locale, BrowserLanguage: c.BrowserLanguage, ExitPolicy: c.ExitPolicy.Normalized()} |
| 175 | } |
| 176 | func proposedSettings(input Settings, old cage.Config, profile string) (cage.Config, Preferences, error) { |
| 177 | if input.ExitPolicy == (cage.ExitPolicy{}) { |
| 178 | input.ExitPolicy = old.ExitPolicy |
| 179 | } |
| 180 | c := cage.Config{ProxyURL: old.ProxyURL, ProxyRevision: old.ProxyRevision, DNSURL: input.DNSURL, Timezone: input.Timezone, Locale: input.Locale, BrowserLanguage: input.BrowserLanguage, ExitPolicy: input.ExitPolicy.Normalized()} |
| 181 | if err := c.Validate(); err != nil { |
| 182 | return c, input.Preferences, err |
| 183 | } |
| 184 | if input.Keyboard != "mac" && input.Keyboard != "native" { |
| 185 | return c, input.Preferences, errors.New("请选择 Mac 或原生 Linux 按键习惯") |
| 186 | } |
| 187 | p := input.Preferences |
| 188 | p.MobileRelay = strings.TrimSuffix(strings.TrimSpace(p.MobileRelay), "/") |
| 189 | if p.MobileRelay != "" && (!strings.HasPrefix(p.MobileRelay, "https://") || !mobilelink.ValidRelayOrigin(p.MobileRelay)) { |
| 190 | return c, p, errors.New("中继地址须为 HTTPS 地址,只包含主机和可选端口") |
| 191 | } |
| 192 | if len(p.ClaudeTerminalCommand) > 4096 || strings.ContainsAny(p.ClaudeTerminalCommand, "\x00\r\n") { |
| 193 | return c, p, errors.New("Claude 终端命令必须为一行,且不超过 4096 字节") |
| 194 | } |
| 195 | p.ClaudeTerminalCommand = claudeTerminalCommand(p) |
| 196 | p.BrowserHomeURL = strings.TrimSpace(browserHomeURL(p)) |
| 197 | home, e := url.Parse(p.BrowserHomeURL) |
| 198 | if e != nil || home == nil || (home.Scheme != "https" && home.Scheme != "http") || home.Hostname() == "" || home.User != nil { |
| 199 | return c, p, errors.New("浏览器默认网站必须是完整的 HTTP 或 HTTPS 网址,且不能包含用户名或密码") |
| 200 | } |
| 201 | if p.Workspace != "" { |
| 202 | workspace, err := validateWorkspace(p.Workspace, profile) |
| 203 | if err != nil { |
| 204 | return c, p, err |
| 205 | } |
| 206 | p.Workspace = workspace |
| 207 | } |
| 208 | return c, p, nil |
| 209 | } |
| 210 | func validateWorkspace(path, profile string) (string, error) { |
| 211 | home, _ := os.UserHomeDir() |
| 212 | if strings.HasPrefix(path, "~/") { |
| 213 | path = filepath.Join(home, path[2:]) |
| 214 | } |
| 215 | abs, err := filepath.Abs(path) |
| 216 | if err != nil { |
| 217 | return "", errors.New("项目路径无效") |
| 218 | } |
| 219 | abs, err = paths.Resolve(abs) |
| 220 | if err != nil { |
| 221 | return "", errors.New("项目目录不存在或无法访问") |
| 222 | } |
| 223 | st, err := os.Stat(abs) |
| 224 | if err != nil || !st.IsDir() { |
| 225 | return "", errors.New("请选择一个项目文件夹") |
| 226 | } |
| 227 | if realHome, err := paths.Resolve(home); err == nil { |
| 228 | home = realHome |
| 229 | } |
| 230 | if executable, e := os.Executable(); e == nil { |
| 231 | if real, e := paths.Resolve(executable); e == nil && cage.StorageContains(abs, real) { |
| 232 | return "", errors.New("不能共享正在运行的工作台程序所在目录。请将安装版 Cage 放在项目外,并重启控制服务后选择此项目。") |
| 233 | } |
| 234 | } |
| 235 | if mounts.UnderName(filepath.ToSlash(abs), nil) { |
| 236 | return "", errors.New("请选择项目根目录,不要共享 Git 等版本控制元数据目录") |
| 237 | } |
| 238 | if paths.Equal(abs, home) || filepath.Dir(abs) == abs { |
| 239 | return "", errors.New("请选择具体项目,不要共享主目录、Cage 配置或包含配置的上级目录") |
| 240 | } |
| 241 | private, err := privateProjectDirectories(profile) |
| 242 | if err != nil { |
| 243 | return "", err |
| 244 | } |
| 245 | for _, dir := range private { |
| 246 | if cage.StoragePathsOverlap(abs, dir) { |
| 247 | return "", errors.New("Cage 配置、环境存储、迁移备份及其上级目录不能共享给虚拟机") |
| 248 | } |
| 249 | } |
| 250 | if err := validateHostProjectData(abs, profile); err != nil { |
| 251 | return "", err |
| 252 | } |
| 253 | return abs, nil |
| 254 | } |
| 255 | |
| 256 | |
| 257 | |
| 258 | func probeLocation(ctx context.Context, c cage.Config) (Location, error) { |
| 259 | ip, err := cage.ProbeExitIP(ctx, c) |
| 260 | if err != nil { |
| 261 | return Location{}, err |
| 262 | } |
| 263 | if state, message := exitpolicy.CheckExitCountry(ip, nil); state == cage.CheckFailed { |
| 264 | return Location{IP: ip, CheckedAt: time.Now()}, errors.New(message) |
| 265 | } |
| 266 | loc, err := probeLocationForIP(ctx, c, ip) |
| 267 | if err != nil { |
| 268 | return Location{IP: ip, CheckedAt: time.Now()}, err |
| 269 | } |
| 270 | observed := loc.exitLocation() |
| 271 | if state, message := exitpolicy.CheckExitCountry(ip, &observed); state != cage.CheckPassed { |
| 272 | return loc, errors.New(message) |
| 273 | } |
| 274 | return loc, nil |
| 275 | } |
| 276 | |
| 277 | |
| 278 | |
| 279 | func probeEnvironmentLocation(ctx context.Context, c cage.Config, _ Preferences) (Location, error) { |
| 280 | return probeLocation(ctx, c) |
| 281 | } |
| 282 | |
| 283 | func (l Location) exitLocation() cage.ExitLocation { |
| 284 | return cage.ExitLocation{IP: l.IP, CountryCode: l.CountryCode, Region: l.Region, City: l.City} |
| 285 | } |
| 286 | |
| 287 | func probeLocationForIP(ctx context.Context, c cage.Config, ip string) (Location, error) { |
| 288 | address := net.ParseIP(ip) |
| 289 | if address == nil { |
| 290 | return Location{}, errors.New("出口地址无效") |
| 291 | } |
| 292 | e, err := cage.NewEgress(c) |
| 293 | if err != nil { |
| 294 | return Location{}, err |
| 295 | } |
| 296 | transport := &http.Transport{Proxy: nil, DialContext: e.DialContext, ForceAttemptHTTP2: true} |
| 297 | defer transport.CloseIdleConnections() |
| 298 | client := &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} |
| 299 | return lookupLocation(ctx, client, address) |
| 300 | } |