store

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store persists the accounts ccdad manages.

Identity has four axes and three roles. uuid is the durable primary key: it survives an email change and a reordering, and it is what --json and exports carry. idx is a display ordinal for typing and for TUI hotkeys. email is the human label and may legitimately repeat across organizations. alias is an optional user handle.

idx is deliberately NOT a key. cswap keys its slots by number and has to move backups, aliases and session directories every time two accounts swap places; keying on uuid removes that whole class of migration work.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLockBusy means another process held the store lock for longer than
	// LockTimeout. It is a sentinel so a caller can tell contention — retry
	// later — from a filesystem that cannot lock at all.
	ErrLockBusy = errors.New("another process is holding the ccdad store")
	// ErrLocksUnsupported means this filesystem cannot do locks: ENOLCK on an
	// NFS or CIFS mount with no lock daemon, or a GOOS gofrs/flock has no
	// implementation for.
	//
	// It is a refusal, never a silent proceed. Writing anyway would be exactly
	// the lost-account race this lock exists to close, silently, on the one
	// class of machine where it is most likely to happen — a home directory on
	// a network mount is shared, so it is the case with the most writers.
	ErrLocksUnsupported = errors.New("this filesystem does not support locks")
)
View Source
var (
	// ErrNotFound means no account matched the reference.
	ErrNotFound = errors.New("no such account")
	// ErrAmbiguous means more than one account matched.
	ErrAmbiguous = errors.New("that reference matches more than one account")
	// ErrBadAlias means an alias failed validation.
	ErrBadAlias = errors.New("invalid alias")
	// ErrAliasTaken means the alias is well-formed but another account holds
	// it. It is separate from ErrBadAlias so a caller does not answer a
	// collision with advice about the charset.
	ErrAliasTaken = errors.New("alias already in use")
)
View Source
var ErrInterrupted = errors.New("interrupted")

ErrInterrupted means a signal arrived while a store transaction was writing.

It is a sentinel for two readers. internal/cli maps it to ExitInterrupted, so an interrupted `ccdad import` exits 130 like every other Ctrl-C in this binary rather than 1; and a caller that wants to distinguish "the user stopped this" from "the disk failed" has something to match on. Both messages wrapping it say which side of the commit the signal landed on, because the answer to "is my change saved" is opposite on the two sides.

View Source
var LockTimeout = 5 * time.Second

LockTimeout bounds how long a caller waits for the store lock.

The longest legitimate hold is a switch, which takes Claude Code's three credential locks inside this one; cclink.LockTimeout bounds each of those, so the worst case there is roughly three times that. This is deliberately shorter: a CLI command that cannot get in should say so rather than stall for half a minute, and the caller who lost is the one who can retry cheaply.

It is a var so a test can shrink it and reach the timeout path without an unbounded contention test.

Functions

func AccountsFileAt added in v0.3.0

func AccountsFileAt(root string) string

AccountsFileAt names the document. See CredentialsDirAt.

func CredentialsDirAt added in v0.3.0

func CredentialsDirAt(root string) string

CredentialsDirAt and AccountsFileAt name a store's two on-disk parts without resolving, creating or opening anything.

They exist because `ccdad doctor` had no way to say these two paths. It spelled both out itself and recorded why — "store exports no path accessors and opening it would create the tree" — which was the wrong generalisation from a true difficulty: LockPath was already exported, for this exact reason and saying so in its own comment, and what the credentials directory and the document lacked was an accessor of their own rather than a policy against having one. The duplicate is the kind that goes wrong quietly: a diagnostic holding its own copy of a naming rule keeps reporting on a directory the store has stopped using, and answers "nothing is wrong" from it.

func LockPath

func LockPath() (string, error)

LockPath is the store lock's path. `ccdad doctor` reports the layout, so the name lives in one place rather than in a string literal per reader.

func NormalizeAlias

func NormalizeAlias(alias string) string

NormalizeAlias lowercases and trims an alias to its stored form.

func OrphanCredentialsAt added in v0.3.0

func OrphanCredentialsAt(root string) ([]string, error)

OrphanCredentialsAt returns the paths of credential files under root that no account names, sorted.

Such a file is a leak that nothing else on the machine can find. `ccdad list`, `ccdad remove` and doctor's account rows all read accounts.toml, and an orphan is by definition a uuid the document does not carry — so it sits there holding a live refresh token at 0600, indefinitely. rollback narrowed the way they are MADE — it runs from a defer now, and mutate holds SIGINT across the write — but it did not close it, because SIGKILL and a power cut are not closable, and it does nothing at all for a store that already has one, left by an older build or by a reversal whose os.Remove was refused.

