cclink

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 23 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 cclink classifies and merges the top-level keys of Claude Code's .credentials.json, and reads and writes the file itself — Load, Activate, ActivateWith, ClearLogin, and the atomic writer.

The file holds twelve top-level keys, not one. Five travel with the account and seven belong to the machine; getting the split wrong destroys either the user's MCP server logins and machine device identity (too much swapped) or leaks one account's device token into another (too little).

Index

Constants

View Source
const APIKeyKind = "api-key"

APIKeyKind is the TokenRecord.Kind an API key is stored under. The other is "setup-token", which Claude Code reads from the environment only and which therefore has no activation path at all.

View Source
const SelfRefreshThreshold = 5 * time.Minute

SelfRefreshThreshold is how long before expiresAt Claude Code stops using an access token and spends its refresh token instead.

Read out of the 2.1.241 bundle rather than guessed. The whole decision is one function:

function Yfe(e){if(e===null)return!1;let t=300000;return Date.now()+t>=e}

and the refresh entry point is gated on it twice — once before taking Claude Code's `.oauth_refresh.lock` and again on the re-read under it, both returning "not_needed" when it answers false. So a credential further out than this is one Claude Code will simply USE, and a credential inside it is one Claude Code will rotate the moment it looks.

That makes this the threshold a SWAP has to respect, which is why the constant lives here rather than in the token machinery. Installing a credential inside this window hands Claude Code a rotation it did not ask for, and the rotation moves the refresh token out from under whatever copy ccdad still holds.

View Source
const TokenKey = "ccdadToken"

TokenKey is ccdad's own record for a credential Claude Code does NOT read out of the credentials file.

The 2.1.238 bundle is explicit about both kinds. An API key is persisted to ~/.claude.json as the top-level string primaryApiKey (function Saa), and the claudeAiOauth object has exactly eight keys — accessToken, refreshToken, expiresAt, refreshTokenExpiresAt, scopes, subscriptionType, rateLimitTier, clientId (function hjd) — none of which is an API key. A setup token is not persisted at all: `claude setup-token` prints it and tells the user to export CLAUDE_CODE_OAUTH_TOKEN, and the OAuth flow's setup-token branch deliberately skips the credential save.

So neither belongs under claudeAiOauth. Putting one there would write a record Claude Code never writes and cannot read as a login. This key is ccdad's own, plainly named as such; Activate refuses a snapshot with no claudeAiOauth, which makes the separation fail-closed.

It is deliberately absent from both AccountScopedKeys and KnownMachineKeys. Merge copies only AccountScopedKeys out of an incoming snapshot, so this key can never reach the live file however a caller mishandles it — the same fail-closed direction, enforced by the merge rather than by care.

Variables

View Source
var (
	// ErrTooLarge means the credentials file exceeded the 1 MiB cap.
	ErrTooLarge = errors.New("credentials file is too large to be valid")
	// ErrSymlink means the credentials path is a symlink. Claude Code opens
	// it O_NOFOLLOW and refuses; ccdad refuses for the same reason, via the
	// platform-specific openCredentialsFile in store_unix.go / store_windows.go,
	// so neither process can be redirected into reading or writing tokens
	// somewhere unexpected.
	ErrSymlink = errors.New("credentials path is a symlink")
	// ErrNoChange is what an ActivateWith decision returns to stand down: the
	// locks were taken, the file was read, and the answer is that nothing should
	// be written. It is a sentinel rather than a (Blob, bool) return so the one
	// path that must never be confused with it -- a decision that FAILED -- keeps
	// its own error, and so a caller can tell the two apart with errors.Is.
	ErrNoChange = errors.New("the credentials file is to be left as it is")
)
View Source
var AccountScopedKeys = []string{
	"claudeAiOauth",
	"organizationUuid",
	"trustedDeviceToken",
	"enterpriseGateway",
	"designOauth",
}

AccountScopedKeys are the keys that travel with the login.

This list mirrors, exactly, the set Claude Code deletes in its own re-login prune. Expressing the rule as a deny-list rather than allow-listing the machine-scoped keys is deliberate: when Anthropic adds a new machine-scoped key, a deny-list preserves it automatically, whereas an allow-list destroys it on every switch. The cost is that a new ACCOUNT-scoped key would leak until ccdad is updated — rare, and caught by UnknownKeys.

View Source
var ErrGlobalConfigShape = errors.New("the Claude Code config is not a JSON object")

ErrGlobalConfigShape means ~/.claude.json is not a JSON object. ccdad refuses to write over one rather than replacing it: whatever is there is the user's, and a file we cannot merge into is a file we cannot edit without loss.

View Source
var ErrKeychainUnsupported = errors.New("the macOS Keychain does not exist on this platform")

ErrKeychainUnsupported means this platform has no macOS Keychain. It is not a failure -- callers report it as "does not apply here".

View Source
var ErrLoginHalfWritten = errors.New("the keychain item Claude Code reads first now holds the new login, " +
	"and the credentials file behind it does not")

ErrLoginHalfWritten is a switch whose keychain item took the new login and whose credentials file did not: a split login, made by the switch itself. The daemon repairs it on its next pass, and an engine that made it remembers the switch so the repair records it as that switch.

View Source
var ErrLoginOutcomeUnknown = errors.New("whether the keychain item now holds the new login is not known")

ErrLoginOutcomeUnknown is a switch whose keychain write ran out of time and whose item could not be read back to say whether it landed -- or held a login that was neither, or moved on before the credentials file could follow. Nothing further was written: the credentials file still holds what it held, and the item holds either login, or one that replaced it since. It is not "nothing changed" and it is not "switched", and a caller must not report either.

View Source
var GlobalConfigLockTimeout = 5 * time.Second

GlobalConfigLockTimeout bounds the wait for the ~/.claude.json lock. Claude Code holds it for a read-modify-write of a local file with no network call in between, so this outlasts a normal hold by a wide margin.

It is a var so a test can shrink it, exactly as LockTimeout is.

