Files
magpie/internal/provider/claude_dirs.go
T
yetone 41d50e15c8 claude: the Claude accounts saved in magpie are served while Claude Code is logged out, and none is dropped (StringKe on Discord: CC(API) -> Magpie -> CC Subscription, and as soon as I /logout in Claude Code all six accounts I manage in magpie disappear) — magpie served its saved Claude accounts only beside the one Claude Code was signed in to: claudeAccount gave no provider without Claude Code's own credentials (or with claude auth status saying no one is signed in), so the gateway had no Claude account at all and the page said the saved ones "are only offered beside the account it is signed in to". Claude Code itself tells the user to log out: with magpie's ANTHROPIC_AUTH_TOKEN beside a claude.ai sign-in it warns "ANTHROPIC_AUTH_TOKEN overriding Claude subscription login · unset it or /logout to sign it out". magpie keeps every account's sign-in in logins.json, so a logout now signs none of them out of magpie: the account seen last (the one Claude Code was signed in to until then, which magpie saw every 30s) stands in its place, run in a config directory of its own as the others on are, listed on, and it can be paused behind another as Claude Code's own could; the others on are served behind it, the Usage page reads it as a saved account, and the saved-but-signed-out notice is no longer given for Claude. An account whose saved sign-in is unreadable is listed as signed out ("its sign-in is gone; sign in again"), never dropped, and isn't picked to stand in while another has one. An account signed in in magpie while Claude Code is logged out and magpie has Claude accounts no longer signs Claude Code back in (which only brought back its warning); it is magpie's alone, on, and the one served first till then stays on behind it. Prompts, identity lines and headers are unchanged; magpie still never refreshes a Claude sign-in nor asks Anthropic anything itself. TestClaudeAccountsOutliveLogout, TestClaudeSignInWhileLoggedOut and TestSavedButSignedOutClaudeServed fail without the change; TestSavedButSignedOutCanBeRemoved now removes the account from the list. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass (TestFetchNewLeavesListedPlugins, a bun plugin test, failed once under load and passes alone and in a rerun of the package).
2026-10-01 20:13:58 +08:00

203 lines
6.7 KiB
Go

