diff --git a/internal/provider/claude_dirs.go b/internal/provider/claude_dirs.go index 895c478f5..b316c72d5 100644 --- a/internal/provider/claude_dirs.go +++ b/internal/provider/claude_dirs.go @@ -150,28 +150,60 @@ func takeClaudeDir(l *savedLogin, c claudeCredentials) (bool, error) { // 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. +// tells them to when magpie's token is set beside a claude.ai sign-in. +// magpie keeps the other accounts' sign-ins itself, each its own, 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. Never the one +// Claude Code was signed in to, whose sign-in its /logout revoked +// (claudeLoggedOut, or still Held before rememberLogins next looks: it is +// asked only while Claude Code is signed out); of the others, one with a +// saved sign-in, on before off, then the one seen last; one whose saved +// sign-in is gone only when no other has one; "" when there is none. func claudeStandIn(ls []savedLogin) string { - user, signedIn := "", false + user, best := "", -1 var seen time.Time for _, l := range ls { - if l.Agent != "claude" { + if l.Agent != "claude" || l.Held || l.Lapsed == claudeLogoutLapse { continue } - _, ok := parseClaudeCredentials(l.Auth) - if user == "" || ok && !signedIn || ok == signedIn && l.Seen.After(seen) { - user, seen, signedIn = l.User, l.Seen, ok + rank := 0 + if _, ok := parseClaudeCredentials(l.Auth); ok { + rank = 2 + if l.On { + rank++ + } + } + if rank > best || rank == best && l.Seen.After(seen) { + user, seen, best = l.User, l.Seen, rank } } return user } +// claudeLogoutLapse is why the account Claude Code was signed in to can't +// be used once Claude Code logged out. +const claudeLogoutLapse = "Claude Code's /logout signed it out (it revokes the sign-in it holds); sign in again" + +// claudeLoggedOut marks the account Claude Code held, now that it is +// signed out, as lapsed: /logout revokes the refresh token Claude Code +// holds (POST /revoke, Claude Code 2.1.x's performLogout), and +// magpie's copy of that account is the same sign-in, so it is gone too. +// The accounts magpie keeps in config directories of their own are +// sign-ins of their own and stay. It says whether ls changed. +func claudeLoggedOut(ls []savedLogin) bool { + changed := false + for i := range ls { + if ls[i].Agent != "claude" || !ls[i].Held { + continue + } + ls[i].Held, changed = false, true + if _, ok := parseClaudeCredentials(ls[i].Auth); ok && ls[i].Lapsed == "" { + ls[i].Lapsed = claudeLogoutLapse + } + } + return changed +} + // 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 { diff --git a/internal/provider/claude_logout_test.go b/internal/provider/claude_logout_test.go index ca0c7f5b3..a038369aa 100644 --- a/internal/provider/claude_logout_test.go +++ b/internal/provider/claude_logout_test.go @@ -27,6 +27,7 @@ func TestClaudeAccountsOutliveLogout(t *testing.T) { writeFile(t, loginsPath(), []map[string]any{ {"agent": "claude", "user": "on@example.com", "plan": "max", "on": true, "seen": seen, "auth": oauth("tok-on")}, {"agent": "claude", "user": "off@example.com", "plan": "pro", "seen": seen, "auth": oauth("tok-off")}, + {"agent": "claude", "user": "two@example.com", "plan": "max", "on": true, "seen": seen.Add(-time.Hour), "auth": oauth("tok-two")}, }) loginsMu.Lock() loginsSeenAt = time.Time{} @@ -43,34 +44,43 @@ func TestClaudeAccountsOutliveLogout(t *testing.T) { loginsSeenAt = time.Time{} loginsMu.Unlock() + // the one Claude Code held went with its /logout, which revokes the + // refresh token it holds — magpie's copy of it too (StringKe on + // Discord: all six had to be signed in again). The others are sign-ins + // of their own: one on stands in, never the revoked one. p, ok := find(All(), "claude") - if !ok || p.Account == nil || p.Account.User != "own@example.com" { + if !ok || p.Account == nil || p.Account.User != "on@example.com" { t.Fatalf("logged out: %v %+v", ok, p.Account) } dir, own, err := p.Account.Token(context.Background()) - if err != nil || !own || dir != claudeAccountDir("own@example.com") { + if err != nil || !own || dir != claudeAccountDir("on@example.com") { t.Fatalf("dir %q %v %v", dir, own, err) } - if c, ok := readClaudeDir(dir); !ok || c.OAuth.RefreshToken != "sk-ant-ort01-old" { + if c, ok := readClaudeDir(dir); !ok || c.OAuth.RefreshToken != "r-tok-on" { t.Fatalf("dir credentials %+v", c.OAuth) } + if _, err := os.Stat(claudeAccountDir("own@example.com")); !os.IsNotExist(err) { + t.Fatalf("the revoked sign-in was put to use: %v", err) + } var also []string for _, q := range p.AlsoOn() { also = append(also, q.Account.User) } - if len(also) != 1 || also[0] != "on@example.com" { + if len(also) != 1 || also[0] != "two@example.com" { t.Fatalf("also on: %v", also) } ls := Logins("claude") - if len(ls) != 3 { + if len(ls) != 4 { t.Fatalf("logins: %+v", ls) } for _, l := range ls { - if l.Active || l.On != (l.User != "off@example.com") { + revoked := l.User == "own@example.com" + if l.Active || l.On != (l.User == "on@example.com" || l.User == "two@example.com") || + (l.Lapsed == claudeLogoutLapse) != revoked { t.Fatalf("login %+v", l) } } - if u := InUseLogin("claude"); u != "own@example.com" { + if u := InUseLogin("claude"); u != "on@example.com" { t.Fatalf("in use %q", u) } for _, x := range savedButSignedOut() { @@ -79,16 +89,57 @@ func TestClaudeAccountsOutliveLogout(t *testing.T) { } } - // it can be paused behind the one on, as when Claude Code was signed in to it - if err := SetLoginOn("claude", "own@example.com", false); err != nil { + // the stand-in can be paused behind another on, as Claude Code's own could + if err := SetLoginOn("claude", "on@example.com", false); err != nil { t.Fatal(err) } if p, _ = find(All(), "claude"); !p.OwnPaused() { t.Fatal("not paused") } - if u := InUseLogin("claude"); u != "on@example.com" { + if u := InUseLogin("claude"); u != "two@example.com" { t.Fatalf("in use %q", u) } + + // /login again in Claude Code, to the same account: a sign-in anew, + // no longer lapsed + writeFile(t, cred, oauth("tok-again")) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "own@example.com"}}) + ForgetAccounts() + for _, l := range Logins("claude") { + if l.User == "own@example.com" && (!l.Active || l.Lapsed != "") { + t.Fatalf("signed in again: %+v", l) + } + } +} + +// A switch in magpie takes Claude Code off one account and puts it on +// another, saving the first's sign-in as it was: nothing revoked it, and it +// isn't taken for logged out. +func TestClaudeSwitchIsNoLogout(t *testing.T) { + home := claudeHome(t) + t.Setenv("CLAUDE_CONFIG_DIR", "") + noAnthropic(t) + claudeSignIn(t, home, time.Now().Add(time.Hour)) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "own@example.com"}}) + far := time.Now().Add(24 * time.Hour).UnixMilli() + writeFile(t, loginsPath(), []map[string]any{ + {"agent": "claude", "user": "other@example.com", "plan": "max", "seen": time.Now().Add(-time.Hour).UTC(), + "profile": map[string]any{"emailAddress": "other@example.com"}, + "auth": map[string]any{"claudeAiOauth": map[string]any{"accessToken": "tok-other", "refreshToken": "r-other", "expiresAt": far}}}, + }) + ForgetAccounts() + if u := InUseLogin("claude"); u != "own@example.com" { + t.Fatalf("in use %q", u) + } + if err := SwitchLogin("claude", "other@example.com"); err != nil { + t.Fatal(err) + } + ForgetAccounts() + for _, l := range Logins("claude") { + if l.Lapsed != "" || l.Active != (l.User == "other@example.com") { + t.Fatalf("login %+v", l) + } + } } // Logged out of Claude Code with accounts in magpie, an account signed in diff --git a/internal/provider/logins.go b/internal/provider/logins.go index c087bb440..a64933bde 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -90,6 +90,10 @@ type savedLogin struct { // paused it in magpie (#263): the gateway passes over it while another // of the agent's accounts is on, the agent staying signed in to it. Paused bool `json:"paused,omitempty"` + // Held is the Claude account Claude Code itself was signed in to when + // magpie last looked: its saved copy is that very sign-in, which + // Claude Code's /logout revokes (claudeLoggedOut). + Held bool `json:"held,omitempty"` } var ( @@ -470,9 +474,18 @@ func rememberLogins(force bool) { } l, ok := liveLogin(agent) if !ok { + if agent == "claude" && claudeLoggedOut(ls) { + changed = true + } continue } l.Seen = time.Now().UTC().Truncate(time.Second) + if agent == "claude" { + for i := range ls { + ls[i].Held = false + } + l.Held = true + } ls = upsertLogin(ls, l) changed = true }