| 1 | package client |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "github.com/gofrs/flock" |
| 10 | "github.com/zalando/go-keyring" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | type Keyring struct{ Profile string } |
| 17 | |
| 18 | func (k Keyring) profile() string { |
| 19 | if k.Profile == "" { |
| 20 | return "default" |
| 21 | } |
| 22 | return k.Profile |
| 23 | } |
| 24 | func (k Keyring) Load() (Credentials, error) { |
| 25 | raw, err := keyring.Get("Oficina", k.profile()) |
| 26 | if err != nil { |
| 27 | return Credentials{}, err |
| 28 | } |
| 29 | var c Credentials |
| 30 | err = json.Unmarshal([]byte(raw), &c) |
| 31 | return c, err |
| 32 | } |
| 33 | func (k Keyring) Save(c Credentials) error { |
| 34 | raw, err := json.Marshal(c) |
| 35 | if err != nil { |
| 36 | return err |
| 37 | } |
| 38 | return keyring.Set("Oficina", k.profile(), string(raw)) |
| 39 | } |
| 40 | func (k Keyring) Delete() error { return keyring.Delete("Oficina", k.profile()) } |
| 41 | |
| 42 | // Serialize refresh across CLI processes as well as concurrent MCP calls. |
| 43 | // Reusing a rotated refresh token revokes the entire connection. |
| 44 | func (k Keyring) Lock(ctx context.Context) (func(), error) { |
| 45 | root, err := os.UserCacheDir() |
| 46 | if err != nil { |
| 47 | return nil, err |
| 48 | } |
| 49 | dir := filepath.Join(root, "Oficina", "credential-locks") |
| 50 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | sum := sha256.Sum256([]byte(k.profile())) |
| 54 | lock := flock.New(filepath.Join(dir, hex.EncodeToString(sum[:])+".lock")) |
| 55 | ok, err := lock.TryLockContext(ctx, 25*time.Millisecond) |
| 56 | if err != nil || !ok { |
| 57 | return nil, errors.New("credential lock unavailable") |
| 58 | } |
| 59 | return func() { _ = lock.Unlock() }, nil |
| 60 | } |
| 61 | |