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
- Variables
- func APIKeyApproval(key string) string
- func Activate(incoming Blob) error
- func ActivateWith(decide func(live Blob) (Blob, error)) error
- func ApprovedAPIKeys(g *GlobalConfig) []string
- func ClearLogin() error
- func ClearPrimaryAPIKey(g *GlobalConfig) bool
- func IsAccountScoped(key string) bool
- func LoadWithSource() (Blob, CredentialSource, error)
- func OAuthAccountSnapshot(g *GlobalConfig) (json.RawMessage, bool)
- func OAuthAccountUUID(raw json.RawMessage) (string, bool)
- func PrimaryAPIKey(g *GlobalConfig) (string, bool)
- func ResetOAuthAccountIdentity(g *GlobalConfig, id AccountIdentity) error
- func RestoreOAuthAccountSnapshot(g *GlobalConfig, snapshot json.RawMessage) error
- func SetPrimaryAPIKey(g *GlobalConfig, key string) error
- func TempPattern(path string) string
- func UnknownKeys(b Blob) []string
- func UpdateGlobalConfig(mutate func(*GlobalConfig) error) error
- func UpdateGlobalConfigAt(configPath string, mutate func(*GlobalConfig) error) (err error)
- func WouldSelfRefresh(b Blob, now time.Time) bool
- func WriteFileAtomic(path string, data []byte, perm os.FileMode) error
- type AccountIdentity
- type Blob
- type CredentialSource
- type GlobalConfig
- type KeychainError
- type KeychainItem
- type KeychainLookup
- type TokenRecord
Constants ¶
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.
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.
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 ¶
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") )
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.
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.
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".
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.
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.
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 ¶
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 ¶
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 ActivateWith ¶
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 IsAccountScoped ¶
IsAccountScoped reports whether key travels with the login.
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 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 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 TempPattern ¶ added in v0.8.0
TempPattern returns the name of the sibling temp file WriteFileAtomic writes beside path, as a pattern.
The returned string is simultaneously an os.CreateTemp pattern and a filepath.Glob pattern — both read `*` as "the part that varies" — and that is the whole point of exporting it. A rename that never completed strands the temp file, and whatever collects those orphans has to name them; daemon.SweepStatusTemps is the one that does. Deriving its glob from here rather than spelling the suffix a second time is what stops the writer and the sweeper from drifting apart. They were two literals under a comment claiming they were one, nothing executed that claim, and changing the writer's left the whole suite green with the sweep collecting nothing.
It takes the full path rather than a base name so a caller cannot hand it the wrong half; only the base is used, so the result names one directory entry and never contains a separator.
The two readings part company for a base name holding a glob metacharacter — `*`, `?`, `[` — which os.CreateTemp takes literally and filepath.Match does not. Nothing sweeps such a file: the only sweeper names its files with constants, and the two callers that take a path from the user (`export --out`, `runway --out`) have no sweeper at all.
func UnknownKeys ¶
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 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 WouldSelfRefresh ¶ added in v0.5.0
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 ¶
WriteFileAtomic writes data to path via a sibling temp file and a rename.
The temp file MUST be a sibling: a rename within one directory is atomic, so a concurrent reader sees either the whole old file or the whole new one. Writing to the system temp directory and moving across filesystems degrades to copy-then-unlink, where a reader can catch a half-written credential file.
The rename also changes the inode and advances the mtime, which is exactly what Claude Code's change probe watches, so a switch hot-reloads a running session with no restart.
On Windows an antivirus scanner or the search indexer may hold the target file open when the rename is attempted; that is retried per winerr.Retryable. If the temp file itself is still held after every retry, it can survive as an orphan — accepted here, since guarding against it needs a second retry loop for a rarer failure than the one this function already handles. An orphan is named by TempPattern, which is what a sweeper globs.
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 ¶
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 ¶
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 ¶
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 ¶
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.
func (*KeychainError) Error ¶
func (e *KeychainError) Error() string
type KeychainItem ¶
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 (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.
NOTHING IN ccdad CALLS THIS, and that is now a ruling rather than a gap. Deleting the item during a switch was the proposed use. 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 ¶
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 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.