Files
pipelines/internal/claudeaccounts/operations.go
T
alan c490f71042 Claude account switcher: save and switch a chat's Claude login in place
Saved accounts live under <CLAUDE_CONFIG_DIR>/pipelines-accounts/<slug>/
(0700 dir, 0600 files). Switching changes what /login changes: the
claudeAiOauth entry of .credentials.json and oauthAccount of .claude.json
(atomic temp+rename, mode and other keys kept) and the org caches /login
drops, under Claude Code's own refresh, storage and config locks, so
running CLIs continue on the new account without a restart. The active
login's rotated tokens are written back to its slot first.

Server: claude_accounts / claude_account_save / _use / _remove, chat-scoped
and Claude-only; a switch moves the home's open chats to the new account's
quota (usage.account.switched_at), clearing a reached limit.
CLI: pipelines claude-account list|save|use|remove [--dir].
App: Claude account in the chat menu, and Switch to <account> on the
usage-limit and usage-warning banners, with a confirmation snack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:10:08 +00:00

303 lines
8.7 KiB
Go

package claudeaccounts
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// ErrNoLogin is returned when the config directory has no Claude subscription
// login to save.
var ErrNoLogin = errors.New("this Claude home has no subscription login; sign in with /login first")
// List reports the saved accounts and the active login. It also writes the
// active login's current tokens back to its own slot, since Claude Code
// rotates them on refresh.
func (s Store) List() (protocol.ClaudeAccountList, error) {
if err := s.check(); err != nil {
return protocol.ClaudeAccountList{}, err
}
// Listing waits only briefly; the write-back can wait for the next call.
release, err := acquire(s.locks(), time.Second)
if err != nil {
return s.list()
}
defer release()
current, err := s.current()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
if err := s.syncBack(current); err != nil {
return protocol.ClaudeAccountList{}, err
}
return s.list()
}
func (s Store) list() (protocol.ClaudeAccountList, error) {
out := protocol.ClaudeAccountList{ConfigDir: s.ConfigDir, Accounts: []protocol.ClaudeAccount{}}
current, err := s.current()
if err != nil {
return out, err
}
slots, err := s.slots()
if err != nil {
return out, err
}
for _, sl := range slots {
account := sl.login.describe(sl.name, true)
if current.same(sl.login) {
account.Active = true
// The active login's own record is the fresher description.
active := current.describe(sl.name, true)
active.Active = true
out.Active = &active
account = active
}
out.Accounts = append(out.Accounts, account)
}
if out.Active == nil && current != nil {
active := current.describe("", false)
active.Active = true
out.Active = &active
}
return out, nil
}
// syncBack rewrites the slot of the active login with its current tokens
// and account record when they changed.
func (s Store) syncBack(current *login) error {
if current == nil {
return nil
}
slots, err := s.slots()
if err != nil {
return err
}
for _, sl := range slots {
if !current.same(sl.login) {
continue
}
if bytes.Equal(sl.login.oauth, current.oauth) && bytes.Equal(sl.login.account, current.account) {
return nil
}
return s.writeSlot(sl.slug, sl.name, current)
}
return nil
}
// keepCurrent saves an active login that has no slot yet under its email,
// so switching away never discards a login.
func (s Store) keepCurrent(current *login) error {
if current == nil {
return nil
}
slots, err := s.slots()
if err != nil {
return err
}
for _, sl := range slots {
if current.same(sl.login) {
return nil
}
}
slug := slugify(current.email)
if _, err := os.Stat(filepath.Join(s.slotsDir(), slug)); err == nil || slug == "" {
return fmt.Errorf("the current login %s is not saved and its name is taken; save it under another name first", current.email)
}
return s.writeSlot(slug, current.email, current)
}
// find returns the slot named by name: its name, slug or email.
func find(slots []slot, name string) (slot, bool) {
name = strings.TrimSpace(name)
for _, match := range []func(slot) bool{
func(sl slot) bool { return sl.name == name },
func(sl slot) bool { return strings.EqualFold(sl.name, name) },
func(sl slot) bool { return sl.slug == slugify(name) },
func(sl slot) bool { return strings.EqualFold(sl.login.email, name) },
} {
for _, sl := range slots {
if match(sl) {
return sl, true
}
}
}
return slot{}, false
}
// Save snapshots the active login as the saved account name ("" uses its
// email). Saving an account that already has a slot renames that slot.
func (s Store) Save(name string) (protocol.ClaudeAccountList, error) {
if err := s.check(); err != nil {
return protocol.ClaudeAccountList{}, err
}
release, err := acquire(s.locks(), lockWait)
if err != nil {
return protocol.ClaudeAccountList{}, err
}
defer release()
current, err := s.current()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
if current == nil {
return protocol.ClaudeAccountList{}, ErrNoLogin
}
name = strings.TrimSpace(name)
if name == "" {
name = current.email
}
slug := slugify(name)
if slug == "" {
return protocol.ClaudeAccountList{}, fmt.Errorf("%q is not a usable account name", name)
}
slots, err := s.slots()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
for _, sl := range slots {
if sl.slug == slug && !current.same(sl.login) {
return protocol.ClaudeAccountList{}, fmt.Errorf("%q already names %s; remove it first", sl.name, sl.login.email)
}
}
if err := s.writeSlot(slug, name, current); err != nil {
return protocol.ClaudeAccountList{}, err
}
for _, sl := range slots {
if sl.slug != slug && current.same(sl.login) {
if err := os.RemoveAll(filepath.Join(s.slotsDir(), sl.slug)); err != nil {
return protocol.ClaudeAccountList{}, err
}
}
}
return s.list()
}
// Use makes the saved account name the active login. The active login's
// refreshed tokens are first written back to its own slot (a login with no
// slot is saved under its email, so it is never lost); then the target's
// .claude.json oauthAccount and .credentials.json claudeAiOauth replace the
// active ones (each file atomically, every other key kept), after the
// organization caches `/login` also drops. The credentials file is written
// last: its new mtime is what tells running Claude Code processes to reload.
func (s Store) Use(name string) (protocol.ClaudeAccountList, error) {
if err := s.check(); err != nil {
return protocol.ClaudeAccountList{}, err
}
release, err := acquire(s.locks(), lockWait)
if err != nil {
return protocol.ClaudeAccountList{}, err
}
defer release()
slots, err := s.slots()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
target, ok := find(slots, name)
if !ok {
return protocol.ClaudeAccountList{}, fmt.Errorf("no saved Claude account %q", strings.TrimSpace(name))
}
current, err := s.current()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
if err := s.syncBack(current); err != nil {
return protocol.ClaudeAccountList{}, err
}
if current.same(target.login) {
return s.list()
}
if err := s.keepCurrent(current); err != nil {
return protocol.ClaudeAccountList{}, err
}
if err := s.install(target.login); err != nil {
return protocol.ClaudeAccountList{}, err
}
return s.list()
}
func (s Store) install(target *login) error {
configPath := filepath.Join(s.ConfigDir, configFile)
credsPath := filepath.Join(s.ConfigDir, credentialsFile)
configBefore, err := os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
return err
}
config := &orderedObject{values: map[string]jsonRaw{}}
if len(configBefore) > 0 {
if config, err = parseObject(configBefore); err != nil {
return fmt.Errorf("%s is not valid JSON", configFile)
}
}
creds, err := readObject(credsPath)
if err != nil {
return err
}
if creds == nil {
creds = &orderedObject{values: map[string]jsonRaw{}}
}
config.set(accountKey, target.account)
creds.set(oauthKey, target.oauth)
configData, err := config.encode(true)
if err != nil {
return err
}
credsData, err := creds.encode(false)
if err != nil {
return err
}
for _, cache := range orgCaches {
if err := os.Remove(filepath.Join(s.ConfigDir, cache)); err != nil && !os.IsNotExist(err) {
return err
}
}
if err := writeAtomic(configPath, configData, 0o600); err != nil {
return err
}
if err := writeAtomic(credsPath, credsData, 0o600); err != nil {
// Leave the directory consistent: the old account record goes back
// with the old credentials still in place.
if len(configBefore) > 0 {
_ = writeAtomic(configPath, configBefore, 0o600)
}
return err
}
return nil
}
// Remove deletes the saved account name. The active login is not changed.
func (s Store) Remove(name string) (protocol.ClaudeAccountList, error) {
if err := s.check(); err != nil {
return protocol.ClaudeAccountList{}, err
}
slots, err := s.slots()
if err != nil {
return protocol.ClaudeAccountList{}, err
}
target, ok := find(slots, name)
if !ok {
return protocol.ClaudeAccountList{}, fmt.Errorf("no saved Claude account %q", strings.TrimSpace(name))
}
if err := os.RemoveAll(filepath.Join(s.slotsDir(), target.slug)); err != nil {
return protocol.ClaudeAccountList{}, err
}
return s.list()
}
// Identity is the account key the CLI's initialize response would report for
// the active login (email, organization name, plan), or ok false when signed
// out. The chat adapter keys account quota by it.
func (s Store) Identity() (email, organization, plan string, ok bool) {
current, err := s.current()
if err != nil || current == nil {
return "", "", "", false
}
return current.email, current.orgName, current.plan, true
}