Merge branch 'main' into worktree-agent-a3ec65b20dc3028b9
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// Account switching (see internal/claudeaccounts) acts on the Claude Code home
|
||||
// a chat's directory selects: the CLAUDE_CONFIG_DIR its processes run with.
|
||||
|
||||
// ErrNoConfigDir is returned for a chat whose directory selects no Claude
|
||||
// home of its own.
|
||||
var ErrNoConfigDir = errors.New("this chat's directory does not set CLAUDE_CONFIG_DIR, so it has no Claude home of its own to switch")
|
||||
|
||||
// AccountConfigDir is the CLAUDE_CONFIG_DIR a process started in directory
|
||||
// runs with: the directory's own environment (direnv, mise) over base.
|
||||
func AccountConfigDir(ctx context.Context, resolver *workenv.Resolver, directory string, base []string) (string, error) {
|
||||
env := base
|
||||
if resolver != nil && strings.TrimSpace(directory) != "" {
|
||||
env = resolver.Resolve(ctx, directory, base).Apply(base)
|
||||
}
|
||||
dir, ok := envValue(env, "CLAUDE_CONFIG_DIR")
|
||||
dir = strings.TrimSpace(dir)
|
||||
if !ok || dir == "" || !filepath.IsAbs(dir) {
|
||||
return "", ErrNoConfigDir
|
||||
}
|
||||
return filepath.Clean(dir), nil
|
||||
}
|
||||
|
||||
func (c *Chat) accountConfigDir(ctx context.Context, directory string) (string, error) {
|
||||
return AccountConfigDir(ctx, c.dirEnv, directory, os.Environ())
|
||||
}
|
||||
|
||||
// accountKeyFor is the quota key decodeAccountIdentity derives from an
|
||||
// initialize response for a subscription login.
|
||||
func accountKeyFor(email, organization string) string {
|
||||
return strings.TrimSpace(email) + "\x00" + strings.TrimSpace(organization) + "\x00" + "firstParty"
|
||||
}
|
||||
|
||||
// ClaudeAccounts runs one claude_account* operation for the chat sessionID in
|
||||
// directory ("" uses the open session's directory). After a switch every
|
||||
// open chat on the same Claude home is moved to the new account's quota and
|
||||
// told so, which clears a usage limit the old account had reached.
|
||||
func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
if s := c.session(sessionID); s != nil {
|
||||
s.mu.Lock()
|
||||
directory = s.directory
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
configDir, err := c.accountConfigDir(ctx, directory)
|
||||
if err != nil {
|
||||
return protocol.ClaudeAccountList{}, err
|
||||
}
|
||||
store := claudeaccounts.Store{ConfigDir: configDir}
|
||||
switch operation {
|
||||
case protocol.ClaudeAccounts:
|
||||
return store.List()
|
||||
case protocol.ClaudeAccountSave:
|
||||
return store.Save(name)
|
||||
case protocol.ClaudeAccountRemove:
|
||||
return store.Remove(name)
|
||||
case protocol.ClaudeAccountUse:
|
||||
list, err := store.Use(name)
|
||||
if err != nil {
|
||||
return list, err
|
||||
}
|
||||
email, org, plan, ok := store.Identity()
|
||||
if ok {
|
||||
list.Usage = c.switchAccount(ctx, configDir, accountKeyFor(email, org), plan)
|
||||
log.Printf("claude account: %s switched to a saved account", configDir)
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
|
||||
}
|
||||
|
||||
// switchAccount records that configDir now signs in as key: its quota report
|
||||
// is marked switched (an empty one when nothing is known yet), and every open
|
||||
// session on that Claude home takes the new key and republishes its usage.
|
||||
func (c *Chat) switchAccount(ctx context.Context, configDir, key, plan string) *protocol.ChatAccountUsage {
|
||||
now := time.Now().UnixMilli()
|
||||
c.quotaMu.Lock()
|
||||
usage := c.quotas[key].Clone()
|
||||
if usage == nil {
|
||||
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: plan, AsOf: now}
|
||||
}
|
||||
usage.SwitchedAt = now
|
||||
if c.quotas == nil {
|
||||
c.quotas = map[string]*protocol.ChatAccountUsage{}
|
||||
}
|
||||
c.quotas[key] = usage
|
||||
c.quotaMu.Unlock()
|
||||
|
||||
c.mu.Lock()
|
||||
sessions := make([]*session, 0, len(c.sessions))
|
||||
for _, s := range c.sessions {
|
||||
sessions = append(sessions, s)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.mu.Lock()
|
||||
directory := s.directory
|
||||
s.mu.Unlock()
|
||||
if dir, err := c.accountConfigDir(ctx, directory); err != nil || dir != configDir {
|
||||
continue
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.account = accountIdentity{key: key, plan: plan}
|
||||
s.mu.Unlock()
|
||||
s.republishUsage()
|
||||
}
|
||||
return usage.Clone()
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func writeLogin(t *testing.T, profile, email, uuid, token string) {
|
||||
t.Helper()
|
||||
writeFile(t, filepath.Join(profile, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"access-`+token+`","refreshToken":"refresh-`+token+`","expiresAt":1,"subscriptionType":"pro","accountUuid":"`+uuid+`"}}`)
|
||||
writeFile(t, filepath.Join(profile, ".claude.json"), "{\n \"numStartups\": 3,\n \"oauthAccount\": {\"accountUuid\":\""+uuid+"\",\"emailAddress\":\""+email+"\",\"organizationName\":\"Org\"}\n}")
|
||||
}
|
||||
|
||||
func TestUseAccountMovesTheHomesChatsToTheNewAccountQuota(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
var logs bytes.Buffer
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(os.Stderr)
|
||||
profile := t.TempDir()
|
||||
directory := t.TempDir()
|
||||
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
|
||||
ctx := context.Background()
|
||||
|
||||
writeLogin(t, profile, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeLogin(t, profile, "b@example.invalid", "uuid-b", "b1")
|
||||
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountSave, "B"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Two chats on the home are on b, which is out of quota; a third chat
|
||||
// elsewhere is on another account.
|
||||
oldKey := accountKeyFor("b@example.invalid", "Org")
|
||||
limited := &protocol.ChatAccountUsage{Harness: quotaHarness, Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: 100, ResetsAt: 1}}}
|
||||
chat.quotas = map[string]*protocol.ChatAccountUsage{oldKey: limited}
|
||||
here := chat.sessionFor("11111111-1111-4111-8111-111111111111", directory)
|
||||
alsoHere := chat.sessionFor("22222222-2222-4222-8222-222222222222", directory)
|
||||
elsewhere := chat.sessionFor("33333333-3333-4333-8333-333333333333", t.TempDir())
|
||||
for _, s := range []*session{here, alsoHere} {
|
||||
s.account = accountIdentity{key: oldKey, plan: "pro"}
|
||||
}
|
||||
elsewhere.account = accountIdentity{key: "other"}
|
||||
frames := subscribe(t, chat, here.id)
|
||||
|
||||
list, err := chat.ClaudeAccounts(ctx, here.id, "", protocol.ClaudeAccountUse, "a@example.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Active == nil || list.Active.Email != "a@example.invalid" || list.Usage == nil || list.Usage.SwitchedAt == 0 || len(list.Usage.Windows) != 0 {
|
||||
t.Fatalf("use reply = %+v usage=%+v", list, list.Usage)
|
||||
}
|
||||
newKey := accountKeyFor("a@example.invalid", "Org")
|
||||
if here.account.key != newKey || alsoHere.account.key != newKey || elsewhere.account.key != "other" {
|
||||
t.Fatalf("keys = %q %q %q", here.account.key, alsoHere.account.key, elsewhere.account.key)
|
||||
}
|
||||
pushed := waitFrame(t, frames, "switched usage", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil && frame.Usage.Account.SwitchedAt != 0
|
||||
}).Usage.Account
|
||||
if len(pushed.Windows) != 0 {
|
||||
t.Fatalf("the new account inherited the old quota: %+v", pushed)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json"))
|
||||
if !strings.Contains(string(data), "refresh-a1") {
|
||||
t.Fatal("credentials not switched")
|
||||
}
|
||||
for _, secret := range []string{"access-", "refresh-"} {
|
||||
if strings.Contains(logs.String(), secret) {
|
||||
t.Fatalf("log carries a token: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// A later quota report on the new account keeps the switch.
|
||||
known := mergeRateLimit(chat.quotas[newKey], []byte(`{"rateLimitType":"five_hour","utilization":0.2,"resetsAt":1900000000}`), "pro", time.Now())
|
||||
if known == nil || known.SwitchedAt != pushed.SwitchedAt {
|
||||
t.Fatalf("merge dropped the switch: %+v", known)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountsRefusedWithoutAClaudeHome(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
os.Unsetenv("CLAUDE_CONFIG_DIR")
|
||||
if _, err := chat.ClaudeAccounts(context.Background(), "s", t.TempDir(), protocol.ClaudeAccounts, ""); err != ErrNoConfigDir {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -123,8 +123,13 @@ func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, pl
|
||||
return nil
|
||||
}
|
||||
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
|
||||
if next.Plan == "" && previous != nil {
|
||||
next.Plan = previous.Plan
|
||||
if previous != nil {
|
||||
if next.Plan == "" {
|
||||
next.Plan = previous.Plan
|
||||
}
|
||||
// A switch stays recorded: the refusal it cleared is still in the
|
||||
// transcript.
|
||||
next.SwitchedAt = previous.SwitchedAt
|
||||
}
|
||||
for _, entry := range quotaWindowOrder {
|
||||
if w, ok := windows[entry.id]; ok {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package claudeaccounts
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// writeAtomic replaces path with data through a temporary file in the same
|
||||
// directory and a rename, so a reader (a running Claude Code) sees either the
|
||||
// old file or the new one, never a partial write. The file keeps the mode of
|
||||
// the file it replaces (mode when there is none). Claude Code opens its
|
||||
// credentials with O_NOFOLLOW, so a symlinked file is refused rather than
|
||||
// replaced by a regular file behind the operator's back.
|
||||
func writeAtomic(path string, data []byte, mode fs.FileMode) error {
|
||||
if info, err := os.Lstat(path); err == nil {
|
||||
if info.Mode()&fs.ModeSymlink != 0 {
|
||||
return fmt.Errorf("%s is a symbolic link; refusing to replace it", filepath.Base(path))
|
||||
}
|
||||
mode = info.Mode().Perm()
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".pipelines-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := tmp.Name()
|
||||
done := false
|
||||
defer func() {
|
||||
if !done {
|
||||
_ = os.Remove(name)
|
||||
}
|
||||
}()
|
||||
if err := tmp.Chmod(mode); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(name, path); err != nil {
|
||||
return err
|
||||
}
|
||||
done = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type jsonRaw = json.RawMessage
|
||||
|
||||
// orderedObject is a JSON object whose keys keep their file order, so a
|
||||
// read-modify-write of .claude.json changes one key and leaves the rest
|
||||
// exactly as Claude Code wrote them.
|
||||
type orderedObject struct {
|
||||
keys []string
|
||||
values map[string]json.RawMessage
|
||||
}
|
||||
|
||||
func parseObject(data []byte) (*orderedObject, error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.UseNumber()
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if delim, ok := tok.(json.Delim); !ok || delim != '{' {
|
||||
return nil, errors.New("not a JSON object")
|
||||
}
|
||||
obj := &orderedObject{values: map[string]json.RawMessage{}}
|
||||
for dec.More() {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, ok := tok.(string)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid JSON object key")
|
||||
}
|
||||
var raw json.RawMessage
|
||||
if err := dec.Decode(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, seen := obj.values[key]; !seen {
|
||||
obj.keys = append(obj.keys, key)
|
||||
}
|
||||
obj.values[key] = raw
|
||||
}
|
||||
if _, err := dec.Token(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (o *orderedObject) get(key string) json.RawMessage { return o.values[key] }
|
||||
|
||||
func (o *orderedObject) set(key string, value json.RawMessage) {
|
||||
if _, seen := o.values[key]; !seen {
|
||||
o.keys = append(o.keys, key)
|
||||
}
|
||||
o.values[key] = value
|
||||
}
|
||||
|
||||
// encode writes the object compactly, or with Claude Code's two-space
|
||||
// indentation when indent is set.
|
||||
func (o *orderedObject) encode(indent bool) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte('{')
|
||||
for i, key := range o.keys {
|
||||
if i > 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
name, err := marshal(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf.Write(name)
|
||||
buf.WriteByte(':')
|
||||
buf.Write(o.values[key])
|
||||
}
|
||||
buf.WriteByte('}')
|
||||
var out bytes.Buffer
|
||||
if indent {
|
||||
if err := json.Indent(&out, buf.Bytes(), "", " "); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if err := json.Compact(&out, buf.Bytes()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// marshal encodes v without HTML escaping, as JSON.stringify does.
|
||||
func marshal(v any) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bytes.TrimRight(buf.Bytes(), "\n"), nil
|
||||
}
|
||||
|
||||
// dirLock is one proper-lockfile style lock: a directory whose existence is
|
||||
// the lock and whose mtime is its heartbeat. Claude Code takes
|
||||
// <config>/.oauth_refresh.lock while it refreshes a token,
|
||||
// <config>/.storage-write.lock around every credential write and
|
||||
// <config>/.claude.json.lock around every .claude.json rewrite; holding all
|
||||
// three keeps a concurrent refresh or config save from writing the old
|
||||
// account back over a switch.
|
||||
|
||||
type dirLock struct {
|
||||
path string
|
||||
stale time.Duration
|
||||
}
|
||||
|
||||
// lockWait bounds how long a switch waits for Claude Code to finish a
|
||||
// refresh or config save. It outlasts the config lock's ten-second staleness,
|
||||
// since a `claude` command that exits mid-save (as `claude auth status` does)
|
||||
// leaves that lock behind. Tests shorten it.
|
||||
var lockWait = 12 * time.Second
|
||||
|
||||
func acquire(locks []dirLock, wait time.Duration) (func(), error) {
|
||||
var held []string
|
||||
release := func() {
|
||||
for i := len(held) - 1; i >= 0; i-- {
|
||||
_ = os.Remove(held[i])
|
||||
}
|
||||
}
|
||||
for _, lock := range locks {
|
||||
if err := lock.acquire(wait); err != nil {
|
||||
release()
|
||||
return nil, err
|
||||
}
|
||||
held = append(held, lock.path)
|
||||
}
|
||||
return release, nil
|
||||
}
|
||||
|
||||
var errLocked = errors.New("Claude Code is updating this login right now; try again in a moment")
|
||||
|
||||
func (l dirLock) acquire(wait time.Duration) error {
|
||||
deadline := time.Now().Add(wait)
|
||||
for {
|
||||
err := os.Mkdir(l.path, 0o700)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, fs.ErrExist) {
|
||||
return err
|
||||
}
|
||||
if info, statErr := os.Stat(l.path); statErr == nil && time.Since(info.ModTime()) > l.stale {
|
||||
// An abandoned lock (its owner stopped updating it) is taken over
|
||||
// the way proper-lockfile does.
|
||||
_ = os.Remove(l.path)
|
||||
continue
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return errLocked
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
// 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 <config>/pipelines-accounts/<slug>/ (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
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package claudeaccounts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeLogin writes a login the way Claude Code's /login leaves it: tokens in
|
||||
// .credentials.json (beside an MCP OAuth entry it must keep) and the account
|
||||
// in .claude.json among unrelated keys.
|
||||
func fakeLogin(t *testing.T, dir, who, uuid, token string) {
|
||||
t.Helper()
|
||||
creds := map[string]any{
|
||||
"claudeAiOauth": map[string]any{
|
||||
"accessToken": "access-" + token, "refreshToken": "refresh-" + token,
|
||||
"expiresAt": 1, "scopes": []string{"user:inference"}, "subscriptionType": "max",
|
||||
"accountUuid": uuid, "organizationUuid": "org-" + uuid,
|
||||
},
|
||||
"mcpOAuth": map[string]any{"server": map[string]any{"accessToken": "mcp-secret"}},
|
||||
}
|
||||
writeJSON(t, filepath.Join(dir, ".credentials.json"), creds, false)
|
||||
config := map[string]any{}
|
||||
if data, err := os.ReadFile(filepath.Join(dir, ".claude.json")); err == nil {
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
config = map[string]any{"numStartups": 4, "projects": map[string]any{"/x": map[string]any{"allowedTools": []any{}}}, "userID": "device"}
|
||||
}
|
||||
config["oauthAccount"] = map[string]any{"accountUuid": uuid, "emailAddress": who, "organizationUuid": "org-" + uuid, "organizationName": "Org " + uuid}
|
||||
writeJSON(t, filepath.Join(dir, ".claude.json"), config, true)
|
||||
}
|
||||
|
||||
func writeJSON(t *testing.T, path string, v any, indent bool) {
|
||||
t.Helper()
|
||||
var data []byte
|
||||
var err error
|
||||
if indent {
|
||||
data, err = json.MarshalIndent(v, "", " ")
|
||||
} else {
|
||||
data, err = json.Marshal(v)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func readJSON(t *testing.T, path string) map[string]any {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(data, &out); err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func activeRefresh(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
return readJSON(t, filepath.Join(dir, ".credentials.json"))["claudeAiOauth"].(map[string]any)["refreshToken"].(string)
|
||||
}
|
||||
|
||||
func scratch(t *testing.T) (Store, string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
return Store{ConfigDir: dir}, dir
|
||||
}
|
||||
|
||||
func noTokens(t *testing.T, v any) {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"access-", "refresh-", "mcp-secret", "accessToken", "refreshToken"} {
|
||||
if strings.Contains(string(data), secret) {
|
||||
t.Fatalf("reply carries %q: %s", secret, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveUseRotateBackAndRemove(t *testing.T) {
|
||||
store, dir := scratch(t)
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
list, err := store.Save("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noTokens(t, list)
|
||||
if len(list.Accounts) != 1 || list.Accounts[0].Name != "a@example.invalid" || !list.Accounts[0].Active || list.Active == nil || !list.Active.Saved {
|
||||
t.Fatalf("after save a: %+v", list)
|
||||
}
|
||||
// A terminal /login switches to b; it is the active, unsaved login.
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
|
||||
list, err = store.List()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved || list.Accounts[0].Active {
|
||||
t.Fatalf("list with unsaved b: %+v", list)
|
||||
}
|
||||
if _, err := store.Save("Work B"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// b's tokens rotate on refresh while it is active.
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b2")
|
||||
|
||||
list, err = store.Use("a@example.invalid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
noTokens(t, list)
|
||||
if list.Active == nil || list.Active.Email != "a@example.invalid" || activeRefresh(t, dir) != "refresh-a1" {
|
||||
t.Fatalf("after use a: %+v refresh=%s", list, activeRefresh(t, dir))
|
||||
}
|
||||
config := readJSON(t, filepath.Join(dir, ".claude.json"))
|
||||
if config["oauthAccount"].(map[string]any)["emailAddress"] != "a@example.invalid" || config["userID"] != "device" || config["numStartups"].(float64) != 4 || config["projects"] == nil {
|
||||
t.Fatalf("config after use = %v", config)
|
||||
}
|
||||
creds := readJSON(t, filepath.Join(dir, ".credentials.json"))
|
||||
if creds["mcpOAuth"] == nil {
|
||||
t.Fatalf("other credentials dropped: %v", creds)
|
||||
}
|
||||
// The rotated b2 tokens were written back to b's slot, so switching back
|
||||
// installs them, not the stale b1.
|
||||
if _, err := store.Use("work b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := activeRefresh(t, dir); got != "refresh-b2" {
|
||||
t.Fatalf("switched back to %s, want the rotated refresh-b2", got)
|
||||
}
|
||||
|
||||
list, err = store.Remove("Work B")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(list.Accounts) != 1 || list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved {
|
||||
t.Fatalf("after remove: %+v", list)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, SlotsDir, "work-b")); !os.IsNotExist(err) {
|
||||
t.Fatalf("slot still present: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUseKeepsAnUnsavedLogin(t *testing.T) {
|
||||
store, dir := scratch(t)
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := store.Save("a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A terminal /login to c, never saved, then a switch back to a.
|
||||
fakeLogin(t, dir, "c@example.invalid", "uuid-c", "c1")
|
||||
list, err := store.Use("a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(list.Accounts) != 2 || list.Accounts[1].Email != "c@example.invalid" || list.Accounts[1].Active {
|
||||
t.Fatalf("the unsaved login was not kept: %+v", list.Accounts)
|
||||
}
|
||||
if _, err := store.Use("c@example.invalid"); err != nil || activeRefresh(t, dir) != "refresh-c1" {
|
||||
t.Fatalf("switch back to the kept login: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionsCachesAndFormat(t *testing.T) {
|
||||
old := syscall.Umask(0o022)
|
||||
defer syscall.Umask(old)
|
||||
store, dir := scratch(t)
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := store.Save("a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
|
||||
if err := os.Chmod(filepath.Join(dir, ".claude.json"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, cache := range orgCaches {
|
||||
writeJSON(t, filepath.Join(dir, cache), map[string]any{}, false)
|
||||
}
|
||||
keep := filepath.Join(dir, "settings.json")
|
||||
writeJSON(t, keep, map[string]any{}, false)
|
||||
before, _ := os.Stat(filepath.Join(dir, ".credentials.json"))
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if _, err := store.Use("a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for path, want := range map[string]os.FileMode{
|
||||
filepath.Join(dir, SlotsDir): 0o700,
|
||||
filepath.Join(dir, SlotsDir, "a"): 0o700,
|
||||
filepath.Join(dir, SlotsDir, "a", "credentials.json"): 0o600,
|
||||
filepath.Join(dir, SlotsDir, "a", "account.json"): 0o600,
|
||||
filepath.Join(dir, SlotsDir, "a", "slot.json"): 0o600,
|
||||
filepath.Join(dir, ".credentials.json"): 0o600,
|
||||
filepath.Join(dir, ".claude.json"): 0o640,
|
||||
} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != want {
|
||||
t.Fatalf("%s mode %v, want %v", path, info.Mode().Perm(), want)
|
||||
}
|
||||
}
|
||||
after, _ := os.Stat(filepath.Join(dir, ".credentials.json"))
|
||||
if !after.ModTime().After(before.ModTime()) {
|
||||
t.Fatal("credentials mtime did not move; running Claude Code would not reload")
|
||||
}
|
||||
for _, cache := range orgCaches {
|
||||
if _, err := os.Stat(filepath.Join(dir, cache)); !os.IsNotExist(err) {
|
||||
t.Fatalf("%s kept after a switch", cache)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(keep); err != nil {
|
||||
t.Fatal("an unrelated file was removed")
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(dir, ".claude.json"))
|
||||
if !strings.HasPrefix(string(data), "{\n \"") {
|
||||
t.Fatalf(".claude.json lost Claude Code's indentation: %.40q", data)
|
||||
}
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, entry := range entries {
|
||||
if strings.Contains(entry.Name(), ".pipelines-") || strings.HasSuffix(entry.Name(), ".lock") {
|
||||
t.Fatalf("left behind %s", entry.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeJSONKeyOrderAndValuesKept(t *testing.T) {
|
||||
store, dir := scratch(t)
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := store.Save(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
|
||||
raw := "{\n \"zeta\": 1,\n \"oauthAccount\": " + string(mustRead(t, filepath.Join(dir, ".claude.json"), "oauthAccount")) +
|
||||
",\n \"alpha\": {\n \"big\": 12345678901234567890,\n \"html\": \"<a&b>\"\n }\n}"
|
||||
if err := os.WriteFile(filepath.Join(dir, ".claude.json"), []byte(raw), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Use("a@example.invalid"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(mustReadFile(t, filepath.Join(dir, ".claude.json")))
|
||||
if !(strings.Index(got, "zeta") < strings.Index(got, "oauthAccount") && strings.Index(got, "oauthAccount") < strings.Index(got, "alpha")) {
|
||||
t.Fatalf("key order changed: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "12345678901234567890") || !strings.Contains(got, `"<a&b>"`) {
|
||||
t.Fatalf("values rewritten: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func mustReadFile(t *testing.T, path string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func mustRead(t *testing.T, path, key string) json.RawMessage {
|
||||
t.Helper()
|
||||
obj, err := parseObject(mustReadFile(t, path))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return obj.get(key)
|
||||
}
|
||||
|
||||
func TestRefusals(t *testing.T) {
|
||||
store, dir := scratch(t)
|
||||
if _, err := store.Save(""); err != ErrNoLogin {
|
||||
t.Fatalf("save while signed out: %v", err)
|
||||
}
|
||||
if _, err := (Store{ConfigDir: "relative"}).List(); err == nil {
|
||||
t.Fatal("a relative config dir was accepted")
|
||||
}
|
||||
if _, err := (Store{ConfigDir: filepath.Join(dir, "missing")}).List(); err == nil {
|
||||
t.Fatal("a missing config dir was accepted")
|
||||
}
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := store.Use("nobody"); err == nil || !strings.Contains(err.Error(), "no saved Claude account") {
|
||||
t.Fatalf("use unknown: %v", err)
|
||||
}
|
||||
if _, err := store.Save("!!!"); err == nil {
|
||||
t.Fatal("an unusable name was accepted")
|
||||
}
|
||||
if _, err := store.Save("shared"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
|
||||
if _, err := store.Save("Shared"); err == nil || !strings.Contains(err.Error(), "already names") {
|
||||
t.Fatalf("a name of another account was overwritten: %v", err)
|
||||
}
|
||||
// A credentials file that is a symlink is not replaced.
|
||||
if _, err := store.Save("b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real := filepath.Join(dir, "real-creds.json")
|
||||
if err := os.Rename(filepath.Join(dir, ".credentials.json"), real); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(real, filepath.Join(dir, ".credentials.json")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := mustReadFile(t, filepath.Join(dir, ".claude.json"))
|
||||
if _, err := store.Use("shared"); err == nil {
|
||||
t.Fatal("a symlinked credentials file was replaced")
|
||||
}
|
||||
if string(mustReadFile(t, filepath.Join(dir, ".claude.json"))) != string(before) {
|
||||
t.Fatal(".claude.json was left naming the other account after a failed switch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUseWaitsForAClaudeRefreshLock(t *testing.T) {
|
||||
defer func(old time.Duration) { lockWait = old }(lockWait)
|
||||
lockWait = 200 * time.Millisecond
|
||||
store, dir := scratch(t)
|
||||
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
|
||||
if _, err := store.Save(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
|
||||
lock := filepath.Join(dir, ".oauth_refresh.lock")
|
||||
if err := os.Mkdir(lock, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Use("a@example.invalid"); err != errLocked {
|
||||
t.Fatalf("use under a live refresh lock: %v", err)
|
||||
}
|
||||
if activeRefresh(t, dir) != "refresh-b1" {
|
||||
t.Fatal("switched while Claude Code held the refresh lock")
|
||||
}
|
||||
// An abandoned lock is taken over.
|
||||
old := time.Now().Add(-2 * time.Minute)
|
||||
if err := os.Chtimes(lock, old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Use("a@example.invalid"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if activeRefresh(t, dir) != "refresh-a1" {
|
||||
t.Fatal("did not switch after the stale lock")
|
||||
}
|
||||
}
|
||||
@@ -294,6 +294,9 @@ func (a App) Run(ctx context.Context, args []string) error {
|
||||
if len(args) > 0 && args[0] == "harness" {
|
||||
return a.harness(ctx, args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "claude-account" {
|
||||
return a.claudeAccount(ctx, args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "--version" {
|
||||
args = append([]string{"version"}, args[1:]...)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
const claudeAccountUsage = "usage: pipelines claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]"
|
||||
|
||||
// claudeAccount saves and switches the Claude login of the Claude home a
|
||||
// directory selects (its CLAUDE_CONFIG_DIR after direnv/mise), locally and
|
||||
// without a server. It changes the same files /login does, so running Claude
|
||||
// Code processes there continue on the new account.
|
||||
func (a App) claudeAccount(ctx context.Context, args []string) error {
|
||||
f := flag.NewFlagSet("claude-account", flag.ContinueOnError)
|
||||
f.SetOutput(a.Err)
|
||||
dir := f.String("dir", "", "Directory whose environment selects the Claude home (default: current directory)")
|
||||
jsonMode := f.Bool("json", false, "Machine-readable JSON")
|
||||
if err := parse(f, args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
pos := f.Args()
|
||||
if len(pos) == 0 {
|
||||
return errors.New(claudeAccountUsage)
|
||||
}
|
||||
directory := *dir
|
||||
if directory == "" {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
directory = wd
|
||||
}
|
||||
directory, err := filepath.Abs(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
configDir, err := claude.AccountConfigDir(ctx, workenv.Default, directory, os.Environ())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store := claudeaccounts.Store{ConfigDir: configDir}
|
||||
var list protocol.ClaudeAccountList
|
||||
switch {
|
||||
case pos[0] == "list" && len(pos) == 1:
|
||||
list, err = store.List()
|
||||
case pos[0] == "save" && len(pos) <= 2:
|
||||
list, err = store.Save(strings.Join(pos[1:], ""))
|
||||
case pos[0] == "use" && len(pos) == 2:
|
||||
list, err = store.Use(pos[1])
|
||||
case pos[0] == "remove" && len(pos) == 2:
|
||||
list, err = store.Remove(pos[1])
|
||||
default:
|
||||
return errors.New(claudeAccountUsage)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *jsonMode {
|
||||
return a.output(list)
|
||||
}
|
||||
fmt.Fprintf(a.Out, "Claude home: %s\n", list.ConfigDir)
|
||||
if len(list.Accounts) == 0 {
|
||||
fmt.Fprintln(a.Out, "No saved accounts.")
|
||||
}
|
||||
for _, account := range list.Accounts {
|
||||
mark := " "
|
||||
if account.Active {
|
||||
mark = "*"
|
||||
}
|
||||
fmt.Fprintf(a.Out, "%s %s%s\n", mark, account.Name, accountDetail(account))
|
||||
}
|
||||
if list.Active != nil && !list.Active.Saved {
|
||||
fmt.Fprintf(a.Out, "* %s (signed in, not saved; pipelines claude-account save)\n", list.Active.Email)
|
||||
}
|
||||
if list.Active == nil {
|
||||
fmt.Fprintln(a.Out, "Signed out.")
|
||||
}
|
||||
if pos[0] == "use" && list.Active != nil {
|
||||
fmt.Fprintf(a.Out, "Switched to %s. Running Claude Code sessions continue on it.\n", list.Active.Email)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func accountDetail(account protocol.ClaudeAccount) string {
|
||||
var parts []string
|
||||
if account.Email != "" && account.Email != account.Name {
|
||||
parts = append(parts, account.Email)
|
||||
}
|
||||
if account.Organization != "" {
|
||||
parts = append(parts, account.Organization)
|
||||
}
|
||||
if account.Plan != "" {
|
||||
parts = append(parts, account.Plan)
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return " (" + strings.Join(parts, ", ") + ")"
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
func cliLogin(t *testing.T, profile, email, uuid, token string) {
|
||||
t.Helper()
|
||||
files := map[string]string{
|
||||
".credentials.json": `{"claudeAiOauth":{"accessToken":"access-` + token + `","refreshToken":"refresh-` + token + `","subscriptionType":"max","accountUuid":"` + uuid + `"}}`,
|
||||
".claude.json": `{"userID":"device","oauthAccount":{"accountUuid":"` + uuid + `","emailAddress":"` + email + `","organizationName":"Org"}}`,
|
||||
}
|
||||
for name, content := range files {
|
||||
if err := os.WriteFile(filepath.Join(profile, name), []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeAccountCommandSavesAndSwitches(t *testing.T) {
|
||||
profile := t.TempDir()
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", profile)
|
||||
t.Setenv(workenv.DisableEnvKey, "off")
|
||||
dir := t.TempDir()
|
||||
run := func(args ...string) (string, error) {
|
||||
var out, errs bytes.Buffer
|
||||
err := App{Out: &out, Err: &errs}.Run(context.Background(), append([]string{"claude-account"}, args...))
|
||||
return out.String() + errs.String(), err
|
||||
}
|
||||
cliLogin(t, profile, "a@example.invalid", "uuid-a", "a1")
|
||||
if out, err := run("save", "--dir", dir); err != nil || !strings.Contains(out, "* a@example.invalid (Org, max)") {
|
||||
t.Fatalf("save a: %v\n%s", err, out)
|
||||
}
|
||||
cliLogin(t, profile, "b@example.invalid", "uuid-b", "b1")
|
||||
if out, err := run("list", "--dir", dir); err != nil || !strings.Contains(out, " a@example.invalid") || !strings.Contains(out, "* b@example.invalid (signed in, not saved") {
|
||||
t.Fatalf("list: %v\n%s", err, out)
|
||||
}
|
||||
if _, err := run("save", "work", "--dir", dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := run("use", "a@example.invalid", "--dir", dir, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("use: %v\n%s", err, out)
|
||||
}
|
||||
if strings.Contains(out, "access-") || strings.Contains(out, "refresh-") {
|
||||
t.Fatalf("output carries a token: %s", out)
|
||||
}
|
||||
var list protocol.ClaudeAccountList
|
||||
if err := json.Unmarshal([]byte(out), &list); err != nil {
|
||||
t.Fatalf("json: %v\n%s", err, out)
|
||||
}
|
||||
if list.ConfigDir != profile || list.Active == nil || list.Active.Email != "a@example.invalid" || len(list.Accounts) != 2 {
|
||||
t.Fatalf("use reply = %+v", list)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(profile, ".credentials.json"))
|
||||
if !strings.Contains(string(data), "refresh-a1") {
|
||||
t.Fatal("credentials not switched")
|
||||
}
|
||||
if out, err := run("remove", "work", "--dir", dir); err != nil || strings.Contains(out, "work") {
|
||||
t.Fatalf("remove: %v\n%s", err, out)
|
||||
}
|
||||
if _, err := run("use", "--dir", dir); err == nil || !strings.Contains(err.Error(), "usage:") {
|
||||
t.Fatalf("use without a name: %v", err)
|
||||
}
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
if _, err := run("list", "--dir", dir); err == nil || !strings.Contains(err.Error(), "CLAUDE_CONFIG_DIR") {
|
||||
t.Fatalf("no Claude home: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ var usage = map[string]string{
|
||||
"stats": "stats [--json]",
|
||||
"rpc": "rpc <request.json|->",
|
||||
"retention": "retention report|apply [--older-than DURATION] [--keep N] [--db FILE] [--artifacts DIR] [--json] [--yes]",
|
||||
"claude-account": "claude-account list | save [name] | use <name> | remove <name> [--dir DIR] [--json]",
|
||||
"tui": "tui",
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@ SERVER / INTERFACE
|
||||
harness setup <claude|codex|opencode|pi>
|
||||
Install check, sign-in, models and verify for one harness
|
||||
harness list Installed / signed-in / configured / default for all four
|
||||
claude-account list|save|use|remove
|
||||
Save and switch the Claude login of this directory's
|
||||
CLAUDE_CONFIG_DIR (--dir DIR); running sessions follow
|
||||
tui Open the dashboard (default with no command)
|
||||
serve Start native server in the foreground (Ctrl+C stops it)
|
||||
service enable Configure user autostart
|
||||
|
||||
@@ -812,6 +812,11 @@ type ChatAccountUsage struct {
|
||||
AsOf int64 `json:"as_of,omitempty"`
|
||||
Windows []ChatQuotaWindow `json:"windows,omitempty"`
|
||||
Unsupported bool `json:"unsupported,omitempty"`
|
||||
// SwitchedAt is when the operator last switched the chat's Claude account
|
||||
// to this one (epoch milliseconds). The report then stands for the new
|
||||
// account even with no windows yet, and a usage-limit refusal the chat
|
||||
// received before it no longer applies.
|
||||
SwitchedAt int64 `json:"switched_at,omitempty"`
|
||||
}
|
||||
|
||||
// ChatQuotaWindow is one rolling quota window. UsedPercent is 0-100 (it can
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package protocol
|
||||
|
||||
// Claude account switching for a chat whose directory selects its own Claude
|
||||
// Code home (CLAUDE_CONFIG_DIR, for example from a direnv .envrc). Each request
|
||||
// body is ClaudeAccountRequest naming the chat; the server resolves the chat's
|
||||
// directory environment to that config directory and replies with
|
||||
// ClaudeAccountList. Saved accounts live in <config dir>/pipelines-accounts/.
|
||||
// Using one changes the same files `/login` changes, in place, so running
|
||||
// Claude Code processes continue on the new account without a restart. No
|
||||
// reply or log ever carries a token.
|
||||
const (
|
||||
// ClaudeAccounts lists the saved accounts and the active login.
|
||||
ClaudeAccounts = "claude_accounts"
|
||||
// ClaudeAccountSave snapshots the active login as a saved account; Name
|
||||
// defaults to its email.
|
||||
ClaudeAccountSave = "claude_account_save"
|
||||
// ClaudeAccountUse makes the saved account Name the active login, first
|
||||
// writing the current login's refreshed tokens back to its own slot.
|
||||
ClaudeAccountUse = "claude_account_use"
|
||||
// ClaudeAccountRemove deletes the saved account Name. The active login is
|
||||
// unchanged.
|
||||
ClaudeAccountRemove = "claude_account_remove"
|
||||
)
|
||||
|
||||
// ClaudeAccountRequest is the body of every claude_account* request.
|
||||
type ClaudeAccountRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
// Name is the saved account (its name, slug or email); for a save, the
|
||||
// name to save under ("" uses the email).
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// ClaudeAccount describes one Claude login without its credentials.
|
||||
type ClaudeAccount struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Organization string `json:"organization,omitempty"`
|
||||
// Plan is the subscription type the login reports ("max", "pro").
|
||||
Plan string `json:"plan,omitempty"`
|
||||
// Active is set on the account the config directory is signed in with.
|
||||
Active bool `json:"active,omitempty"`
|
||||
// Saved is false for an active login that has no saved slot yet.
|
||||
Saved bool `json:"saved"`
|
||||
}
|
||||
|
||||
// ClaudeAccountList is the reply to every claude_account* request.
|
||||
type ClaudeAccountList struct {
|
||||
// ConfigDir is the Claude Code home the chat's directory selects.
|
||||
ConfigDir string `json:"config_dir"`
|
||||
// Active is the current login (saved or not); nil when signed out.
|
||||
Active *ClaudeAccount `json:"active,omitempty"`
|
||||
// Accounts are the saved accounts, sorted by name.
|
||||
Accounts []ClaudeAccount `json:"accounts"`
|
||||
// Usage is the newly active account's latest known quota after a
|
||||
// claude_account_use (see ChatAccountUsage.SwitchedAt).
|
||||
Usage *ChatAccountUsage `json:"usage,omitempty"`
|
||||
}
|
||||
@@ -250,6 +250,10 @@ type Message struct {
|
||||
ChatModels []ChatModel `json:"chat_models,omitempty"`
|
||||
// ChatCommands is the chat_commands reply: the session's slash commands.
|
||||
ChatCommands []ChatCommand `json:"chat_commands,omitempty"`
|
||||
// ClaudeAccount is the body of the claude_account* requests and
|
||||
// ClaudeAccounts their reply (claude_accounts.go).
|
||||
ClaudeAccount *ClaudeAccountRequest `json:"claude_account,omitempty"`
|
||||
ClaudeAccounts *ClaudeAccountList `json:"claude_accounts,omitempty"`
|
||||
// ModelRequest is the chat_model body and echoed selection.
|
||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||
|
||||
@@ -253,6 +253,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatCommands:
|
||||
handleChatCommands(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove:
|
||||
handleClaudeAccounts(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatModelSelect:
|
||||
handleChatModelSwitch(ctx, request, broker, write)
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatAccountSwitcher is Claude Code's saved-account surface
|
||||
// (claude.Chat.ClaudeAccounts): list, save, use and remove the logins of the
|
||||
// Claude home a chat's directory selects.
|
||||
type chatAccountSwitcher interface {
|
||||
ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error)
|
||||
}
|
||||
|
||||
var errNotClaudeChat = errors.New("Claude accounts apply to Claude Code chats only")
|
||||
|
||||
// ClaudeAccounts routes a claude_account* request to the Claude adapter with
|
||||
// the chat's recorded directory. Other harnesses are refused.
|
||||
func (m *chatManager) ClaudeAccounts(ctx context.Context, sessionID, operation, name string) (protocol.ClaudeAccountList, error) {
|
||||
if m.backendFor(ctx, sessionID) != claude.Backend {
|
||||
return protocol.ClaudeAccountList{}, errNotClaudeChat
|
||||
}
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return protocol.ClaudeAccountList{}, err
|
||||
}
|
||||
switcher, ok := adapter.(chatAccountSwitcher)
|
||||
if !ok {
|
||||
return protocol.ClaudeAccountList{}, errNotClaudeChat
|
||||
}
|
||||
directory := ""
|
||||
if m.registry != nil {
|
||||
if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found {
|
||||
directory = row.Directory
|
||||
}
|
||||
}
|
||||
return switcher.ClaudeAccounts(ctx, sessionID, directory, operation, name)
|
||||
}
|
||||
|
||||
// handleClaudeAccounts answers claude_accounts, claude_account_save,
|
||||
// claude_account_use and claude_account_remove. Replies describe accounts
|
||||
// only; no token ever leaves the server.
|
||||
func handleClaudeAccounts(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
body := request.ClaudeAccount
|
||||
if body == nil || !validChatSessionID(body.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
if (request.Type == protocol.ClaudeAccountUse || request.Type == protocol.ClaudeAccountRemove) && body.Name == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a saved account name is required"})
|
||||
return
|
||||
}
|
||||
switcher, ok := broker.(interface {
|
||||
ClaudeAccounts(ctx context.Context, sessionID, operation, name string) (protocol.ClaudeAccountList, error)
|
||||
})
|
||||
if !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errNotClaudeChat.Error()})
|
||||
return
|
||||
}
|
||||
list, err := switcher.ClaudeAccounts(ctx, body.SessionID, request.Type, body.Name)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = write(protocol.Message{Type: request.Type, ID: request.ID, ClaudeAccounts: &list})
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// accountChat is a Claude harness with saved accounts.
|
||||
type accountChat struct {
|
||||
*fakeChat
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (c *accountChat) ClaudeAccounts(_ context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) {
|
||||
c.calls = append(c.calls, strings.Join([]string{sessionID, directory, operation, name}, "|"))
|
||||
return protocol.ClaudeAccountList{
|
||||
ConfigDir: "/home/op/caplens/.claude-profile",
|
||||
Active: &protocol.ClaudeAccount{Name: "b@example.invalid", Email: "b@example.invalid", Active: true, Saved: true},
|
||||
Accounts: []protocol.ClaudeAccount{
|
||||
{Name: "a@example.invalid", Email: "a@example.invalid", Plan: "max", Saved: true},
|
||||
{Name: "b@example.invalid", Email: "b@example.invalid", Active: true, Saved: true},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestClaudeAccountRequestsRouteToTheChatsClaudeHome(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
claudeID := "01900000-0000-7000-8000-000000000021"
|
||||
codexID := "01900000-0000-7000-8000-000000000022"
|
||||
for id, backend := range map[string]string{claudeID: "claude", codexID: "codex"} {
|
||||
if err := store.RecordOperatorSession(ctx, id, "/home/op/caplens", "chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, id, backend); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
claudeChat := &accountChat{fakeChat: scriptedChat()}
|
||||
manager := &chatManager{claude: claudeChat, codex: scriptedChat(), registry: store, cache: map[string]string{}}
|
||||
var reply protocol.Message
|
||||
capture := func(msg protocol.Message) error { reply = msg; return nil }
|
||||
|
||||
for _, kind := range []string{protocol.ClaudeAccounts, protocol.ClaudeAccountSave, protocol.ClaudeAccountUse, protocol.ClaudeAccountRemove} {
|
||||
handled := handleChat(ctx, protocol.Message{Type: kind, ID: "r-" + kind, ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID, Name: "a@example.invalid"}}, manager, nil, store, "client", capture)
|
||||
if !handled || reply.Type != kind || reply.ID != "r-"+kind || reply.ClaudeAccounts == nil || len(reply.ClaudeAccounts.Accounts) != 2 {
|
||||
t.Fatalf("%s reply = %+v", kind, reply)
|
||||
}
|
||||
}
|
||||
want := []string{
|
||||
claudeID + "|/home/op/caplens|claude_accounts|a@example.invalid",
|
||||
claudeID + "|/home/op/caplens|claude_account_save|a@example.invalid",
|
||||
claudeID + "|/home/op/caplens|claude_account_use|a@example.invalid",
|
||||
claudeID + "|/home/op/caplens|claude_account_remove|a@example.invalid",
|
||||
}
|
||||
if strings.Join(claudeChat.calls, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("calls = %v", claudeChat.calls)
|
||||
}
|
||||
wire, _ := json.Marshal(reply)
|
||||
if !strings.Contains(string(wire), `"claude_accounts":{"config_dir":"/home/op/caplens/.claude-profile","active":{"name":"b@example.invalid"`) {
|
||||
t.Fatalf("wire = %s", wire)
|
||||
}
|
||||
|
||||
// Other harnesses, a missing name for use/remove, and a bad id are refused.
|
||||
for _, request := range []protocol.Message{
|
||||
{Type: protocol.ClaudeAccounts, ID: "x1", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: codexID}},
|
||||
{Type: protocol.ClaudeAccountUse, ID: "x2", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID}},
|
||||
{Type: protocol.ClaudeAccountRemove, ID: "x3", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: claudeID}},
|
||||
{Type: protocol.ClaudeAccounts, ID: "x4", ClaudeAccount: &protocol.ClaudeAccountRequest{SessionID: "../etc"}},
|
||||
{Type: protocol.ClaudeAccounts, ID: "x5"},
|
||||
} {
|
||||
handleChat(ctx, request, manager, nil, store, "client", capture)
|
||||
if reply.Type != protocol.Error || reply.ID != request.ID {
|
||||
t.Fatalf("%s accepted: %+v", request.ID, reply)
|
||||
}
|
||||
}
|
||||
if len(claudeChat.calls) != 4 {
|
||||
t.Fatalf("a refused request reached the harness: %v", claudeChat.calls)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user