View Source
var KnownMachineKeys = []string{
	"mcpOAuth",
	"mcpOAuthClientConfig",
	"mcpXaaIdp",
	"mcpXaaIdpConfig",
	"pluginSecrets",
	"gatewayTrust",
	"coworkRemoteDevice",
}

KnownMachineKeys are the machine-scoped keys observed in Claude Code 2.1.238. This list is documentation and drift detection only: Merge preserves anything not in AccountScopedKeys whether or not it appears here.

View Source
var LockTimeout = 9 * time.Second

LockTimeout bounds the wait for each Claude Code lock. Claude Code holds the credential locks for one token-endpoint round trip, so this outlasts a normal hold without stalling the CLI indefinitely. It is per lock, so the worst case is roughly three times this.

It is a var, not a const, so a test can shrink it to exercise the timeout path -- the one that produces the error the CLI maps to a non-zero exit code -- without an unbounded contention test.

Functions

func APIKeyApproval

func APIKeyApproval(key string) string

APIKeyApproval is the value Claude Code stores in customApiKeyResponses to stand for a key, and the value it looks the environment's ANTHROPIC_API_KEY up by: `Cbe(e){return e.trim().slice(-20)}`, verbatim from 2.1.238.

The LAST twenty characters, not the first. Both halves matter: an entry built from the prefix is one Claude Code will never match, so the key would be silently rejected at every interactive start.

JavaScript's slice counts UTF-16 code units where this counts bytes. The two agree for every real key -- they are ASCII, `sk-ant-api03-...` -- and a value where they would disagree is not a Claude API key.

func Activate

func Activate(incoming Blob) error

Activate makes incoming the live login.

The whole read-merge-write runs under Claude Code's three credential locks, acquired via cclock.AcquireCredentials in Claude Code's own order. Without them, a switch landing inside Claude Code's refresh window is overwritten by the refreshed OLD account's token, and the snapshot ccdad just took keeps a pre-rotation refresh token. Under the locks, Claude Code's own double-checked re-read sees the swapped credential and abandons its refresh.

