(key []byte, overwrite bool)
| 44 | } |
| 45 | |
| 46 | func StoreMasterKey(key []byte, overwrite bool) error { |
| 47 | exists, err := MasterKeyExists() |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | if exists && !overwrite { |
| 52 | return nil |
| 53 | } |
| 54 | if exists && overwrite { |
| 55 | if err := DeleteMasterKey(); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | } |
| 59 | it := kc.NewItem() |
| 60 | it.SetSecClass(kc.SecClassGenericPassword) |
| 61 | it.SetService(serviceNew) |
| 62 | it.SetAccount(account) |
| 63 | it.SetAccessible(kc.AccessibleWhenUnlocked) |
| 64 | it.SetData(key) |
| 65 | |
| 66 | // Retry logic for Keychain authorization |
| 67 | // First authorization may take time or return temporary error |
| 68 | maxRetries := 3 |
| 69 | for attempt := 1; attempt <= maxRetries; attempt++ { |
| 70 | err = kc.AddItem(it) |
| 71 | if err == nil { |
| 72 | return nil |
| 73 | } |
| 74 | |
| 75 | // Check if it's a user cancellation (-128) |
| 76 | if kcErr, ok := err.(kc.Error); ok { |
| 77 | if kcErr == kc.ErrorUserCanceled { |
| 78 | return fmt.Errorf("用户取消了 Keychain 授权") |
| 79 | } |
| 80 | // If item already exists (despite our check), that's okay |
| 81 | if kcErr == kc.ErrorDuplicateItem { |
| 82 | return nil |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // For other errors, retry after a short delay |
| 87 | if attempt < maxRetries { |
| 88 | // Wait briefly before retry (macOS authorization may need time) |
| 89 | time.Sleep(time.Duration(attempt) * 500 * time.Millisecond) |
| 90 | continue |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | return fmt.Errorf("存储 master key 失败 (尝试 %d 次): %w", maxRetries, err) |
| 95 | } |
| 96 | |
| 97 | func LoadMasterKey() ([]byte, error) { |
| 98 | // Gate access behind biometry prompt |
no test coverage detected