package provider
// A saved Claude account in use beside the one Claude Code is signed in to
// runs Claude Code in a config directory of its own (CLAUDE_CONFIG_DIR): its
// sign-in is put there once, from logins.json, and from then on Claude Code
// keeps it, refreshing it as it does its own. magpie never refreshes a
// Claude sign-in nor asks Anthropic anything with one; it only reads back
// what Claude Code left, so logins.json follows.
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/proc"
"golang.org/x/text/unicode/norm"
)
// claudeDirsRoot holds the saved Claude accounts' config directories, and
// the sign-ins being made.
func claudeDirsRoot() string { return filepath.Join(filepath.Dir(Path()), "claude-accounts") }
// claudeAccountDir is the config directory a saved Claude account runs
// Claude Code in.
func claudeAccountDir(user string) string {
sum := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(user))))
return filepath.Join(claudeDirsRoot(), hex.EncodeToString(sum[:])[:16])
}
// claudeDirService is the keychain item Claude Code keeps its sign-in in
// when CLAUDE_CONFIG_DIR is dir: its own name, told apart by the directory.
func claudeDirService(dir string) string {
sum := sha256.Sum256([]byte(norm.NFC.String(dir)))
return "Claude Code-credentials-" + hex.EncodeToString(sum[:])[:8]
}
// readClaudeDir is the sign-in Claude Code keeps in config directory dir,
// where it looks first: the keychain on a Mac, then the file.
func readClaudeDir(dir string) (claudeCredentials, bool) {
if claudeKeychain {
out, err := proc.Command("security", "find-generic-password", "-s", claudeDirService(dir), "-a", claudeKeychainAccount(), "-w").Output()
if err == nil {
b, _ := keychainText(bytes.TrimSpace(out))
if c, ok := parseClaudeCredentials(b); ok {
return c, true
}
}
}
b, err := os.ReadFile(filepath.Join(dir, ".credentials.json"))
if err != nil {
return claudeCredentials{}, false
}
return parseClaudeCredentials(b)
}
// clearClaudeDir takes the sign-in out of config directory dir, so the one
// it was moved to is its only holder.
func clearClaudeDir(dir string) {
if claudeKeychain {
_ = proc.Command("security", "delete-generic-password", "-s", claudeDirService(dir), "-a", claudeKeychainAccount()).Run()
}
_ = os.Remove(filepath.Join(dir, ".credentials.json"))
}
// forgetClaudeDir removes a saved account's config directory altogether.
func forgetClaudeDir(user string) {
dir := claudeAccountDir(user)
clearClaudeDir(dir)
_ = os.RemoveAll(dir)
}
// claudeSavedDir is the config directory to run Claude Code in for the
// saved account user: its sign-in is put there from logins.json when there
// is none yet, and what Claude Code has made of it since is read back.
func claudeSavedDir(user string) (string, error) {
savedTokenMu.Lock()
defer savedTokenMu.Unlock()
loginsMu.Lock()
defer loginsMu.Unlock()
ls := readLogins()
i := -1
for j := range ls {
if ls[j].Agent == "claude" && strings.EqualFold(ls[j].User, user) {
i = j
}
}
if i < 0 {
return "", fmt.Errorf("no saved claude account %q", user)
}
dir := claudeAccountDir(user)
if c, ok := readClaudeDir(dir); ok {
if changed, err := takeClaudeDir(&ls[i], c); err != nil || !changed {
return dir, err
}
return dir, writeLogins(ls)
}
c, ok := parseClaudeCredentials(ls[i].Auth)
if !ok {
return "", errors.New("the saved Claude sign-in of " + user + " is unreadable")
}
b, err := c.marshal()
if err != nil {
return "", err
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
if err := writePrivate(filepath.Join(dir, ".credentials.json"), append(b, '\n')); err != nil {
return "", err
}
// who it is, as Claude Code keeps it beside a sign-in it made
profile := filepath.Join(dir, ".claude.json")
if _, err := os.Stat(profile); os.IsNotExist(err) && len(ls[i].Profile) > 0 {
var acct map[string]any
if json.Unmarshal(ls[i].Profile, &acct) == nil {
pb, _ := json.MarshalIndent(map[string]any{"oauthAccount": acct, "hasCompletedOnboarding": true}, "", " ")
_ = writePrivate(profile, append(pb, '\n'))
}
}
return dir, nil
}
// takeClaudeDir puts the sign-in Claude Code keeps in an account's config
// directory into its saved login, and says whether that changed it.
func takeClaudeDir(l *savedLogin, c claudeCredentials) (bool, error) {
if old, ok := parseClaudeCredentials(l.Auth); ok && old.OAuth.AccessToken == c.OAuth.AccessToken &&
old.OAuth.RefreshToken == c.OAuth.RefreshToken {
return false, nil
}
b, err := c.marshal()
if err != nil {
return false, err
}
l.Auth = b
if c.OAuth.SubscriptionType != "" {
l.Plan = c.OAuth.SubscriptionType
}
l.Renewed = time.Now().UTC().Truncate(time.Second)
l.Lapsed = ""
return true, nil
}
// claudeStandIn is the saved account served in the place of Claude Code's
// own while Claude Code is signed out — the user logged out of it, as it
// tells them to when magpie's token is set beside a claude.ai sign-in. It
// is the account seen last, which is the one Claude Code was signed in to
// until then (rememberLogins sees that one every 30s), passing over one
// whose saved sign-in is gone while another has one; "" when none is
// saved. magpie keeps every account's sign-in itself, so a logout signs
// none of them out of magpie: the stand-in runs Claude Code in a config
// directory of its own, as the others on do.
func claudeStandIn(ls []savedLogin) string {
user, signedIn := "", false
var seen time.Time
for _, l := range ls {
if l.Agent != "claude" {
continue
}
_, ok := parseClaudeCredentials(l.Auth)
if user == "" || ok && !signedIn || ok == signedIn && l.Seen.After(seen) {
user, seen, signedIn = l.User, l.Seen, ok
}
}
return user
}
// claudeSignedOut is why a saved Claude account can't be used: its saved
// sign-in is gone, and it has to be signed in again; "" when it has one.
func claudeSignedOut(l savedLogin) string {
if _, ok := parseClaudeCredentials(l.Auth); ok {
return ""
}
return "its sign-in is gone; sign in again"
}
// claudeStandInAccount is the Claude Code provider while Claude Code is
// signed out, on claudeStandIn's account; false with no account saved.
func claudeStandInAccount() (Provider, bool) {
loginsMu.Lock()
ls := readLogins()
loginsMu.Unlock()
user := claudeStandIn(ls)
if user == "" {
return Provider{}, false
}
acct := &Account{Agent: "claude", User: user, standIn: true}
for _, l := range ls {
if l.Agent == "claude" && strings.EqualFold(l.User, user) {
acct.Plan = l.Plan
}
}
acct.token = func(context.Context) (string, error) { return claudeSavedDir(user) }
return claudeProvider(acct), true
}