The file is re-read INSIDE the lock (loadFrom held.Scope(), never Load's fresh ccpath.CredentialsPath()): whatever was loaded before the wait may be stale by the time the lock is granted, and a freshly re-resolved path could in principle disagree with the directory just locked if the environment changed in between -- ccdad is the program that mutates those variables for per-account scoping.

held.Compromised() is consulted twice. Once, cheaply, right before the write: this is the only check that can PREVENT damage, by refusing to write at all once a takeover is already known. And once implicitly after the write, via held.Release()'s returned error, joined into Activate's own result rather than discarded -- this is what actually catches a takeover in practice, because cclock only notices one on its touch tick (DefaultTouchInterval, 3s): for a fast Activate the pre-write check will rarely have fired, while Release's own synchronous re-stat of each lock directory does not wait for that tick.

Neither check triggers a rollback. With a same-directory atomic rename there is no partially-written state to restore, and if Claude Code wrote after us, a blind restore would clobber ITS write instead of preventing damage. This is what satisfies the rollback rule -- on any failure once the write has begun, restore from the pre-write snapshot -- for a compromise: the rule is vacuous here, because the one case with lingering state to worry about is exactly the case a restore would make worse. The caller gets the error and should re-read and verify rather than assume either side's state.

Activate does not itself surface unrecognized top-level keys (the unknown-key probe). That is deferred to the CLI layer: it already holds the live Blob via Load and can call UnknownKeys directly, without widening this function's signature for every caller that does not need the result.

func ActivateAgainst added in v0.29.1

func ActivateAgainst(writes StoreWrites, decide func(live Blob, stores LoginStores) (Blob, error)) error

ActivateAgainst is ActivateWith for a decision that also needs each store on its own: decide is handed the merge base, as ActivateWith's is, and the item and the file as they were read under the same locks. Whether a login is already where it should be is a question about BOTH stores -- the item can name the target while the file names someone else, which is the split a timed-out keychain write leaves -- and the merge base alone answers it about the item. The rules ActivateWith lists for decide hold here unchanged.

func ActivateWith

func ActivateWith(decide func(live Blob) (Blob, error)) error

ActivateWith is Activate for a caller whose decision is only sound against the file as it is at the moment of the write.

Activate re-reads under the lock too, but only to build its merge base: by the time it has the locks it has already committed to writing. An UNATTENDED executor cannot commit that early. Between the engine reading the live login and the swap landing, the user may have run `ccdad switch` by hand or logged in through Claude Code, and a daemon that goes ahead overwrites a choice a human made seconds ago. decide runs under the three credential locks with the live file as it is, and returns ErrNoChange to stand down.

Two rules decide inherits, neither of which this function can enforce:

  • It runs with Claude Code's refresh locks held, so it must not make a network call, refresh a token, or fetch usage. cclock says why: Claude Code's own refresh blocks on these, so anything slow here stalls the user's session.
  • It must not take ccdad's store lock. store/lock.go documents the store lock as the OUTER one, and a store mutation inside a credential lock is the opposite order -- two callers that pick opposite orders deadlock. Reading a credential blob the caller already holds is fine; writing is what waits until after this returns.

func ApprovedAPIKeys

func ApprovedAPIKeys(g *GlobalConfig) []string

ApprovedAPIKeys returns the approval values Claude Code will accept from the environment. Entries that are not strings are skipped rather than refused, for the same reason PrimaryAPIKey skips a non-string: Claude Code's own `includes` would never match them.

func ClearLogin

func ClearLogin() error

ClearLogin removes every account-scoped key from the live credentials file, leaving the machine-scoped ones -- MCP logins, this machine's device key -- exactly where they are.

This is Activate with an empty snapshot, and it logs the user out on purpose. It exists for the one target that cannot be installed as a credential record: an API-key account. Claude Code prefers a claudeAiOauth login over its stored primaryApiKey in every configuration (the client binds `anthropicAuthEnabled: BE()`, and BE() only turns off for an ENVIRONMENT key or an apiKeyHelper), so writing the key while a login is sitting in the credentials file activates nothing at all. Removing the login is what makes the key the answer.

Nothing is lost by it: the account whose login is being removed keeps its own stored snapshot in ccdad's store, and switching back reinstalls it.

func ClearPrimaryAPIKey

func ClearPrimaryAPIKey(g *GlobalConfig) bool

ClearPrimaryAPIKey removes the stored key, reporting whether there was one.

The approval entry is deliberately LEFT BEHIND. It is not a credential -- it is twenty characters of a key, and its only effect is that an interactive Claude Code will accept that key from the environment without prompting. Removing it would revoke a consent the USER gave through Claude Code's own prompt, on a key that may still be exported in their shell, and the next `ccdad switch` back would only have to ask for it again.

func ForbidRealSecurityForTest added in v0.29.2

func ForbidRealSecurityForTest()

ForbidRealSecurityForTest makes every later spawn of the real /usr/bin/security in this process panic, so a test that reaches the developer's own keychain fails loudly instead of reading it. It cannot be undone: a test binary that has forbidden the real keychain does not get it back. Production code must never call it.

func IsAccountScoped

func IsAccountScoped(key string) bool

IsAccountScoped reports whether key travels with the login.

func IssuedAfter added in v0.29.2

func IssuedAfter(login, than Blob) bool

IssuedAfter reports whether login was issued after than, by LoginExpiry. Two logins with no expiry are not ordered, and the login in hand wins, which is how adoption behaved before it was ordered at all; an expiry on than beside a login without one keeps than.

func LoadWithSource added in v0.9.4

func LoadWithSource() (Blob, CredentialSource, error)

LoadWithSource is Load, and also says which store answered.

A missing login is (Blob{}, SourceNone, nil): the file half returns an empty Blob for a machine where Claude Code has never logged in, and naming a store for a login that is not there would be a third wrong answer of the same kind.

func LoginExpiry added in v0.29.1

func LoginExpiry(b Blob) (time.Time, bool)

LoginExpiry is when a blob's login expires, and whether it says. It is the evidence of WHICH of two logins was issued later: Claude Code's grants all last as long, so the later expiry is the later issue.

func LoginIdentity added in v0.29.1

func LoginIdentity(b Blob) string

LoginIdentity is the value that says whether two blobs hold the same login: the refresh token, or the access token for a record without one, prefixed by which it is. "" means "cannot identify" and never equals anything.

The refresh token leads because it survives an access-token rotation; the kind prefix keeps an access token stored in one record from matching a refresh token stored in another. switcher.CredentialIdentity is this, under the name its attribution rules are written against.

func OAuthAccountSnapshot added in v0.4.1

func OAuthAccountSnapshot(g *GlobalConfig) (json.RawMessage, bool)

OAuthAccountSnapshot returns the raw oauthAccount value, if the config has one. A present-but-empty or JSON-null value reads as absent: both are states Claude Code's own refresh handler treats as "no cached profile" -- its merge is gated on `S && y.oauthAccount` (2.1.241).

func OAuthAccountUUID added in v0.4.1

func OAuthAccountUUID(raw json.RawMessage) (string, bool)

OAuthAccountUUID reads accountUuid out of a raw oauthAccount value.

func PrimaryAPIKey

func PrimaryAPIKey(g *GlobalConfig) (string, bool)

PrimaryAPIKey is the key stored in ~/.claude.json, if any. A value that is present but not a JSON string reads as absent rather than as an error: it is not a key Claude Code could use either.

func RealSecurityForbidden added in v0.29.2

func RealSecurityForbidden() bool

RealSecurityForbidden reports whether ForbidRealSecurityForTest has run in this process: a test re-executing its own binary asks it of the child, to prove the child cannot reach the real keychain either.

func ResetOAuthAccountIdentity added in v0.4.1

func ResetOAuthAccountIdentity(g *GlobalConfig, id AccountIdentity) error

ResetOAuthAccountIdentity replaces oauthAccount with a MINIMAL object naming only who the account is -- accountUuid, emailAddress, the organization fields ccdad already has from the profile lookup it made when the account was added, and the seat tier.

SEATTIER IS THE ONE FIELD HERE CLAUDE CODE READS TO DECIDE BEHAVIOUR rather than to display. `Zu(){return Xe()==="enterprise"&&dO()==="enterprise_usage_based"}` is its test for a money-metered enterprise seat, and the seat half of it reads this file: `dO(){return Dn()?.seatTier??null}` over `Dn(){return Zt()?k().oauthAccount:void 0}` (2.1.246). claudeAiOauth has no seatTier key -- its eight keys are fixed, see token.go -- so oauthAccount is the only place a switch can put one. Omitting it drops such a seat out of the Opus tier `cE()` grants it beside max and team-5x until Claude Code's own next token refresh repairs the field, which happens no earlier than five minutes before the access token expires.

It deliberately OMITS billingType, accountCreatedAt, subscriptionCreatedAt, and ccOnboardingFlags rather than leaving them at a previous account's values or guessing new ones. Claude Code's own token-refresh handler treats their combined presence as "the cached profile is already complete" and skips re-fetching it entirely -- in 2.1.246 that gate is `oauthAccount.billingType!==void 0 && .accountCreatedAt!==void 0 && .subscriptionCreatedAt!==void 0 && .ccOnboardingFlags!==void 0` together with the credentials file's subscriptionType and rateLimitTier being non-null. Omitting the four is what makes Claude Code fetch the real values itself on its next refresh instead of ccdad forging them. SEATTIER IS NOT IN THAT GATE, so writing it does not suppress the re-fetch -- and the re-fetch, when it comes, sets seatTier from the profile it just read, so ccdad's value is a stand-in until Claude Code measures it again rather than a claim that outlives the evidence.

func RestoreOAuthAccountSnapshot added in v0.4.1

func RestoreOAuthAccountSnapshot(g *GlobalConfig, snapshot json.RawMessage) error

RestoreOAuthAccountSnapshot installs a previously captured oauthAccount object verbatim -- the exact object Claude Code itself last wrote while this account was live, byte-for-byte including every cosmetic field ccdad never asked for (displayName, billingType, the trial and onboarding flags). Nothing ccdad could construct is safer than what Claude Code already wrote.

func SetPrimaryAPIKey

func SetPrimaryAPIKey(g *GlobalConfig, key string) error

SetPrimaryAPIKey installs key as Claude Code's stored API key and adds its approval value, mirroring the pair of writes Claude Code's own API-key login makes in one transaction.

The approval half is not optional and is not the same mechanism as the first. primaryApiKey is what Claude Code falls back to when NOTHING else resolves; the approved list is what makes an exported ANTHROPIC_API_KEY acceptable to an interactive session. `ccdad run` needs the second, and a user who exports the variable by hand needs it too, so both are written together rather than leaving one for a later command to remember.

rejected is materialised as an empty array when absent because Claude Code materialises it: its writer is `{...responses, approved: [...], rejected: responses?.rejected ?? []}`.

func SetSecurityRunnerForTest added in v0.29.2

func SetSecurityRunnerForTest(r SecurityRunner) (restore func())

SetSecurityRunnerForTest makes r run every subcommand in place of the real binary and returns a function restoring the runner it replaced. It is the seam cclinktest plugs its fake keychain into, the way credhome.SetTryLockForTest replaces a lock primitive. Production code must never call it.

func SurvivesRestart added in v0.9.8

func SurvivesRestart(err error) bool

SurvivesRestart reports whether err names a keychain failure a FRESH PROCESS on this machine would hit identically, so replacing the process cannot clear it.

errSecInteractionNotAllowed is that failure, and the reason is the scoping unit. macOS refuses it per AUDIT SESSION, and a child inherits its parent's: the daemon's detach sets SysProcAttr{Setsid: true}, which creates a new POSIX session and changes neither the audit session (au_session) nor the Mach bootstrap namespace -- and those are what Security.framework consults to decide whether it may prompt. So a daemon that replaces itself over this fault gets a successor that fails on its own first tick.

Measured 2026-08-31: three consecutive replacements, each failing 1.1 seconds after it started, and then a chain with no replacements left for a wedge a restart COULD have cleared. The remedy is a restart from a shell that already has the keychain, which is a thing only a person can do.

Every other classification is deliberately absent. A locked keychain that a user unlocks, a timeout, a `security` that exited silently -- a fresh process really might get a different answer to any of those, and claiming otherwise would spend the opposite mistake.

func TempPattern added in v0.8.0

func TempPattern(path string) string

TempPattern names the sibling temp file WriteFileAtomic writes beside path, as a pattern that is simultaneously an os.CreateTemp pattern and a filepath.Glob pattern. daemon.SweepStatusTemps globs it. It is re-exported rather than respelled so the writer and the sweeper cannot drift apart.

func UnknownKeys

func UnknownKeys(b Blob) []string

UnknownKeys returns the top-level keys ccdad does not recognize. Six machine keys appeared after clauth's one-key carry list was written, so drift here is demonstrated rather than hypothetical: warn on it and surface it in --json and in exports.

func UnlockLoginKeychain added in v0.9.10

func UnlockLoginKeychain(ctx context.Context) error

UnlockLoginKeychain runs `security unlock-keychain` against the default keychain with this process's stdio INHERITED.

INHERITING STDIO IS THE WHOLE DESIGN. `security` asks for the password on the TERMINAL -- not through the window server, which is why it works over SSH in a session that could never raise a dialog -- so inheriting stdio sends the password from the user's keyboard into Apple's own binary. ccdad never reads it, never holds it, never writes it anywhere, and never passes `-p`, which is the non-interactive form. It sees an exit code.

That is not a formality. This password opens EVERY secret in the login keychain -- browser logins, wifi, certificates -- and not just the one item ccdad wants. A tool that prompts for it is shaped exactly like a credential stealer, so the prompt on screen has to be verifiably Apple's rather than ccdad's; securityPath being pinned absolute is the other half of that.

THE DEFAULT KEYCHAIN, not a hardcoded path. `security unlock-keychain` with no argument unlocks whatever the user's default is -- login.keychain-db on an ordinary machine, and something else on a machine that has said otherwise.

No timeout is imposed on the context. A person is typing.

func UpdateGlobalConfig

func UpdateGlobalConfig(mutate func(*GlobalConfig) error) error

UpdateGlobalConfig applies mutate to ~/.claude.json under Claude Code's own config lock and writes the result atomically.

The file is read INSIDE the lock, never before it, for the same reason Activate re-reads: whatever was loaded before the wait may be stale by the time the lock is granted, and Claude Code writes this file constantly -- every startup counter, every tip shown, every project entry.

mutate returning an error abandons the write and leaves the file untouched. So does mutate leaving the document byte-identical: a switch that changes nothing must not advance the file's mtime, because Claude Code watches it.

func UpdateGlobalConfigAt added in v0.2.0

func UpdateGlobalConfigAt(configPath string, mutate func(*GlobalConfig) error) (err error)

UpdateGlobalConfigAt is UpdateGlobalConfig against a named config file, for the one caller that has a config home no environment variable in this process points at: a `ccdad run --full-profile` profile.

It reads the path back out of the lock rather than using its argument, so the file that is written and the file that is locked cannot drift apart.

func WorstCaseSwitch added in v0.29.1

func WorstCaseSwitch() time.Duration

WorstCaseSwitch is the longest one switch can still be writing after the intent it records ahead of itself: Claude Code's three credential locks waited for in turn and the keychain spawns under them (lockedKeychainBound); then, for a write that ran out of time, the read-back after the locks are released; and, when that finds the write landed, the second hold that brings the file into line -- the locks again, and one more read of the item. At today's values 2*(3*9 s) + 62 s + 31 s + 31 s is just under three minutes.

It is what an intent written ahead of a switch is given before anybody may conclude the switch did not take effect: younger than this, the write may still land.

func WouldSelfRefresh added in v0.5.0

func WouldSelfRefresh(b Blob, now time.Time) bool

WouldSelfRefresh reports whether Claude Code, handed this credential right now, would spend its refresh token rather than use the access token it carries.

A record with no readable expiry answers FALSE, matching Yfe's own null case. Claude Code does not refresh on a missing expiresAt, so neither may this: answering true would make ccdad refuse to install a hand-written or very old credential that Claude Code is perfectly willing to use, and there is no expiry to refresh it against anyway.

A blob with no claudeAiOauth answers false for the same reason it is not a login: an api-key account has no access token and no expiry, and the swap path that installs one must not be gated on a field it will never have.

func WriteFileAtomic

func WriteFileAtomic(path string, data []byte, perm os.FileMode) error

WriteFileAtomic writes data to path through a sibling temp file and a rename.

The body moved to internal/atomicfile, which is a leaf: a package holding a switch has to be able to take an atomic write without taking the package that reads and rewrites Claude Code's login. The name stayed here because a dozen callers spell it and the move is not their business.

Types

type AccountIdentity added in v0.9.0

type AccountIdentity struct {
	// UUID is accountUuid. Everything else is optional; this is not.
	UUID string
	// Email is emailAddress.
	Email string
	// OrganizationUUID is organizationUuid.
	OrganizationUUID string
	// OrganizationType is organizationType, and it is the RAW wire value
	// (claude_max, claude_enterprise), not the short name. Claude Code writes
	// the raw value here itself; the short name lives in the credentials
	// file's subscriptionType, which is a different field in a different file.
	OrganizationType string
	// RateLimitTier is organizationRateLimitTier.
	RateLimitTier string
	// SeatTier is seat_tier: "enterprise_usage_based" for a money-metered
	// seat, empty for everything else. A pro or max account answers
	// seat_tier null, so empty here means "the wire reported none" and not
	// "ccdad did not look" -- both are written as an ABSENT key, which is
	// what Claude Code's own `??null` already reads as unknown.
	SeatTier string
}

AccountIdentity is what ResetOAuthAccountIdentity writes. It is a struct rather than a run of positional strings because the fields are all strings and three of them are organization-shaped: a caller that transposed SeatTier and RateLimitTier would compile silently and write a literal Claude Code compares by value into a file it trusts, which is the exact class of fault this object exists to prevent.

type Blob

type Blob map[string]json.RawMessage

Blob is the decoded credentials file. Values stay as RawMessage so unknown fields survive a round trip unchanged in value — decoding into typed structs silently drops keys instead: clauth's typed token struct loses refreshTokenExpiresAt, rateLimitTier and clientId on every rewrite, and clientId is required to revoke a token. (The one exception is coworkRemoteDevice's sub-object during Merge, which is decoded and re-encoded to union it per organization; see merge.go.)

func Extract

func Extract(live Blob) Blob

Extract returns the account-scoped subset of live — what ccdad snapshots when it captures an account.

Machine-scoped keys are excluded, with no exception: live is authoritative for machine state, and a snapshot must be safe to carry to another machine, because `export` writes snapshots to a file and `import` can restore them there. Two keys carry a device identity, and only one is machine-scoped:

  • trustedDeviceToken is per device AND per account, and Claude Code's own re-login prune settles the tie by deleting it — so ccdad classifies it with the account, and a snapshot does carry it.
  • coworkRemoteDevice is the stronger form of the same hazard. It holds a P-256 private key minted on THIS machine plus a server-side device registration named after THIS machine's hostname (Claude Code's own device display name is "Claude Code on <hostname> · <platform>") — it is scoped to the machine, not the account. Claude Code's own full logout path proves it: logout deletes the entire credential store and then writes back exactly this one key, because every other key belongs to the account being logged out of and this one does not. Carrying it in a snapshot would let `import` plant one machine's device identity onto another, colliding with that machine's own registration and burning the account's device-registration cap.

func Load

func Load() (Blob, error)

Load reads the login Claude Code is actually authenticating with. A missing one is an empty Blob and no error: that is a machine where Claude Code has never logged in.

ON macOS THAT IS THE KEYCHAIN ITEM WHEN ONE IS THERE. Claude Code assembles its credential store as a keychain-with-plaintext-fallback combinator whose read is

