// Package claudeaccounts saves and switches the Claude subscription login of // one Claude Code home (CLAUDE_CONFIG_DIR). // // A login is two things Claude Code's own `/login` writes in that directory: // the claudeAiOauth entry of .credentials.json (tokens, plan, account uuid) // and the oauthAccount object of .claude.json (email, organization). `/login` // also drops the organization's cached policy limits and remote managed // settings, which Claude Code fetches again for the new account. Running // Claude Code processes watch the credentials file's mtime and reload it // before their next request, so changing these files in place switches them // without a restart, exactly as a terminal `/login` does. // // Saved accounts are slots under /pipelines-accounts// (0700), // each holding that account's claudeAiOauth (credentials.json), oauthAccount // (account.json) and its name (slot.json), all 0600. Nothing here returns or // logs a token. package claudeaccounts import ( "encoding/json" "errors" "fmt" "io/fs" "os" "path/filepath" "sort" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // SlotsDir is the directory under the config directory holding saved accounts. const SlotsDir = "pipelines-accounts" const ( credentialsFile = ".credentials.json" configFile = ".claude.json" oauthKey = "claudeAiOauth" accountKey = "oauthAccount" ) // orgCaches are the per-organization caches `/login` deletes so Claude Code // fetches them again for the new account. var orgCaches = []string{ "policy-limits.json", "policy-limits.json.stamp.json", "policy-limits.json.signature.json", "remote-settings.json", "remote-settings.json.synced-at", "remote-settings.json.signature.json", } // Store is the saved accounts of one Claude Code config directory. type Store struct { ConfigDir string } // login is one Claude login: the raw credential and account objects and the // identity read from them. type login struct { oauth json.RawMessage account json.RawMessage uuid string email string orgUUID string orgName string plan string } func (l *login) describe(name string, saved bool) protocol.ClaudeAccount { if name == "" { name = l.email } return protocol.ClaudeAccount{Name: name, Email: l.email, Organization: l.orgName, Plan: l.plan, Saved: saved} } // same reports whether two logins are the same account: by account uuid when // both have one, else by email and organization. Tokens are never compared. func (l *login) same(other *login) bool { if l == nil || other == nil { return false } if l.uuid != "" && other.uuid != "" { return l.uuid == other.uuid && (l.orgUUID == "" || other.orgUUID == "" || l.orgUUID == other.orgUUID) } return l.email != "" && strings.EqualFold(l.email, other.email) && l.orgUUID == other.orgUUID } func decodeLogin(oauth, account json.RawMessage) (*login, error) { var creds struct { RefreshToken string `json:"refreshToken"` SubscriptionType string `json:"subscriptionType"` AccountUUID string `json:"accountUuid"` OrganizationUUID string `json:"organizationUuid"` } if len(oauth) == 0 || string(oauth) == "null" || json.Unmarshal(oauth, &creds) != nil || creds.RefreshToken == "" { return nil, errors.New("no Claude subscription login") } var info struct { AccountUUID string `json:"accountUuid"` EmailAddress string `json:"emailAddress"` OrganizationUUID string `json:"organizationUuid"` OrganizationName string `json:"organizationName"` } if len(account) == 0 || string(account) == "null" || json.Unmarshal(account, &info) != nil || info.EmailAddress == "" { return nil, errors.New("the login names no account") } if creds.AccountUUID != "" && info.AccountUUID != "" && creds.AccountUUID != info.AccountUUID { return nil, errors.New("the login's credentials and account record name different accounts; sign in again with /login") } l := &login{oauth: oauth, account: account, uuid: info.AccountUUID, email: info.EmailAddress, orgUUID: info.OrganizationUUID, orgName: info.OrganizationName, plan: creds.SubscriptionType} if l.uuid == "" { l.uuid = creds.AccountUUID } if l.orgUUID == "" { l.orgUUID = creds.OrganizationUUID } return l, nil } // current reads the active login, or nil when the directory is signed out. func (s Store) current() (*login, error) { creds, err := readObject(filepath.Join(s.ConfigDir, credentialsFile)) if err != nil { return nil, err } config, err := readObject(filepath.Join(s.ConfigDir, configFile)) if err != nil { return nil, err } if creds == nil || config == nil { return nil, nil } l, err := decodeLogin(creds.get(oauthKey), config.get(accountKey)) if err != nil { return nil, nil } return l, nil } // readObject reads a JSON object file, or nil when it does not exist. func readObject(path string) (*orderedObject, error) { data, err := os.ReadFile(path) if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { return nil, err } obj, err := parseObject(data) if err != nil { return nil, fmt.Errorf("%s is not valid JSON", filepath.Base(path)) } return obj, nil } // slot is one saved account. type slot struct { slug string name string login *login } func (s Store) slotsDir() string { return filepath.Join(s.ConfigDir, SlotsDir) } func (s Store) slots() ([]slot, error) { entries, err := os.ReadDir(s.slotsDir()) if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { return nil, err } var out []slot for _, entry := range entries { if !entry.IsDir() || entry.Name() != slugify(entry.Name()) { continue } if sl, err := s.readSlot(entry.Name()); err == nil { out = append(out, sl) } } sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i].name) < strings.ToLower(out[j].name) }) return out, nil } func (s Store) readSlot(slug string) (slot, error) { dir := filepath.Join(s.slotsDir(), slug) creds, err := readObject(filepath.Join(dir, "credentials.json")) if err != nil || creds == nil { return slot{}, errors.New("missing credentials") } account, err := os.ReadFile(filepath.Join(dir, "account.json")) if err != nil { return slot{}, err } l, err := decodeLogin(creds.get(oauthKey), account) if err != nil { return slot{}, err } var meta struct { Name string `json:"name"` } if data, err := os.ReadFile(filepath.Join(dir, "slot.json")); err == nil { _ = json.Unmarshal(data, &meta) } if meta.Name == "" { meta.Name = l.email } return slot{slug: slug, name: meta.Name, login: l}, nil } // writeSlot stores l under slug with 0700/0600 permissions. func (s Store) writeSlot(slug, name string, l *login) error { for _, dir := range []string{s.slotsDir(), filepath.Join(s.slotsDir(), slug)} { if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { return err } if err := os.Chmod(dir, 0o700); err != nil { return err } } dir := filepath.Join(s.slotsDir(), slug) creds := &orderedObject{values: map[string]json.RawMessage{}} creds.set(oauthKey, l.oauth) credsData, err := creds.encode(false) if err != nil { return err } meta, err := marshal(map[string]any{"name": name, "saved_at": time.Now().UnixMilli()}) if err != nil { return err } for file, data := range map[string][]byte{"credentials.json": credsData, "account.json": l.account, "slot.json": meta} { path := filepath.Join(dir, file) if err := writeAtomic(path, data, 0o600); err != nil { return err } if err := os.Chmod(path, 0o600); err != nil { return err } } return nil } // slugify makes a slot directory name: lower case letters, digits and // @ . _ + -, other runs replaced by "-". func slugify(name string) string { var b strings.Builder dash := false for _, r := range strings.ToLower(strings.TrimSpace(name)) { ok := (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || strings.ContainsRune("@._+-", r) if ok { b.WriteRune(r) dash = false } else if !dash { b.WriteByte('-') dash = true } } slug := strings.Trim(b.String(), "-.") if len(slug) > 100 { slug = slug[:100] } return slug } func (s Store) locks() []dirLock { return []dirLock{ {path: filepath.Join(s.ConfigDir, ".oauth_refresh.lock"), stale: time.Minute}, {path: filepath.Join(s.ConfigDir, ".storage-write.lock"), stale: 15 * time.Second}, // Claude Code rewrites .claude.json under this lock (proper-lockfile's // default ten-second staleness), re-reading it first. {path: filepath.Join(s.ConfigDir, configFile+".lock"), stale: 10 * time.Second}, } } func (s Store) check() error { if s.ConfigDir == "" || !filepath.IsAbs(s.ConfigDir) { return errors.New("no Claude config directory") } info, err := os.Stat(s.ConfigDir) if err != nil || !info.IsDir() { return fmt.Errorf("the Claude config directory %s does not exist", s.ConfigDir) } return nil }