| 1 | package remotehost |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/base64" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "net" |
| 11 | "os" |
| 12 | "path" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | ) |
| 20 | |
| 21 | var uuidPattern = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`) |
| 22 | var instancePattern = regexp.MustCompile(`^[a-f0-9]{64}$`) |
| 23 | var hostnamePattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$`) |
| 24 | var storeLocks sync.Map |
| 25 | |
| 26 | type Store struct { |
| 27 | profile string |
| 28 | mu *sync.Mutex |
| 29 | } |
| 30 | type storedHosts struct { |
| 31 | Version int `json:"version"` |
| 32 | Hosts []HostProfile `json:"hosts"` |
| 33 | } |
| 34 | |
| 35 | func NewStore(profileDir string) *Store { |
| 36 | absolute, err := filepath.Abs(profileDir) |
| 37 | if err == nil { |
| 38 | profileDir = absolute |
| 39 | } |
| 40 | lock, _ := storeLocks.LoadOrStore(filepath.Clean(profileDir), &sync.Mutex{}) |
| 41 | return &Store{profile: profileDir, mu: lock.(*sync.Mutex)} |
| 42 | } |
| 43 | |
| 44 | func newID() string { |
| 45 | var raw [16]byte |
| 46 | if _, err := rand.Read(raw[:]); err != nil { |
| 47 | panic(err) |
| 48 | } |
| 49 | raw[6] = (raw[6] & 15) | 64 |
| 50 | raw[8] = (raw[8] & 63) | 128 |
| 51 | s := hex.EncodeToString(raw[:]) |
| 52 | return s[:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20] + "-" + s[20:] |
| 53 | } |
| 54 | |
| 55 | func hasControl(s string) bool { |
| 56 | return strings.ContainsFunc(s, func(r rune) bool { return r < 32 || r == 127 }) |
| 57 | } |
| 58 | |
| 59 | func normalizeProfile(p HostProfile) (HostProfile, error) { |
| 60 | p.Name = strings.TrimSpace(p.Name) |
| 61 | p.Host = strings.TrimSpace(p.Host) |
| 62 | p.User = strings.TrimSpace(p.User) |
| 63 | if p.Port == 0 { |
| 64 | p.Port = 22 |
| 65 | } |
| 66 | if p.Executable == "" { |
| 67 | p.Executable = "cage" |
| 68 | } |
| 69 | if p.ID != "" && !uuidPattern.MatchString(p.ID) { |
| 70 | return p, failure("invalid_profile", "主机标识无效") |
| 71 | } |
| 72 | if p.Name == "" || len(p.Name) > 200 || hasControl(p.Name) { |
| 73 | return p, failure("invalid_profile", "请填写有效的主机名称") |
| 74 | } |
| 75 | if p.Host == "" || len(p.Host) > 253 || (net.ParseIP(p.Host) == nil && !hostnamePattern.MatchString(p.Host)) || strings.Contains(p.Host, "..") { |
| 76 | return p, failure("invalid_profile", "请填写主机名或 IP 地址") |
| 77 | } |
| 78 | if p.Port < 1 || p.Port > 65535 || p.User == "" || len(p.User) > 128 || hasControl(p.User) { |
| 79 | return p, failure("invalid_profile", "SSH 用户名或端口无效") |
| 80 | } |
| 81 | if p.Auth.Kind != "key_file" && p.Auth.Kind != "agent" { |
| 82 | return p, failure("invalid_profile", "请选择 SSH 密钥文件或本机 SSH agent") |
| 83 | } |
| 84 | if p.Auth.Kind == "key_file" && (!filepath.IsAbs(p.Auth.IdentityFile) || hasControl(p.Auth.IdentityFile)) { |
| 85 | return p, failure("invalid_profile", "SSH 密钥文件需要使用本机绝对路径") |
| 86 | } |
| 87 | if p.Auth.Kind == "agent" { |
| 88 | p.Auth.IdentityFile = "" |
| 89 | } |
| 90 | if (p.Executable != "cage" && !path.IsAbs(p.Executable)) || hasControl(p.Executable) || len(p.Executable) > 4096 { |
| 91 | return p, failure("invalid_profile", "云端 Cage 程序需要使用绝对路径或 cage") |
| 92 | } |
| 93 | if (p.ConfigPath != "" && !path.IsAbs(p.ConfigPath)) || hasControl(p.ConfigPath) || len(p.ConfigPath) > 4096 { |
| 94 | return p, failure("invalid_profile", "云端配置文件需要使用绝对路径") |
| 95 | } |
| 96 | if p.HostKey != nil { |
| 97 | key := *p.HostKey |
| 98 | raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key.Fingerprint, "SHA256:")) |
| 99 | if key.Algorithm == "" || len(key.Algorithm) > 128 || hasControl(key.Algorithm) || !strings.HasPrefix(key.Fingerprint, "SHA256:") || err != nil || len(raw) != 32 { |
| 100 | return p, failure("invalid_profile", "SSH 主机密钥指纹无效") |
| 101 | } |
| 102 | p.HostKey = &key |
| 103 | } |
| 104 | return p, nil |
| 105 | } |
| 106 | |
| 107 | func (s *Store) read() ([]HostProfile, error) { |
| 108 | filename := filepath.Join(s.profile, "remote-hosts.json") |
| 109 | if err := host.CheckPrivateFile(filename); err != nil { |
| 110 | if os.IsNotExist(err) { |
| 111 | return []HostProfile{}, nil |
| 112 | } |
| 113 | return nil, failure("profile_permissions", "远程主机配置权限不安全") |
| 114 | } |
| 115 | f, err := os.Open(filename) |
| 116 | if err != nil { |
| 117 | return nil, failure("profile_read", "无法读取远程主机配置") |
| 118 | } |
| 119 | defer f.Close() |
| 120 | info, err := f.Stat() |
| 121 | if err != nil || info.Size() > 1<<20 { |
| 122 | return nil, failure("profile_invalid", "远程主机配置过大或无法读取") |
| 123 | } |
| 124 | var data storedHosts |
| 125 | decoder := json.NewDecoder(io.LimitReader(f, 1<<20)) |
| 126 | decoder.DisallowUnknownFields() |
| 127 | if decoder.Decode(&data) != nil || data.Version != 1 || len(data.Hosts) > 100 { |
| 128 | return nil, failure("profile_invalid", "远程主机配置损坏,现有文件未修改") |
| 129 | } |
| 130 | var extra any |
| 131 | if decoder.Decode(&extra) != io.EOF { |
| 132 | return nil, failure("profile_invalid", "远程主机配置内容无效") |
| 133 | } |
| 134 | seen := map[string]bool{} |
| 135 | for i, p := range data.Hosts { |
| 136 | normalized, err := normalizeProfile(p) |
| 137 | if err != nil || p.ID == "" || seen[p.ID] { |
| 138 | return nil, failure("profile_invalid", "远程主机配置内容无效") |
| 139 | } |
| 140 | data.Hosts[i] = normalized |
| 141 | seen[p.ID] = true |
| 142 | } |
| 143 | if data.Hosts == nil { |
| 144 | data.Hosts = []HostProfile{} |
| 145 | } |
| 146 | return data.Hosts, nil |
| 147 | } |
| 148 | |
| 149 | func (s *Store) write(profiles []HostProfile) error { |
| 150 | if err := host.EnsurePrivateDir(s.profile); err != nil { |
| 151 | return failure("profile_permissions", "无法创建私有远程主机配置目录") |
| 152 | } |
| 153 | file, err := os.CreateTemp(s.profile, ".remote-hosts-*") |
| 154 | if err != nil { |
| 155 | return failure("profile_write", "无法保存远程主机配置") |
| 156 | } |
| 157 | tmp := file.Name() |
| 158 | defer os.Remove(tmp) |
| 159 | if err = host.ProtectFile(tmp); err == nil { |
| 160 | err = json.NewEncoder(file).Encode(storedHosts{1, profiles}) |
| 161 | } |
| 162 | if err == nil { |
| 163 | err = file.Sync() |
| 164 | } |
| 165 | err = errors.Join(err, file.Close()) |
| 166 | if err == nil { |
| 167 | err = os.Rename(tmp, filepath.Join(s.profile, "remote-hosts.json")) |
| 168 | } |
| 169 | if err != nil { |
| 170 | return failure("profile_write", "远程主机配置未能保存,现有文件保持不变") |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 | |
| 175 | func (s *Store) List() ([]HostProfile, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.read() } |
| 176 | func (s *Store) Get(id string) (HostProfile, error) { |
| 177 | profiles, err := s.List() |
| 178 | if err != nil { |
| 179 | return HostProfile{}, err |
| 180 | } |
| 181 | for _, p := range profiles { |
| 182 | if p.ID == id { |
| 183 | return p, nil |
| 184 | } |
| 185 | } |
| 186 | return HostProfile{}, failure("host_not_found", "远程主机配置已不存在") |
| 187 | } |
| 188 | func (s *Store) Upsert(profile HostProfile) (HostProfile, error) { |
| 189 | profile, err := normalizeProfile(profile) |
| 190 | if err != nil { |
| 191 | return profile, err |
| 192 | } |
| 193 | s.mu.Lock() |
| 194 | defer s.mu.Unlock() |
| 195 | profiles, err := s.read() |
| 196 | if err != nil { |
| 197 | return profile, err |
| 198 | } |
| 199 | if profile.ID == "" { |
| 200 | if len(profiles) >= 100 { |
| 201 | return profile, failure("profile_limit", "最多保存 100 台远程主机") |
| 202 | } |
| 203 | profile.ID = newID() |
| 204 | profiles = append(profiles, profile) |
| 205 | } else { |
| 206 | found := false |
| 207 | for i, p := range profiles { |
| 208 | if p.ID == profile.ID { |
| 209 | profiles[i] = profile |
| 210 | found = true |
| 211 | break |
| 212 | } |
| 213 | } |
| 214 | if !found { |
| 215 | return profile, failure("host_not_found", "远程主机配置已不存在") |
| 216 | } |
| 217 | } |
| 218 | return profile, s.write(profiles) |
| 219 | } |
| 220 | func (s *Store) Delete(id string) error { |
| 221 | s.mu.Lock() |
| 222 | defer s.mu.Unlock() |
| 223 | profiles, err := s.read() |
| 224 | if err != nil { |
| 225 | return err |
| 226 | } |
| 227 | for i, p := range profiles { |
| 228 | if p.ID == id { |
| 229 | return s.write(append(profiles[:i], profiles[i+1:]...)) |
| 230 | } |
| 231 | } |
| 232 | return failure("host_not_found", "远程主机配置已不存在") |
| 233 | } |