It reads under the store lock, unlike AccountsAt, and unlike its own first draft: see the lock paragraph below. A store that is not there still yields no orphans rather than being brought into existence by the probe asking about it. An unreadable accounts.toml is an ERROR rather than an empty answer — "nothing is orphaned", said out of a read that failed, is precisely the reassuring lie the caller exists to remove.

The rule is a file named <uuid>.json, which is credentialPath's rule read backwards, with two departures both of which are about not lying to the caller. The suffix is matched WITHOUT case, on every platform, because macOS and Windows hand credentialPath a file called uuid.JSON when it asks for uuid.json -- so on those a case-sensitive test would skip a credential file the store itself reads -- and because a store is one rsync away from being opened on another platform, which is the argument ValidateUUID's device-name check already makes. And each survivor is os.Stat-ed: ReadDir does not follow symlinks, so a dangling link or a directory named <uuid>.json reads as a file here, and the caller says of everything in this list that it holds a live refresh token at 0600 and can be deleted.

The Stat is also the only thing standing between this and a torn answer over a REMOVE: the listing and the account read are two syscalls, and a concurrent `ccdad remove` completing between them leaves a uuid in neither -- gone from the document and gone from the disk -- which without the Stat is reported as an orphan pointing at nothing.

The lock closes the opposite direction, an ADD or an IMPORT: Store.add writes a credential file before the document names it (store.go's own mutate re-reads accounts.toml inside the lock precisely because of that ordering), so a lockless read here can see the new file and the old document in the same instant and call a credential about to be claimed an orphan -- and doctor's own text for this row says to delete it. Held for the read the same way mutate holds it for a write, that instant cannot be observed: the listing and the document are both from the same committed state, whichever one that is. A root with no store yet -- no lock file's directory to open -- answers what it already did: no orphans rather than a store the probe brought into existence.

Anything else in the directory is not a credential file this store wrote: an interrupted WriteFileAtomic leaves <name>.tmp-* beside its target, and calling that stem a uuid would send the user looking for an account that never existed.

func ValidateAlias

func ValidateAlias(alias string) error

ValidateAlias enforces the alias rules against the NORMALIZED form, so a caller that validates a flag value before touching the store gets the same verdict SetAlias would give it.

Two of the rules are structural rather than cosmetic. An alias may not be purely numeric, because Resolve tries an index first and the two axes would otherwise name different accounts for the same token. An alias may not start with a hyphen, so `ccdad run <ACCT>` can reject a leading-hyphen token as a usage error rather than mistaking a flag for an account.

func ValidateUUID

func ValidateUUID(uuid string) error

ValidateUUID refuses anything that could not be an account uuid. The value arrives from the profile endpoint and becomes a path component, so a traversal sequence in it would write a credential file outside the store.

It is exported for the same reason ValidateAlias is: a caller staging many accounts — `ccdad import` — has to be able to reject the whole batch BEFORE the first credential file is written, and the only alternative is re-spelling the rule somewhere it can drift from this one.

func WithStore

func WithStore(fn func(*Store) error) error

WithStore runs fn against the store under the cross-process lock and writes what it changed, once.

This is how a caller makes SEVERAL changes land together. The individual mutators each take the lock themselves, so a caller changing one thing does not need this; a caller importing five accounts does, or an alias collision on the fourth leaves three written and two not, with no rollback.

fn returning an error leaves accounts.toml exactly as it was, and now the credentials directory with it: mutate replays what the transaction wrote there, backwards, through Store.rollback. A batch that fails on the fourth of five accounts — an I/O failure on that credential write, which is what remains once a caller has judged its document up front — leaves neither three accounts in the file nor three credential files beside it. The second was the worse half: a live refresh token that `ccdad list`, `ccdad remove` and `ccdad doctor` could not see, because all three read the file.

One change is deliberately NOT reversed: the content of a credential file the transaction only overwrote. rollback says why, and the cost is real — an account that was already stored can come out of a refused transaction holding credentials it did not have going in.

A batch STOPPED rather than refused is reversed the same way. Ctrl-C partway through `ccdad import` used to be the ordinary way to leave a live refresh token nothing on the machine could find; mutate holds SIGINT for the span of the write, and the error it returns wraps ErrInterrupted so the command exits 130 rather than reporting an I/O failure for something the user cancelled.

Types

type Account

type Account struct {
	// UUID is account.uuid from the profile endpoint. The primary key, and the
	// name of the account's credential file, so it is charset-checked on the
	// way in — see ValidateUUID.
	UUID string `toml:"uuid"`
	// Email labels the account for humans.
	Email string `toml:"email"`
	// Alias is an optional short handle, unique across accounts. Stored in its
	// normalized form; see NormalizeAlias.
	Alias string `toml:"alias,omitempty"`
	// Idx is the 1-based display ordinal. Stored rather than derived so it is
	// stable across restarts.
	Idx int `toml:"idx"`
	// Kind is how the account is metered. Callers set this one.
	Kind identity.Kind `toml:"-"`
	// KindName is Kind's serialized form, because TOML has no enum. It is
	// maintained by Save, which overwrites it from Kind on every write — a
	// caller that sets only KindName silently loses it.
	KindName string `toml:"kind"`
	// Tier is organization_type, e.g. claude_max.
	Tier string `toml:"tier,omitempty"`
	// RateLimitTier is rate_limit_tier, e.g. default_claude_max_20x.
	RateLimitTier string `toml:"rate_limit_tier,omitempty"`
	// OrganizationUUID is the owning organization, when the profile reported
	// one. The ambiguous-email error names it, so a user with the same address
	// in two organizations can tell the candidates apart.
	OrganizationUUID string `toml:"organization_uuid,omitempty"`
	// OAuthAccountSnapshot is the exact oauthAccount object Claude Code held
	// in ~/.claude.json for this account, captured by ccdad the moment a
	// switch displaced it as the live login. A later switch back restores it
	// verbatim, because reconstructing it from the fields above would drop
	// everything the profile lookup above never asked for -- displayName,
	// billingType, the trial and onboarding flags. Empty for an account
	// ccdad has never switched AWAY from; see switcher.SyncGlobalConfigIdentity.
	OAuthAccountSnapshot string `toml:"oauth_account_snapshot,omitempty"`
	// Disabled holds an account out of auto-rotation while keeping it a valid
	// explicit switch target.
	Disabled bool `toml:"disabled,omitempty"`
	// Elsewhere says another machine's ccdad owns this account, so this one
	// neither ranks it nor polls it.
	//
	// It is a SECOND flag rather than a use of Disabled, and the difference is
	// the one that matters across machines. Disabled is a statement about the
	// account -- do not rotate into this one -- and a disabled account is still
	// polled, because `ccdad switch` can still name it and a named switch wants
	// a fresh reading. Elsewhere is a statement about THIS MACHINE: the account
	// is somebody else's to drive, so a reading taken here buys nothing and
	// spends a budget that is shared with whoever is driving it.
	//
	// Why the flag exists at all: two ccdad installs reading the same accounts
	// rank them with the same pure function and the same uuid tie-break, so they
	// converge on the same target and stack two machines' inference onto one
	// five-hour window while the rest of the pool sits idle. Nothing can
	// coordinate that at runtime -- every lock in this tree and in both
	// reference projects is a local flock -- so the partition has to be declared.
	//
	// The live account is the documented exception on the poll path: an account
	// this machine did not choose can still be the one Claude Code is logged in
	// as, and going blind on the live login is how the engine loses its
	// hysteresis baseline.
	Elsewhere bool `toml:"elsewhere,omitempty"`
	// Primary marks an account whose credits are its ORDINARY metering rather
	// than overage — an enterprise seat billed in credits and nothing else. It
	// is ranked beside the subscription accounts instead of waiting in the
	// last-resort credit pool, and credit.max_auto_spend does not gate it,
	// because a ceiling that defaults to 0 would mean the seat could never be
	// used at all. Typing the command that sets this IS the second opt-in that
	// ceiling otherwise supplies.
	Primary bool `toml:"primary,omitempty"`
	// AddedAt is when ccdad first stored this account.
	AddedAt time.Time `toml:"added_at"`
	// Credit is the credit balance kept alongside the classification. An
	// account that is both — a subscription with overage enabled — classifies
	// as Subscription and keeps its credit balance as a SECONDARY axis,
	// because credits are not spent while a subscription window still has
	// room — but the engine still has to know what is there when that window
	// runs out.
	Credit CreditBalance `toml:"credit,omitempty"`
}

Account is one managed Claude Code account.

func AccountsAt added in v0.3.0

func AccountsAt(root string) ([]Account, error)

AccountsAt reads a store's accounts WITHOUT creating any part of it.

Open is the ordinary entry point and it is the wrong one for a diagnostic: it does an MkdirAll and two Chmods, which is right for every caller that is about to write and manufactures the very thing `ccdad doctor` was asked to report on. This is the same read Open performs, with the creation and the mode tightening left out — a store that is not there yields no accounts rather than being brought into existence.

It takes the root rather than resolving one so the caller that already resolved it does not resolve it twice and risk answering about a different directory than the rest of its report.

func Resolve

func Resolve(accounts []Account, ref string) (Account, error)

Resolve maps a user-typed reference to exactly one account.

Order: index, then alias, then email, then uuid prefix. There is no substring or fuzzy matching at any step.

func (Account) Label

func (a Account) Label() string

Label is the account's best human name: the alias when it has one, else the email, else a short uuid.

type CreditBalance

type CreditBalance struct {
	// State is usage.ExtraUsageState's name: enabled, disabled, blocked, or
	// empty for an account no reading has covered yet.
	State string `toml:"state,omitempty"`
	// DisabledReason is the organization's own word for a refusal, kept
	// verbatim because it is what a notification says out loud.
	DisabledReason string `toml:"disabled_reason,omitempty"`
	// Currency is the ISO code the figures below are denominated in, so that a
	// stored 150 is never ambiguous between $150 and ¥150.
	Currency string `toml:"currency,omitempty"`
	// MonthlyLimit is the account's own spend cap, in the MAJOR unit — dollars
	// for USD, the same unit max_auto_spend is written in. The endpoint reports
	// it in the minor unit; usage.ExtraUsage converts, and that conversion
	// happens in exactly one place. Nil means the account sets no cap —
	// unlimited — which is not the same as a cap of zero.
	MonthlyLimit *float64 `toml:"monthly_limit,omitempty"`
	// UsedCredits is what has already been spent, in the same major unit. Nil
	// means it could not be read, and that refuses a switch rather than reading
	// as zero.
	UsedCredits *float64 `toml:"used_credits,omitempty"`
	// ObservedAt is when the reading behind these figures was taken. The zero
	// time means no reading ever has been.
	ObservedAt time.Time `toml:"observed_at,omitempty"`
}

CreditBalance is what a usage reading last said about an account's overage credits.

The two figures are pointers because the credit gate branches on used_credits being nil and fails closed on money: a balance that could not be read must never persist as "$0 spent, full cap available". State is a string rather than a typed enum so that reading an accounts.toml stays free of the usage package; callers turn it back into one with usage.ParseExtraUsageState, which reads anything it does not recognize as unknown.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is ccdad's account database.

Every mutator runs its read-modify-write under the cross-process lock in lock.go, which is what makes two concurrent ccdad processes safe: the state is re-read inside the lock, so the write is against what the previous holder left rather than against whatever Open happened to see. Reads take no lock — every write is an atomic rename, so a reader sees one whole version of the document or another, never a torn one.

A Store is NOT safe for concurrent use by several goroutines in one process. The lock excludes other processes; it does not serialize this one.

func Open

func Open() (*Store, error)

Open loads the store, creating an empty one if none exists.

func (*Store) Accounts

func (s *Store) Accounts() []Account

Accounts returns the managed accounts in display order.

func (*Store) ActiveUUID

func (s *Store) ActiveUUID() string

ActiveUUID is the last account ccdad activated, or "".

func (*Store) Add

func (s *Store) Add(a Account, creds cclink.Blob) error

Add stores an account and its account-scoped credentials.

Re-adding an existing uuid updates it in place: the fresh login replaces the stored credentials while the alias, the display index and the two per-account flags — disabled and primary, which belong to the user rather than to the login — survive. This is what makes `ccdad add` double as re-authentication.

func (*Store) ApplyUsage

func (s *Store) ApplyUsage(uuid string, snap *usage.Snapshot, observedAt time.Time) error

ApplyUsage records a SUCCESSFUL usage reading against an account: it revises the account's Kind if the reading is evidence, and refreshes the credit balance the account keeps alongside it as a secondary axis.

Taking a non-nil *usage.Snapshot is the whole point of the signature. The Classify calls in `ccdad add` and `add-token` all pass an empty UsageShape, so the window evidence Classify makes primary is never consulted there — and the fix must not be a function that can be handed "no reading" and quietly apply Classify's no-evidence default. A failed poll has nothing to pass here, and passing nil is refused rather than treated as an empty reading.

The read-modify-write runs under the store lock like every other mutator, so the daemon applying a poll result and a CLI adding an account cannot lose each other's write. The nil check happens BEFORE the lock is taken: a caller that has nothing to apply should not make every other writer wait for it.

func (*Store) Credentials

func (s *Store) Credentials(uuid string) (cclink.Blob, error)

Credentials returns an account's stored account-scoped keys.

func (*Store) Get

func (s *Store) Get(uuid string) (Account, bool)

Get looks an account up by uuid.

func (*Store) Move

func (s *Store) Move(uuid string, position int) (changed bool, err error)

Move puts an account at a 1-based display position and renumbers the rest.

A position past the end clamps to the end rather than erroring: "put it last" is what a caller who typed a big number meant, and the alternative is making them count. A position below 1 clamps to the front for the same reason — callers that want to refuse 0 as a non-position do so before calling, where they can say so in the user's own terms.

It renumbers rather than reorders-and-sorts. sortAndReindex sorts on the Idx values already stored, so a moved slice handed to it is sorted straight back into the order it started in — which is also what a "just set the new Idx and Save" implementation runs into on the next Open, where two accounts then share an Idx and SliceStable breaks the tie by slice position.

It reports whether the account actually moved, so a caller can spend exit 3 on a move that asked for the position the account already holds.

Every account between the source and the destination changes number, so a script holding an idx from an earlier `ccdad list` now acts on a different account. That is the stability contract in `ccdad --help` — idx is an ordinal, not a key — and move is the command that makes it routine rather than a side effect of removal.

func (*Store) Remove

func (s *Store) Remove(uuid string) error

Remove deletes an account and its stored credentials.

func (*Store) SetActive

func (s *Store) SetActive(uuid string) error

SetActive records which account ccdad last activated.

func (*Store) SetAlias

func (s *Store) SetAlias(uuid, alias string) error

SetAlias assigns a unique alias. An empty alias clears it.

func (*Store) SetDisabled

func (s *Store) SetDisabled(uuid string, disabled bool) (changed bool, err error)

SetDisabled holds an account out of auto-rotation, or puts it back, and reports whether that was a change.

Disabled is a policy for the auto engine and NOT a lock: an explicit `ccdad switch <account>` still works on a disabled account, because a user naming an account by hand has said what they want more clearly than the flag has. The bool exists so the caller can spend the exit contract's exit 3 — "the world is already as you asked" — rather than reporting a no-op as an action taken.

func (*Store) SetOAuthAccountSnapshot added in v0.4.1

func (s *Store) SetOAuthAccountSnapshot(uuid string, snapshot json.RawMessage) error

SetOAuthAccountSnapshot records the oauthAccount object Claude Code held for this account in ~/.claude.json at the moment a switch displaced it as the live login. See switcher.SyncGlobalConfigIdentity, the only caller.

func (*Store) SetOwned added in v0.5.0

func (s *Store) SetOwned(uuids []string) (changed int, err error)

SetOwned declares the accounts this machine drives, and reports how many rows changed.

It is transactional over the WHOLE list and not a per-account setter, because the partition is one statement: every uuid named is owned here, every uuid not named belongs to another machine. A per-account toggle would let a user own account 3 on both machines by forgetting to run the other half, which is the failure the flag exists to prevent and is invisible until a five-hour window burns twice as fast.

An empty owned set clears the partition -- this machine owns everything again, the state every store is in before `ccdad own` is first run. It is spelled as the empty set rather than as a separate verb so that "own nothing" cannot be typed by accident: the CLI requires --clear for it.

Every uuid must resolve, and nothing is written unless all of them do. A partial application would leave the machine owning a set the user did not ask for, which is worse than refusing.

func (*Store) SetPrimary added in v0.3.0

func (s *Store) SetPrimary(uuid string, primary bool) (changed bool, err error)

SetPrimary marks an account as metered in credits BY DESIGN, or unmarks it, and reports whether that was a change.

It takes the caller's word and checks nothing about the account's kind. Kind is re-derived from the last profile read on every load, so an account that reads as subscription today can read as credit tomorrow; a store that refused the flag on today's answer would make the setting depend on when it was typed. Looking at the account, and explaining a refusal, belongs where there is a user to explain it to.

The bool is here for the same reason SetDisabled's is: a caller can spend the exit contract's exit 3 — the world is already as you asked — rather than reporting a no-op as an action taken.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL