Documentation
¶
Overview ¶
Package auth handles credential storage and OAuth flows for AI providers.
Credentials are stored in ~/.config/moa/auth.json with mode 0600. Supports both API keys and OAuth tokens (Claude Max).
Index ¶
- Constants
- Variables
- func DefaultStorePath() string
- func IsOAuthToken(key string) bool
- func MCPOAuthKey(rawURL string) string
- func OpenBrowser(url string)
- type AnthropicBackupSelection
- type AnthropicBackupStatus
- type BackupRevision
- type CodeAttempt
- type Credential
- type CredentialSnapshot
- type LoginAttemptView
- type LoginError
- type LoginProgress
- type MCPOAuthRecord
- type MCPOAuthStore
- func (s *MCPOAuthStore) Begin(ctx context.Context, serverURL string) (string, error)
- func (s *MCPOAuthStore) Complete(ctx context.Context, serverURL, pastedURL string) error
- func (s *MCPOAuthStore) Has(key string) (exists, needsReauth bool)
- func (s *MCPOAuthStore) RefreshIfCurrent(ctx context.Context, key, rejectedAccess string) error
- func (s *MCPOAuthStore) SignOut(ctx context.Context, serverURL string) error
- func (s *MCPOAuthStore) SignedOut(key string) bool
- func (s *MCPOAuthStore) Subscribe(fn func(key string)) (unsubscribe func())
- func (s *MCPOAuthStore) SubscribeSignOut(fn func(key string)) (unsubscribe func())
- func (s *MCPOAuthStore) Token(ctx context.Context, key string) (*oauth2.Token, error)
- type MetaCredentials
- type MetaDeviceCode
- type OAuthCredentials
- func CompleteAnthropic(ctx context.Context, a *CodeAttempt, input string) (*OAuthCredentials, error)
- func CompleteOpenAI(ctx context.Context, a *CodeAttempt, input string) (*OAuthCredentials, error)
- func CompleteXAIDeviceFlow(ctx context.Context, client *http.Client, _ XAIEndpoints, ...) (*OAuthCredentials, error)
- func LoginAnthropic(openURL func(string), promptCode func() (string, error)) (*OAuthCredentials, error)
- func LoginOpenAI(openURL func(string), promptCode func() (string, error)) (*OAuthCredentials, error)
- func LoginXAI(ctx context.Context, openURL func(string), display func(*XAIDeviceCode)) (*OAuthCredentials, error)
- func RefreshAnthropicToken(refreshToken string) (*OAuthCredentials, error)
- func RefreshOpenAIToken(refreshToken string) (*OAuthCredentials, error)
- func RefreshXAIToken(refreshToken string) (*OAuthCredentials, error)
- type ProviderLoginManager
- func (m *ProviderLoginManager) Begin(ctx context.Context, provider, browserBinding, expectedGeneration string) (LoginAttemptView, error)
- func (m *ProviderLoginManager) Cancel(provider, attemptID, browserBinding string) error
- func (m *ProviderLoginManager) Close()
- func (m *ProviderLoginManager) Complete(ctx context.Context, provider, attemptID, browserBinding, input string) error
- func (m *ProviderLoginManager) Progress(provider, attemptID, browserBinding string) (LoginProgress, error)
- func (m *ProviderLoginManager) SaveAPIKey(provider, expectedGeneration, key string) (string, error)
- type ProviderStatus
- type Store
- func (s *Store) AdmitAnthropicBackup(ctx context.Context, expected BackupRevision, ...) error
- func (s *Store) AdmitSnapshot(ctx context.Context, expected CredentialSnapshot, ...) error
- func (s *Store) AnthropicBackupStatus() (AnthropicBackupStatus, error)
- func (s *Store) CommitLogin(provider, expectedGeneration string, cred Credential) (string, error)
- func (s *Store) CredentialKind(provider string) string
- func (s *Store) Get(provider string) (Credential, bool)
- func (s *Store) GetAPIKey(provider string) (key string, isOAuth bool, err error)
- func (s *Store) GetAccountID(provider string) string
- func (s *Store) LoadError() error
- func (s *Store) PeekOAuthToken(provider string) (token string, isOAuth, valid bool)
- func (s *Store) PeekSnapshot(provider string) (CredentialSnapshot, error)
- func (s *Store) ProviderStatus(provider string) ProviderStatus
- func (s *Store) RecordAnthropicBackupUse(revision BackupRevision, err error)
- func (s *Store) RecordUse(snap CredentialSnapshot, err error)
- func (s *Store) RefreshOAuthIfGeneration(ctx context.Context, snap CredentialSnapshot, rejected string) (CredentialSnapshot, error)
- func (s *Store) Remove(provider string) error
- func (s *Store) RemoveAnthropicAPIKey(expectedKey string) error
- func (s *Store) ResolveSnapshot(ctx context.Context, provider string) (CredentialSnapshot, error)
- func (s *Store) RetrySave(provider string) error
- func (s *Store) SaveAnthropicAPIKey(expectedPrimary, key string) (string, error)
- func (s *Store) Set(provider string, cred Credential) error
- func (s *Store) StoredGeneration(provider string) (string, error)
- type XAIDeviceCode
- type XAIEndpoints
Constants ¶
const ( LoginUnsupported = "unsupported" LoginEnvManaged = "env_managed" LoginInvalidInput = "invalid_input" LoginMismatch = "mismatch" LoginNotFound = "not_found" LoginExpired = "expired" LoginDenied = "denied" LoginCanceled = "canceled" LoginSuperseded = "superseded" LoginInvalidKey = "invalid_key" LoginNotAPIKey = "not_api_key" )
Login error classes. Each maps to fixed copy that says what to do next; none carries user input or provider text.
const ( StatusMissing = "missing" StatusSaved = "saved" StatusReady = "ready" StatusRenewOnUse = "renew_on_use" StatusReconnect = "reconnect" StatusKeyRejected = "key_rejected" StatusTemporary = "temporary" StatusSaveFailed = "save_failed" )
Provider status states, as shown in Settings → Providers.
Variables ¶
var ( // ErrMCPOAuthNoPending means a pasted callback URL does not belong to an // in-flight authorization of this server (wrong/unknown/expired/used // state, wrong redirect target, or wrong issuer). ErrMCPOAuthNoPending = errors.New("that link doesn't match an authorization in progress for this server") // ErrMCPOAuthDenied means the authorization server returned an error // instead of a code (typically the user declined). ErrMCPOAuthDenied = errors.New("authorization was denied") )
var ErrMCPAuthRequired = errors.New("sign-in required")
ErrMCPAuthRequired means the MCP server needs the user to (re)authorize: there is no usable token and no way to get one without a human.
Functions ¶
func DefaultStorePath ¶
func DefaultStorePath() string
DefaultStorePath returns the default path for the auth store, or "" when no config directory can be resolved.
func IsOAuthToken ¶
IsOAuthToken returns true if the given key looks like an OAuth token rather than a standard API key. Detects Anthropic OAuth (sk-ant-oat) and JWT tokens (three dot-separated segments, as used by OpenAI OAuth).
func MCPOAuthKey ¶ added in v0.41.0
MCPOAuthKey normalizes a server URL into the key its tokens are stored under, so trivially different spellings of one endpoint share credentials.
Types ¶
type AnthropicBackupSelection ¶ added in v0.46.0
type AnthropicBackupSelection struct {
Snapshot CredentialSnapshot `json:"-"`
Revision BackupRevision
}
type AnthropicBackupStatus ¶ added in v0.46.0
type AnthropicBackupStatus struct {
Revision BackupRevision `json:"revision"`
Configured bool `json:"configured"`
Active bool `json:"active"`
State string `json:"state"`
}
AnthropicBackupStatus describes the API key stored next to the plan sign-in. Active means it is used once the plan reports a 5h or weekly limit: storing the key is the whole consent, there is no separate switch.
type BackupRevision ¶ added in v0.46.0
type BackupRevision struct {
Primary string `json:"primary_generation"`
Key string `json:"key_generation"`
}
BackupRevision is a secret-free CAS tuple, not a credential or a capability.
type CodeAttempt ¶ added in v0.46.0
type CodeAttempt struct {
// contains filtered or unexported fields
}
CodeAttempt is one authorization-code sign-in in progress (Anthropic or OpenAI). It holds the PKCE verifier, so it only lives in server memory: its fields are unexported, it has no JSON form, and only the authorize URL (state and challenge, never the verifier) is meant for the browser.
func BeginAnthropic ¶ added in v0.46.0
func BeginAnthropic() (*CodeAttempt, error)
BeginAnthropic starts an Anthropic sign-in. Nothing listens anywhere: the user approves in a browser and pastes back the code#state Anthropic shows, or the callback URL.
func BeginOpenAI ¶ added in v0.46.0
func BeginOpenAI() (*CodeAttempt, error)
BeginOpenAI starts an OpenAI sign-in. The browser ends on http://localhost:1455/auth/callback; that full URL is what gets pasted back, whether or not anything listens there.
func (*CodeAttempt) AuthorizeURL ¶ added in v0.46.0
func (a *CodeAttempt) AuthorizeURL() string
AuthorizeURL is the provider page the user opens to approve the sign-in.
func (*CodeAttempt) Deadline ¶ added in v0.46.0
func (a *CodeAttempt) Deadline() time.Time
Deadline is when the attempt stops being completable.
type Credential ¶
type Credential struct {
Type string `json:"type"` // "api_key" or "oauth"
Key string `json:"key,omitempty"` // API key (type=api_key), or a key minted from an OAuth session (Meta)
Access string `json:"access,omitempty"` // OAuth access token (type=oauth)
Refresh string `json:"refresh,omitempty"` // OAuth refresh token (type=oauth)
Expires int64 `json:"expires,omitempty"` // OAuth token expiry (unix ms) (type=oauth)
AccountID string `json:"account_id,omitempty"` // Provider-specific account ID (e.g., OpenAI chatgpt_account_id)
// Generation identifies one login or key replacement. OAuth rotation keeps
// it, so a request can tell "same login, newer token" from "another login".
Generation string `json:"generation,omitempty"`
// contains filtered or unexported fields
}
Credential represents a stored credential for a provider.
func (Credential) MarshalJSON ¶ added in v0.46.0
func (c Credential) MarshalJSON() ([]byte, error)
MarshalJSON writes the known fields plus any unknown ones read from disk.
func (*Credential) UnmarshalJSON ¶ added in v0.46.0
func (c *Credential) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes one provider record strictly, keeping unknown fields.
type CredentialSnapshot ¶ added in v0.46.0
type CredentialSnapshot struct {
Provider string
Source string // core.CredentialSourceEnv or core.CredentialSourceStore
Kind string // "api_key" or "oauth"
// Credential is the stored record, or a synthetic one for the environment.
Credential Credential `json:"-"`
// Token is the value the provider API accepts (access token, key or Meta
// minted key).
Token string `json:"-"`
AccountID string
Generation string // "" for environment and legacy records
}
CredentialSnapshot is one coherent credential selection: source, kind, credential, account and generation read together, so a request never mixes the token of one login with the account or transport of another. It holds secrets and is server-side only; never serialize it.
type LoginAttemptView ¶ added in v0.46.0
type LoginAttemptView struct {
Provider string `json:"provider"`
Flow string `json:"flow"` // paste_code_state, paste_url or device
AttemptID string `json:"attempt_id"`
AuthorizeURL string `json:"authorize_url,omitempty"`
UserCode string `json:"user_code,omitempty"`
VerificationURI string `json:"verification_uri,omitempty"`
VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
State string `json:"state,omitempty"`
}
LoginAttemptView is what Begin returns to the browser that started the sign-in. It never holds the verifier, device code or any token.
type LoginError ¶ added in v0.46.0
LoginError is a sign-in or key-entry failure that is safe to show.
func (*LoginError) Error ¶ added in v0.46.0
func (e *LoginError) Error() string
type LoginProgress ¶ added in v0.46.0
type LoginProgress struct {
Provider string `json:"provider"`
State string `json:"state"`
ExpiresAt time.Time `json:"expires_at"`
ErrorClass string `json:"error_class,omitempty"`
}
LoginProgress is the state of one attempt. ErrorClass is a LoginError or core credential class, never provider text.
type MCPOAuthRecord ¶ added in v0.41.0
type MCPOAuthRecord struct {
ServerURL string `json:"server_url"`
Resource string `json:"resource,omitempty"`
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
AuthStyle int `json:"auth_style"`
RedirectURI string `json:"redirect_uri"`
Scopes []string `json:"scopes,omitempty"`
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
TokenType string `json:"token_type,omitempty"`
// ExpiresAt is the access token expiry in unix ms; 0 means unknown.
ExpiresAt int64 `json:"expires_at"`
// ObtainedAt is when the current access token was issued (unix ms).
ObtainedAt int64 `json:"obtained_at"`
NeedsReauth bool `json:"needs_reauth,omitempty"`
// SignedOut prevents a configured static Authorization header from
// reactivating this server after the user explicitly signed out.
SignedOut bool `json:"signed_out,omitempty"`
}
MCPOAuthRecord is the persisted OAuth state of one remote MCP server.
type MCPOAuthStore ¶ added in v0.41.0
type MCPOAuthStore struct {
// contains filtered or unexported fields
}
MCPOAuthStore persists OAuth tokens for remote MCP servers and runs the authorization flow. One instance exists per file path in the process (see MCPOAuthStoreAt) so every session's MCP manager shares its refresh single-flight and change notifications.
func DefaultMCPOAuthStore ¶ added in v0.41.0
func DefaultMCPOAuthStore() *MCPOAuthStore
DefaultMCPOAuthStore returns the store at <config dir>/mcp-oauth.json.
func MCPOAuthStoreAt ¶ added in v0.41.0
func MCPOAuthStoreAt(path string) *MCPOAuthStore
MCPOAuthStoreAt returns the process-wide store for path, creating and loading it on first use. An empty path yields a store that holds nothing and refuses to save, rather than writing tokens relative to the cwd.
func (*MCPOAuthStore) Begin ¶ added in v0.41.0
Begin discovers the server's authorization server, registers a fresh client and returns the URL the user must open. Nothing listens on the loopback redirect: the browser fails to load it and the user pastes that URL into Complete, which works the same when moa runs on another machine.
func (*MCPOAuthStore) Complete ¶ added in v0.41.0
func (s *MCPOAuthStore) Complete(ctx context.Context, serverURL, pastedURL string) error
Complete finishes the authorization Begin started for serverURL, from the URL the browser was redirected to. On success the tokens are stored and subscribers are notified.
func (*MCPOAuthStore) Has ¶ added in v0.41.0
func (s *MCPOAuthStore) Has(key string) (exists, needsReauth bool)
Has reports whether a record exists for key and whether it is waiting for the user to sign in again. It never touches the network.
func (*MCPOAuthStore) RefreshIfCurrent ¶ added in v0.41.0
func (s *MCPOAuthStore) RefreshIfCurrent(ctx context.Context, key, rejectedAccess string) error
RefreshIfCurrent reacts to a server rejecting rejectedAccess. If the stored token already differs, someone rotated it meanwhile and nothing is done.
func (*MCPOAuthStore) SignOut ¶ added in v0.41.0
func (s *MCPOAuthStore) SignOut(ctx context.Context, serverURL string) error
SignOut removes all OAuth credentials for serverURL and leaves a tokenless sign-in marker. The marker makes an explicit OAuth sign-out take precedence over a configured static Authorization header until the user connects again.
func (*MCPOAuthStore) SignedOut ¶ added in v0.41.0
func (s *MCPOAuthStore) SignedOut(key string) bool
SignedOut reports whether key has an explicit tokenless sign-out marker.
func (*MCPOAuthStore) Subscribe ¶ added in v0.41.0
func (s *MCPOAuthStore) Subscribe(fn func(key string)) (unsubscribe func())
Subscribe registers fn to be called with a key after new tokens for it are stored by Complete. The returned func unregisters it.
func (*MCPOAuthStore) SubscribeSignOut ¶ added in v0.41.0
func (s *MCPOAuthStore) SubscribeSignOut(fn func(key string)) (unsubscribe func())
SubscribeSignOut registers fn to be called after a server is explicitly signed out. It is separate from Subscribe because authorization reconnects waiting servers while sign-out must close live ones.
func (*MCPOAuthStore) Token ¶ added in v0.41.0
Token returns the access token for key, refreshing it first when it is about to expire. It returns (nil, nil) when no record exists, so a server without OAuth is left to its static headers, and ErrMCPAuthRequired when only a human can produce a new token.
type MetaCredentials ¶ added in v0.37.0
type MetaCredentials struct {
OAuthCredentials
APIKey string
}
MetaCredentials is a completed Muse subscription login: the OAuth tokens plus the Model API key minted from them. The key — not the access token — is what /v1/responses accepts.
func LoginMeta ¶ added in v0.37.0
func LoginMeta(ctx context.Context, openURL func(string), display func(*MetaDeviceCode)) (*MetaCredentials, error)
LoginMeta runs the Muse device flow and mints a Model API key from the resulting access token.
func RefreshMetaToken ¶ added in v0.37.0
func RefreshMetaToken(refreshToken string) (*MetaCredentials, error)
RefreshMetaToken renews a Muse subscription login and re-mints its Model API key. The refresh grant is unverified — the launcher never refreshes — so a failure asks for a fresh login instead of guessing further.
type MetaDeviceCode ¶ added in v0.37.0
type MetaDeviceCode struct {
DeviceCode string
UserCode string
VerificationURI string
VerificationURIComplete string
ExpiresIn time.Duration
Interval time.Duration
}
MetaDeviceCode is the user-facing part of a device authorization request.
type OAuthCredentials ¶
type OAuthCredentials struct {
Access string `json:"access"`
Refresh string `json:"refresh"`
Expires int64 `json:"expires"` // Unix milliseconds
AccountID string `json:"account_id,omitempty"` // OpenAI chatgpt_account_id
// APIKey is a provider key derived from the OAuth session instead of the
// access token: Meta mints a Model API key, and api.meta.ai does not
// accept the access token itself.
APIKey string `json:"api_key,omitempty"`
}
OAuthCredentials holds the result of an OAuth login/refresh.
func CompleteAnthropic ¶ added in v0.46.0
func CompleteAnthropic(ctx context.Context, a *CodeAttempt, input string) (*OAuthCredentials, error)
CompleteAnthropic validates the pasted value against a and exchanges the code at the pinned token endpoint. It never reads stdin or opens a browser.
func CompleteOpenAI ¶ added in v0.46.0
func CompleteOpenAI(ctx context.Context, a *CodeAttempt, input string) (*OAuthCredentials, error)
CompleteOpenAI is CompleteAnthropic for OpenAI: input must be the full http://localhost:1455/auth/callback?code=...&state=... URL.
func CompleteXAIDeviceFlow ¶ added in v0.26.0
func CompleteXAIDeviceFlow(ctx context.Context, client *http.Client, _ XAIEndpoints, device *XAIDeviceCode) (*OAuthCredentials, error)
CompleteXAIDeviceFlow uses the endpoint, endpoint configuration and expiry captured at authorization; it never rediscovers metadata or restarts the device-code lifetime. The deadline is measured on the configured clock and re-checked after every wait, so an injected clock and the real one are never mixed.
func LoginAnthropic ¶
func LoginAnthropic(openURL func(string), promptCode func() (string, error)) (*OAuthCredentials, error)
LoginAnthropic runs the Anthropic OAuth PKCE sign-in for the CLI: it opens the authorize URL, then promptCode returns what the user pasted from Anthropic's page (code#state or the callback URL; state is required).
func LoginOpenAI ¶
func LoginOpenAI(openURL func(string), promptCode func() (string, error)) (*OAuthCredentials, error)
LoginOpenAI runs the OpenAI PKCE sign-in for the CLI. A loopback listener on 127.0.0.1:1455 catches the browser redirect when moa runs on this machine; otherwise, after 60 seconds (or if the port is busy), promptCode returns the full callback URL the user copied from the browser.
func LoginXAI ¶ added in v0.26.0
func LoginXAI(ctx context.Context, openURL func(string), display func(*XAIDeviceCode)) (*OAuthCredentials, error)
func RefreshAnthropicToken ¶
func RefreshAnthropicToken(refreshToken string) (*OAuthCredentials, error)
RefreshAnthropicToken refreshes an expired OAuth token.
func RefreshOpenAIToken ¶
func RefreshOpenAIToken(refreshToken string) (*OAuthCredentials, error)
RefreshOpenAIToken refreshes an expired OpenAI OAuth token.
func RefreshXAIToken ¶ added in v0.26.0
func RefreshXAIToken(refreshToken string) (*OAuthCredentials, error)
type ProviderLoginManager ¶ added in v0.46.0
type ProviderLoginManager struct {
// contains filtered or unexported fields
}
ProviderLoginManager runs web sign-ins against the shared Store. Attempts live only in memory (a restart means starting again, with the previous credential intact), there is at most one per provider, and each is bound to the browser that started it and usable once.
Lock order: mu → Store locks. mu is never held across network calls; it is held across the final CommitLogin so a cancel, replacement or expiry cannot interleave with the save.
func NewProviderLoginManager ¶ added in v0.46.0
func NewProviderLoginManager(ctx context.Context, store *Store) *ProviderLoginManager
NewProviderLoginManager returns a manager whose background work (xAI polling) lives until ctx ends or Close is called.
func NewProviderLoginManagerWithHTTPClient ¶ added in v0.46.0
func NewProviderLoginManagerWithHTTPClient(ctx context.Context, store *Store, client *http.Client) *ProviderLoginManager
NewProviderLoginManagerWithHTTPClient is NewProviderLoginManager whose token exchanges and device flow go through client. The fixed production endpoints are unchanged: this is a server-side Go seam for tests that route those origins to a local server, never configuration.
func (*ProviderLoginManager) Begin ¶ added in v0.46.0
func (m *ProviderLoginManager) Begin(ctx context.Context, provider, browserBinding, expectedGeneration string) (LoginAttemptView, error)
Begin starts a sign-in for provider bound to browserBinding (an opaque per-browser secret), replacing any attempt in progress for that provider. expectedGeneration is the stored generation the caller's page showed; a different one means the page is stale. For xAI the device code is requested with ctx, and polling then continues on the manager's lifetime.
func (*ProviderLoginManager) Cancel ¶ added in v0.46.0
func (m *ProviderLoginManager) Cancel(provider, attemptID, browserBinding string) error
Cancel stops an attempt; nothing it obtains afterwards is saved.
func (*ProviderLoginManager) Close ¶ added in v0.46.0
func (m *ProviderLoginManager) Close()
Close cancels every attempt and waits for background polling to stop.
func (*ProviderLoginManager) Complete ¶ added in v0.46.0
func (m *ProviderLoginManager) Complete(ctx context.Context, provider, attemptID, browserBinding, input string) error
Complete finishes an Anthropic or OpenAI sign-in with what the user pasted. A paste that is malformed or belongs to another attempt, provider or browser consumes nothing and makes no request. A matching one is claimed once before the exchange; a matching denial consumes the attempt without any exchange.
func (*ProviderLoginManager) Progress ¶ added in v0.46.0
func (m *ProviderLoginManager) Progress(provider, attemptID, browserBinding string) (LoginProgress, error)
Progress reports an attempt's state. It never exchanges or starts polling.
func (*ProviderLoginManager) SaveAPIKey ¶ added in v0.46.0
func (m *ProviderLoginManager) SaveAPIKey(provider, expectedGeneration, key string) (string, error)
SaveAPIKey stores a write-only API key as a new generation, provided the stored generation is still expectedGeneration. The key is never echoed.
type ProviderStatus ¶ added in v0.46.0
type ProviderStatus struct {
Provider string
Source string // core.CredentialSourceEnv or core.CredentialSourceStore
Kind string // "api_key", "oauth" or "" when unknown
Generation string
State string
PendingSave bool // an unsaved rotation that RetrySave can persist
ChangedAt time.Time
RenewAt time.Time
LastUseOKAt time.Time
}
ProviderStatus is the secret-free state of a provider's selected credential. Zero times mean "not known in this server lifetime".
func (ProviderStatus) NeedsAttention ¶ added in v0.46.0
func (st ProviderStatus) NeedsAttention() bool
NeedsAttention reports a problem only the owner can resolve.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store manages credentials on disk.
Lock order for every mutation (Set, Remove, CommitLogin, RetrySave and both rotation paths): refreshMu → adjacent file lock → mu. refreshMu serializes mutations and makes rotation single-flight inside a process; the file lock does the same across processes. mu only guards short in-memory access and is never held across network calls.
func NewStore ¶
NewStore creates or loads a credential store. It always returns a Store: an unreadable or invalid file is retained as LoadError, so environment credentials keep working while every stored read and write fails closed.
func NewStoreWithHTTPClient ¶ added in v0.46.0
NewStoreWithHTTPClient is NewStore whose token refreshes go through client. The fixed production endpoints are unchanged: this is a server-side Go seam for tests that route those origins to a local server, never configuration.
func (*Store) AdmitAnthropicBackup ¶ added in v0.46.0
func (s *Store) AdmitAnthropicBackup(ctx context.Context, expected BackupRevision, admit func(AnthropicBackupSelection) error) error
AdmitAnthropicBackup linearizes a paid dispatch while holding the existing Store/file locks. The callback is a short Agent admission gate, never HTTP. No resolved key escapes this method until durability and the current key have both been acknowledged. Every retry calls it again after its sleep.
func (*Store) AdmitSnapshot ¶ added in v0.46.0
func (s *Store) AdmitSnapshot(ctx context.Context, expected CredentialSnapshot, admit func(CredentialSnapshot) error) error
AdmitSnapshot checks a prepared selection under the Store lock before the caller's short dispatch gate. Refresh is prepared outside this section.
func (*Store) AnthropicBackupStatus ¶ added in v0.46.0
func (s *Store) AnthropicBackupStatus() (AnthropicBackupStatus, error)
func (*Store) CommitLogin ¶ added in v0.46.0
func (s *Store) CommitLogin(provider, expectedGeneration string, cred Credential) (string, error)
CommitLogin durably stores cred as a new login generation, provided the stored generation for provider is still expectedGeneration ("" for none or a legacy record). It returns the new generation. It governs the store only: whether an environment credential takes precedence is the caller's concern. A durable commit supersedes an unsaved rotation of the previous login.
func (*Store) CredentialKind ¶ added in v0.26.0
CredentialKind reports the credential origin without inspecting token contents. Environment values are always API keys, including JWT-shaped xAI values, so transport selection cannot be confused by token syntax.
func (*Store) Get ¶
func (s *Store) Get(provider string) (Credential, bool)
Get retrieves the cached credential for a provider. It is best-effort and internal: inference must resolve through ResolveSnapshot, which re-reads the file and fails closed.
func (*Store) GetAPIKey ¶
GetAPIKey resolves the API key for a provider. Priority:
- Environment variable (ANTHROPIC_API_KEY, etc.)
- OAuth token from store (auto-refreshed if expired)
- API key from store
Returns the key and whether it's an OAuth token.
func (*Store) GetAccountID ¶
GetAccountID returns the account ID of the effective credential (e.g. the OpenAI chatgpt_account_id). An environment OAuth token answers from its own JWT and never borrows the stored login's account.
func (*Store) LoadError ¶ added in v0.46.0
LoadError reports why the credential file could not be used, or nil.
func (*Store) PeekOAuthToken ¶
PeekOAuthToken returns the current OAuth access token for a provider WITHOUT triggering a refresh. It is for read-only, best-effort callers (e.g. the plan usage widget) that must never rotate the shared refresh token.
- isOAuth is true when an OAuth credential is in use for the provider.
- valid is true only when a non-expired access token is available.
When isOAuth is true but valid is false, the token has expired: the caller should treat usage as temporarily unavailable rather than refresh, and let a real API call renew the token on demand.
func (*Store) PeekSnapshot ¶ added in v0.46.0
func (s *Store) PeekSnapshot(provider string) (CredentialSnapshot, error)
PeekSnapshot is ResolveSnapshot without any refresh or write, for status, capabilities and usage. An expired OAuth snapshot is returned as is.
func (*Store) ProviderStatus ¶ added in v0.46.0
func (s *Store) ProviderStatus(provider string) ProviderStatus
ProviderStatus reports provider's current state from a refresh-free read of the selection plus what this process has observed about it. It makes no network call and writes nothing.
func (*Store) RecordAnthropicBackupUse ¶ added in v0.46.0
func (s *Store) RecordAnthropicBackupUse(revision BackupRevision, err error)
Backup results are attributed only to their secondary generation. They never feed the primary OAuth status or expire its access token.
func (*Store) RecordUse ¶ added in v0.46.0
func (s *Store) RecordUse(snap CredentialSnapshot, err error)
RecordUse records the outcome of one provider request made with snap: a success, or a classified credential failure the owner or user can act on. Other failures (quota, permissions, credentials changed mid-request, store problems that the status reads directly) are not recorded. A result is kept only while snap is still the provider's selection, so a late answer to an older login can neither set nor clear the current one's state. For a failure before any snapshot existed, pass a snapshot with only Provider set: the classified error says which selection failed.
func (*Store) RefreshOAuthIfGeneration ¶ added in v0.46.0
func (s *Store) RefreshOAuthIfGeneration(ctx context.Context, snap CredentialSnapshot, rejected string) (CredentialSnapshot, error)
RefreshOAuthIfGeneration handles a consumer rejecting snap's token. If the current selection is no longer snap's (source, generation, account), it returns credentials_changed without any network call: the request must be sent again, not retried with another login's token. If the same login was already rotated by someone else, that token is reused; otherwise exactly one refresh happens.
func (*Store) RemoveAnthropicAPIKey ¶ added in v0.46.0
RemoveAnthropicAPIKey deletes the key stored next to the plan sign-in, which stays signed in. expectedKey is the key generation the caller saw.
func (*Store) ResolveSnapshot ¶ added in v0.46.0
ResolveSnapshot selects the environment or the stored credential for the next request. Stored credentials are re-read from disk, so a CLI login is noticed without a watcher; an expired OAuth token is rotated on demand, and a pending unsaved rotation is persisted before any new rotation.
func (*Store) RetrySave ¶ added in v0.46.0
RetrySave persists a pending rotation for provider without any network call. It reconciles under lock with whatever other processes wrote: a newer login supersedes the rotation (nil, nothing written over it), and a same-generation divergence is a save conflict that keeps it pending.
func (*Store) SaveAnthropicAPIKey ¶ added in v0.46.0
SaveAnthropicAPIKey stores the one Anthropic API key. Next to a stored plan sign-in it goes to the second slot and never replaces the sign-in; without one it is the primary credential, exactly as before. expectedPrimary is the generation the caller saw for the primary credential. The key is validated by the caller.
type XAIDeviceCode ¶ added in v0.26.0
type XAIDeviceCode struct {
DeviceCode string
UserCode string
VerificationURI string
VerificationURIComplete string
ExpiresIn time.Duration
Interval time.Duration
// contains filtered or unexported fields
}
XAIDeviceCode is the user-facing part of an RFC 8628 authorization request.
func StartXAIDeviceFlow ¶ added in v0.26.0
func StartXAIDeviceFlow(ctx context.Context, client *http.Client, endpoints XAIEndpoints) (*XAIDeviceCode, error)
type XAIEndpoints ¶ added in v0.26.0
type XAIEndpoints struct {
DiscoveryURL string
AllowedHosts []string
AllowedIssuers []string
AllowHTTP bool
Wait func(context.Context, time.Duration) error
Now func() time.Time
}
XAIEndpoints is test configuration for the xAI OIDC client. Production must leave it empty: that pins discovery, issuer, and endpoints to auth.x.ai. A non-default endpoint requires an explicit host allowlist. AllowHTTP and Wait are intended only for local tests.