@@ -26,7 +26,12 @@ const (
2626
2727// Config holds the Uncompact configuration.
2828type Config struct {
29- APIKey string `json:"api_key"`
29+ // APIKey is the decrypted API key. It is not stored in plain text.
30+ APIKey string `json:"-"`
31+
32+ // SecureAPIKey is the encrypted API key stored in the config file.
33+ SecureAPIKey string `json:"api_key,omitempty"`
34+
3035 BaseURL string `json:"base_url,omitempty"`
3136 MaxTokens int `json:"max_tokens,omitempty"`
3237 Mode string `json:"mode,omitempty"` // "local" or "api"; empty = auto-detect
@@ -138,9 +143,24 @@ func Load(flagAPIKey string) (*Config, error) {
138143 if err := json .Unmarshal (data , cfg ); err != nil {
139144 return nil , fmt .Errorf ("malformed config file %s: %w" , cfgFile , err )
140145 }
141- if cfg .APIKey != "" {
142- cfg .Source = "config file"
146+
147+ // Decrypt or migrate the API key
148+ if cfg .SecureAPIKey != "" {
149+ if strings .HasPrefix (cfg .SecureAPIKey , "smsk_" ) {
150+ // Migration: existing plain text key found
151+ cfg .APIKey = cfg .SecureAPIKey
152+ cfg .Source = "config file (migrated to secure storage)"
153+ } else {
154+ // Normal case: decrypt the secure key
155+ decrypted , err := decrypt (cfg .SecureAPIKey )
156+ if err != nil {
157+ return nil , fmt .Errorf ("decrypting API key from config: %w" , err )
158+ }
159+ cfg .APIKey = decrypted
160+ cfg .Source = "config file"
161+ }
143162 }
163+
144164 if cfg .Mode != "" {
145165 cfg .Mode = strings .ToLower (strings .TrimSpace (cfg .Mode ))
146166 if err := ValidateMode (cfg .Mode ); err != nil {
@@ -185,6 +205,17 @@ func Load(flagAPIKey string) (*Config, error) {
185205
186206// Save writes the config to disk.
187207func Save (cfg * Config ) error {
208+ // Encrypt the API key before saving
209+ if cfg .APIKey != "" {
210+ encrypted , err := encrypt (cfg .APIKey )
211+ if err != nil {
212+ return fmt .Errorf ("encrypting API key for storage: %w" , err )
213+ }
214+ cfg .SecureAPIKey = encrypted
215+ } else {
216+ cfg .SecureAPIKey = ""
217+ }
218+
188219 dir , err := ConfigDir ()
189220 if err != nil {
190221 return err
0 commit comments