read(a){let o=e.read(a);if(o!==null&&o!==void 0)return o;return t.read(a)||{}}

so an item that exists is the login and the file is a store nothing consults. Reading the file past such an item is a CONFIDENT WRONG ANSWER -- it is what had `ccdad which` naming one account while an hour of work went to another -- and every command that asks who is live asks through here.

LoadKeychainCredentials's own header used to rule the opposite way, that Load must not consult the keychain because 2.1.113 dropped the backend. That premise was measured again and is false; keychain_security.go's Write carries the measurement.

A keychain that cannot be READ is an error rather than a fallback. The fallback is for "there is no item", which is a fact; a locked keychain is an unknown, and answering an unknown with the file is the same confident wrong answer in a quieter form.

func LoadKeychainCredentials

func LoadKeychainCredentials(ctx context.Context) (Blob, bool, error)

LoadKeychainCredentials reads the login a Keychain-era Claude Code would be using on this machine. The second return is false when there is no such item, which is every machine running any Claude Code this project has seen.

Load() CALLS THIS FIRST on macOS, which is the reverse of what this header used to rule. It said Load must not consult the keychain, because "since 2.1.113 the installed Claude Code does not read the item, so a ccdad that did would report a login that Claude Code will never use". The premise is false -- keychain.go's header carries the measurement -- and with it false, the confident wrong answer is the one Load gave by reading the file past an item that exists.

A value that is not JSON is an error rather than an empty blob: `security -w` hex-encodes data it cannot print, so unparseable output means the item is not holding what its name says it holds, and silently reporting "no login" would hide that.

func Merge

func Merge(live, incoming Blob) Blob

