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 // /.oauth_refresh.lock while it refreshes a token, // /.storage-write.lock around every credential write and // /.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) } }