Merge produces the credentials file to write when activating an account.

live is the file as it exists right now and is authoritative for everything machine-scoped, including keys ccdad has never heard of. incoming is the target account's stored snapshot, as produced by Extract — the five account-scoped keys only.

An account-scoped key missing from incoming is REMOVED rather than inherited: carrying account A's trustedDeviceToken into a session running as account B presents A's device under B's identity.

coworkRemoteDevice is unioned per organization sub-key rather than replaced wholesale, with live winning on any collision — see unionObjects. This is defence-in-depth, not a path Extract can exercise: Extract deliberately never puts coworkRemoteDevice in a snapshot (see its doc comment), so an incoming blob built by this package from a live file can never carry the key. The union guards against any OTHER source of incoming doing so — a hand-built call, or an export file written by some future version of ccdad — so that even then, a wholesale replace cannot destroy the live machine's other-organization entries.

Neither argument is mutated.

type CredentialSource added in v0.9.4

type CredentialSource int

CredentialSource is WHICH STORE answered. It exists because on macOS "who is logged in" and "where does that come from" are two different questions, and every command that reported the first was naming the second from a constant: `which` said "the Claude Code credentials file" while the keychain item was what it had read, on exactly the machine where the difference was the whole point.

const (
	// SourceNone is no login anywhere.
	SourceNone CredentialSource = iota
	// SourceCredentialsFile is ~/.claude/.credentials.json.
	SourceCredentialsFile
	// SourceKeychainItem is the macOS Keychain item, which Claude Code's
	// credential store reads BEFORE the file.
	SourceKeychainItem
)

func (CredentialSource) String added in v0.9.4

func (s CredentialSource) String() string

String names the store for a person.

It is a NOUN PHRASE and deliberately short, because both readers put it inside a sentence of their own: `which` prints "via <this>" and doctor prints "the login in <this>". Spelling it "the Claude Code credentials file" made the second read "the login in the Claude Code credentials file", which says Claude Code twice and reads like a different file from the one meant.

type GlobalConfig

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

GlobalConfig is a decoded ~/.claude.json that remembers its key order.

Values stay as RawMessage for the same reason Blob's do: everything ccdad does not understand has to survive a round trip byte-identical.

func LoadGlobalConfig

func LoadGlobalConfig() (*GlobalConfig, error)

LoadGlobalConfig reads ~/.claude.json. A missing file is an empty document and no error: that is a machine Claude Code has never been configured on.

func LoadGlobalConfigAt added in v0.2.0

func LoadGlobalConfigAt(path string) (*GlobalConfig, error)

LoadGlobalConfigAt reads a named global config -- the `ccdad run --full-profile` profile's own, which no environment variable in THIS process points at.

func NewGlobalConfig

func NewGlobalConfig() *GlobalConfig

NewGlobalConfig returns an empty document, which is what a machine with no ~/.claude.json has.

func (*GlobalConfig) Delete

func (g *GlobalConfig) Delete(key string) bool

Delete removes a top-level key, reporting whether it was there.

func (*GlobalConfig) Get

func (g *GlobalConfig) Get(key string) (json.RawMessage, bool)

Get returns a top-level value.

func (*GlobalConfig) Keys

func (g *GlobalConfig) Keys() []string

Keys returns the top-level keys in file order.

func (*GlobalConfig) Set

func (g *GlobalConfig) Set(key string, value json.RawMessage)

Set writes a top-level value. An existing key keeps its position and a new one is appended, which is what JavaScript's `{...config, key: value}` does and therefore what Claude Code's own writes do.

type KeychainError

type KeychainError struct {
	// Op is the security subcommand that failed.
	Op string
	// contains filtered or unexported fields
}

KeychainError is a `security` invocation that did not answer: not "the item is not there", which is an answer, but "ccdad could not find out".

A probe that could not answer is not an absence, the same rule daemon status follows one layer up. A keychain that is locked and a keychain with nothing in it produce the same silence, and treating the first as the second reports a machine as clean while a stale credential sits on it.

func (*KeychainError) Detail

func (e *KeychainError) Detail() string

Detail is the sentence a diagnostic prints. Every failure has its own, so a report says what the user should do next rather than only that something went wrong.

The silent failure gets its sentence built here rather than in the table, because the exit code IS the sentence: without it the report is "it failed", which is what the caller already knew.

func (*KeychainError) Error

func (e *KeychainError) Error() string

type KeychainItem

type KeychainItem struct {
	Service string
	Account string
}

KeychainItem names one generic-password item: the two attributes that identify it to `security`, and the only two ccdad ever needs to spell.

func CredentialKeychainItem

func CredentialKeychainItem() KeychainItem

CredentialKeychainItem is the name a CURRENT Claude Code's rules would give the item -- the first candidate. Callers that intend to find an item that exists want CredentialKeychainItems instead.

func CredentialKeychainItems added in v0.3.0

func CredentialKeychainItems() []KeychainItem

CredentialKeychainItems is every name this machine's legacy OAuth item could carry, most recent spelling first.

There is more than one because Claude Code changed how it hashed CLAUDE_CONFIG_DIR mid-era: 2.1.38 and later normalize the value to NFC before hashing, 1.0.30 through 2.1.37 hash the bytes as they came. A decomposed value therefore names TWO different items depending on which build wrote it, and probing only one of them is the same false "no legacy item" this derivation was corrected to stop producing. They coincide -- one candidate -- whenever CLAUDE_CONFIG_DIR is unset or already composed, which is every ordinary machine.

The older eras are deliberately NOT candidates, and not merely because each is another spawn. Before ~1.0.30 there was no hash at all and before 1.0.128 no OAUTH_FILE_SUFFIX, so their names are the UNSUFFIXED ones -- which on a machine that sets CLAUDE_CONFIG_DIR or CLAUDE_CODE_CUSTOM_OAUTH_URL belong to a different profile's login, not to this one. Probing them would report, and invite deleting, somebody else's item. The NFC pair is the only split where both spellings name the SAME logical item.

It is a derivation, not a probe: it says what the items WOULD be called, and says nothing about whether any exists. Nothing here touches the filesystem or spawns anything, so it is safe to call on any platform and in any state.

func LiveKeychainItem added in v0.9.8

func LiveKeychainItem(env []string) KeychainItem

LiveKeychainItem is the credential item a CURRENT Claude Code, launched with env, reads and writes.

IT IS A SECOND DERIVATION AND THAT IS THE POINT. CredentialKeychainItems names an item a <=2.1.112 build could have LEFT BEHIND, and no such build had heard of CLAUDE_SECURESTORAGE_CONFIG_DIR, so reading that variable there names an item which cannot exist -- keychainServiceName's header says so. This one answers the opposite question: which item is the INSTALLED build using right now, in THIS environment. The two agree on a machine that exports neither variable, which is why the difference stayed invisible until a scoped session needed it.

Measured verbatim in 2.1.251, in the credential-store chunk:

var s5="-credentials";
function a0(n=""){let e=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,
  t=e!==void 0?!e:!process.env.CLAUDE_CONFIG_DIR,
  r=e!==void 0?e.normalize("NFC"):be(),
  c=t?"":`-${a("sha256").update(r).digest("hex").substring(0,8)}`;
  return `Claude Code${zt().OAUTH_FILE_SUFFIX}${n}${c}`}

So CLAUDE_SECURESTORAGE_CONFIG_DIR OUTRANKS CLAUDE_CONFIG_DIR here, and the test on the winner is DEFINEDNESS, not truthiness: a defined-but-empty value selects the unsuffixed item, exactly as an unset CLAUDE_CONFIG_DIR does. The hashed string is the variable's own NFC-normalized value, not a resolved or symlink-followed form of it.

Every `ccdad run` session and every probe exports a real directory into that variable, so their item always carries a suffix and can never collide with the machine's own login. That is the property adoptBack depends on.

func (KeychainItem) Delete

func (it KeychainItem) Delete(ctx context.Context) error

Delete removes the item. An item that was already absent is success: the caller asked for a state, not for an event.

ONE CALLER, AND THE RULING BELOW IS ABOUT A DIFFERENT SUBJECT. removeSession deletes the item a `ccdad run` session or a probe created under its OWN scoped credential root -- an ephemeral store ccdad made, whose directory is being deleted in the same breath, and whose login has just been carried into the account's snapshot. Nothing about that is the machine's login.

DELETING THE MACHINE'S OWN ITEM DURING A SWITCH is what the ruling refuses, and it still does. The fact it waited on is settled -- <=2.1.112 reads the keychain and FALLS BACK to the credentials file, so the delete redirects rather than logs out -- and the measurement then supplied three reasons not to ship it anyway:

  • 2.1.113 dropped the backend, so on every Claude Code a user can install today the item is inert. The spawn would buy nothing while sitting inside the credential-lock window of every macOS switch.
  • Where it is NOT inert, the item is that Claude Code's live login, so deleting it unasked is "destroying a credential on every switch" -- the highest-rated risk this tool carries -- with a different subject. Making it safe needs the item READ and attributed against the store first -- a second spawn, and one that decrypts.
  • AND IT WOULD NOT EVEN WORK THERE. From 1.0.36 the combinator's update() deletes the credentials file whenever the pre-write keychain read came back empty, so the next token refresh after a delete recreates the item AND unlinks the file ccdad had just redirected Claude Code to. A switch that repairs a machine for a few hours and then costs it the file is not a repair. On such a machine the fix is upgrading Claude Code.

doctor names the item, hands over the command, and says which of those two machines the command is for.

func (KeychainItem) Present

func (it KeychainItem) Present(ctx context.Context) (bool, error)

Present reports whether the item exists, WITHOUT decrypting it.

The lookup deliberately omits -w. `find-generic-password` without it returns only the item's attributes, which needs no access to the secret and therefore can never raise the "wants to use your keychain" dialog -- not even for an item another application owns. A diagnostic that popped an auth prompt on someone's machine would be a worse bug than the drift it was looking for.

func (KeychainItem) Read

func (it KeychainItem) Read(ctx context.Context) (string, bool, error)

Read returns the secret stored in the item, and whether there was one.

The argument order is Claude Code's own, -w between the account and the service, so a process listing on a machine running both shows the same shape.

func (KeychainItem) Write added in v0.9.2

func (it KeychainItem) Write(ctx context.Context, secret string) error

Write installs secret into the item, creating it or replacing whatever is there.

WHY ccdad WRITES THE KEYCHAIN AT ALL, given that the header of keychain.go spent its length arguing ccdad should not touch it: because the premise that argument rested on -- that 2.1.113 dropped the backend, so the item is inert on anything a user can install today -- is FALSE. Measured against the installed 2.1.234, 2.1.238 and 2.1.251, every one of them carries a whole keychain backend that spawns `security find-generic-password`, and the combinator still reads it BEFORE the credentials file:

read(a){let o=e.read(a);if(o!==null&&o!==void 0)return o;return t.read(a)||{}}

So on macOS the item is the live login, and a switch that writes only .credentials.json writes the store Claude Code consults SECOND. It appears to work -- the file changes, `which` reads it back, the daemon logs a switch -- and Claude Code goes on authenticating as whoever the item names. That was observed, not deduced: with the item holding one account and the file another, an hour of work after a switch landed entirely on the item's account.

-U is what makes this an install rather than a create: without it `security` refuses an item that already exists with errSecDuplicateItem, which is the ordinary case here -- the item is nearly always already there.

THE SECRET GOES ON ARGV, and that is a real cost rather than an oversight. -X takes the payload as hex, and hex is what makes `security` store the bytes rather than interpret them; the alternative is -w, which takes the same plaintext on the same argv. Both are visible in a process listing for the life of the spawn. Claude Code's own writer passes -X the same way and only falls back from stdin to argv past a length limit, so ccdad is not opening an exposure Claude Code closes -- but it is opening one on every switch rather than on an occasional oversized payload. Narrowing it needs `security -i`, which is an interactive command stream rather than a flag, and runSecurity deliberately pins Stdin to DevNull so that a subcommand which decides to prompt cannot compete for the terminal. Changing that is a bigger change than this one and it is not free either.

type KeychainLookup added in v0.3.0

type KeychainLookup struct {
	// Present is whether one of the candidate names is on the keychain.
	Present bool

	// Item is the candidate that was found, or the first one when none was.
	Item KeychainItem

	// Checked is every name that was looked for, in order. A report that says
	// "nothing there" has to be able to say what it looked for, and on a
	// decomposed CLAUDE_CONFIG_DIR that is two names rather than one.
	Checked []KeychainItem
}

KeychainLookup is what a probe for the legacy credential item found.

func ProbeCredentialKeychainItem added in v0.3.0

func ProbeCredentialKeychainItem(ctx context.Context) (KeychainLookup, error)

ProbeCredentialKeychainItem is the doctor probe: derive the names this environment's item could carry and ask whether any of them is there, without decrypting anything.

The candidates are tried in order and the FIRST hit wins, so a machine that somehow has both spellings is reported as the newer one -- which is the one a Claude Code new enough to have written both would read. A probe that fails is returned as an error rather than continued past: "the keychain is locked" is not "the item is not under this name", and answering the second question with the first is the mistake this whole check exists to avoid.

type LoginStores added in v0.29.1

type LoginStores struct {
	// Item is the keychain item's login, valid when HasItem. Off macOS, and on
	// a Mac with no item, HasItem is false: the file is then the only store.
	Item    Blob
	HasItem bool
	// File is the credentials file's login. FileErr is why it could not be
	// read; with an item present that is not a failure of the whole read,
	// because Claude Code reads the item first.
	File    Blob
	FileErr error
}

LoginStores is what each of Claude Code's two login stores holds, read separately.

Load answers "who is logged in" and stops at the first store that has an answer, because that is how Claude Code's combinator reads. That is the right question for most callers and the wrong one for a machine whose stores DISAGREE: the item names one account, the file names another, and Load reports the item and nothing else. On 2026-11-10 that was the state a timed-out keychain write left behind, and every ccdad command that asked through Load saw a machine that looked switched while Claude Code -- which falls back to the file whenever its own keychain read fails, as it does on a loaded Mac -- went on spending the other account. Telling the two apart needs both answers.

func ReadLoginStores added in v0.29.1

func ReadLoginStores() (LoginStores, error)

ReadLoginStores reads both stores: the item with the LOOKUP bound, the file at the path Claude Code would read.

The error is for an item that could not be read, and it is the only error: a locked keychain is an unknown about the store Claude Code reads first, and nothing about the file can stand in for it. A file that cannot be read is carried in FileErr, so a caller that only wants Live gets exactly what Load gave it. With the error the LoginStores is the zero value, which holds no login: no evidence of anything, which is what store.Account.StoredLoginSpent is to be handed when the read failed.

func (LoginStores) Live added in v0.29.1

func (l LoginStores) Live() (Blob, CredentialSource, error)

Live is the login Claude Code reads first, and which store that is: the item when there is one, the file otherwise. It is Load's answer, from the same read.

func (LoginStores) Logins added in v0.29.2

func (l LoginStores) Logins() []Blob

Logins is the login each store that could be read holds: the item's when there is one, and the file's unless it could not be read.

type SecurityAnswer added in v0.29.2

type SecurityAnswer struct {
	Stdout string
	Stderr string
	Code   int
}

SecurityAnswer is what one `security` subcommand answered: what it printed and the status it exited with. A non-zero Code is carried here rather than as an error, because callers decide which codes mean what -- 44 is "the item is not there", which is an answer.

type SecurityRunner added in v0.29.2

type SecurityRunner func(ctx context.Context, args ...string) (SecurityAnswer, error)

SecurityRunner runs one `security` subcommand and returns its answer. ctx carries the subcommand's deadline; a runner that gives up because that deadline passed returns an error wrapping context.DeadlineExceeded, and that is the only way a write that ran out of time is told apart from one that answered.

The real runner is spawnSecurity. The only other one is the in-memory item in internal/cclink/cclinktest, which replaces the exec layer whole so that every line ABOVE it -- the bounds, the read-back of an unconfirmed write, the item-first order -- runs in another package's test as it does on a Mac.

type StoreWrites added in v0.29.1

type StoreWrites uint8

StoreWrites says which login stores a write touches.

const (
	// WriteChanged writes only a store whose login differs from the one being
	// installed, by LoginIdentity. Repairing a split installs an account one
	// store already holds, and on the machine that needs the repair the
	// keychain is the slow part: rewriting an item that already holds the
	// login spends up to two bounded spawns -- the write and its read-back --
	// to change nothing, and a read-back that cannot answer would fail a repair
	// that never needed the keychain at all.
	WriteChanged StoreWrites = iota
	// WriteAll writes every store whatever it holds. It is `--force`: a person
	// asked for the stored login to be put back over whatever the stores hold,
	// the same grant included.
	WriteAll
)

type TokenRecord

type TokenRecord struct {
	// Kind is "api-key" or "setup-token".
	Kind  string `json:"kind"`
	Token string `json:"token"`
}

TokenRecord is what TokenKey holds.

func TokenRecordOf

func TokenRecordOf(b Blob) (TokenRecord, bool)

TokenRecordOf reports the ccdad token record a blob carries, if any.

A malformed record reads as absent rather than as an error. The callers are all asking a classification question — is this account a token account? — and there is no answer to give a corrupt record other than "not one this can install", which is what absent already means.

Directories

Path Synopsis
Package cclinktest is an in-memory macOS Keychain item for tests in other packages, the way net/http/httptest is a server for them.
Package cclinktest is an in-memory macOS Keychain item for tests in other packages, the way net/http/httptest is a server for them.

Jump to

Keyboard shortcuts

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