profiles

package
v1.18.3 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package profiles provides multi-account authentication management for DevClaw. It allows multiple credentials per provider (e.g., google:work, google:personal) with automatic fallback and integration with the encrypted vault.

Index

Constants

This section is empty.

Variables

View Source
var BuiltinProviders = map[string]*ProviderMetadata{

	"openai": {
		Name:        "openai",
		Label:       "OpenAI",
		Description: "OpenAI API (GPT-4, GPT-3.5)",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "OPENAI_API_KEY",
		Website:     "https://platform.openai.com/api-keys",
	},
	"anthropic": {
		Name:        "anthropic",
		Label:       "Anthropic",
		Description: "Anthropic API (Claude)",
		Modes:       []AuthMode{ModeAPIKey, ModeOAuth},
		EnvKey:      "ANTHROPIC_API_KEY",
		Website:     "https://console.anthropic.com/settings/keys",
		Scopes:      []string{"openid", "email", "profile"},
	},
	"gemini": {
		Name:        "gemini",
		Label:       "Google Gemini",
		Description: "Google Gemini API",
		Modes:       []AuthMode{ModeOAuth, ModeAPIKey},
		EnvKey:      "GOOGLE_API_KEY",
		Website:     "https://ai.google.dev/",
		OAuthEndpoint: OAuthEndpoint{
			AuthURL:  "https://accounts.google.com/o/oauth2/v2/auth",
			TokenURL: "https://oauth2.googleapis.com/token",
			Scopes:   []string{"openid", "email", "profile", "https://www.googleapis.com/auth/cloud-platform"},
		},
	},
	"groq": {
		Name:        "groq",
		Label:       "Groq",
		Description: "Groq API (fast inference)",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "GROQ_API_KEY",
		Website:     "https://console.groq.com/keys",
	},
	"mistral": {
		Name:        "mistral",
		Label:       "Mistral AI",
		Description: "Mistral AI API",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "MISTRAL_API_KEY",
		Website:     "https://console.mistral.ai/api-keys/",
	},
	"cohere": {
		Name:        "cohere",
		Label:       "Cohere",
		Description: "Cohere API",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "COHERE_API_KEY",
		Website:     "https://dashboard.cohere.com/api-keys",
	},
	"xai": {
		Name:        "xai",
		Label:       "xAI",
		Description: "xAI API (Grok)",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "XAI_API_KEY",
		Website:     "https://console.x.ai/",
	},
	"deepseek": {
		Name:        "deepseek",
		Label:       "DeepSeek",
		Description: "DeepSeek API",
		Modes:       []AuthMode{ModeAPIKey},
		EnvKey:      "DEEPSEEK_API_KEY",
		Website:     "https://platform.deepseek.com/api_keys",
	},
	"qwen": {
		Name:        "qwen",
		Label:       "Qwen (Alibaba)",
		Description: "Qwen API (Alibaba Cloud)",
		Modes:       []AuthMode{ModeOAuth, ModeAPIKey},
		EnvKey:      "QWEN_API_KEY",
		Website:     "https://dashscope.aliyun.com/",
		OAuthEndpoint: OAuthEndpoint{
			Scopes: []string{"openid", "email", "profile"},
		},
	},
	"minimax": {
		Name:        "minimax",
		Label:       "MiniMax",
		Description: "MiniMax API",
		Modes:       []AuthMode{ModeOAuth, ModeAPIKey},
		EnvKey:      "MINIMAX_API_KEY",
		Website:     "https://www.minimaxi.com/",
		OAuthEndpoint: OAuthEndpoint{
			Scopes: []string{"openid", "email", "profile"},
		},
	},
}

BuiltinProviders contains metadata for built-in authentication providers.

Functions

func CalculateBillingDisable

func CalculateBillingDisable(errorCount int, cfg *ProfileCooldownConfig) time.Duration

CalculateBillingDisable returns the disable duration for billing/auth_permanent errors. Exponential: base * 2^(n-1), capped at max. If cfg is non-nil, uses configured backoff/max hours; otherwise uses defaults.

func CalculateRateLimitCooldown

func CalculateRateLimitCooldown(cfg *ProfileCooldownConfig) time.Duration

CalculateRateLimitCooldown returns the cooldown for rate limit errors. If cfg is non-nil and RateLimitSeconds > 0, uses that value; otherwise falls back to 30s.

func ClearExpiredCooldowns

func ClearExpiredCooldowns(store *ProfileStore) bool

ClearExpiredCooldowns resets cooldown/disabled state for profiles whose windows have passed. Returns true if any state was cleared.

func FormatProfileList

func FormatProfileList(result *ProfileListResult) string

FormatProfileList formats a profile list for display.

func GetOAuthScopes

func GetOAuthScopes(provider string, service string) ([]string, error)

GetOAuthScopes returns the OAuth scopes for a provider and service.

func GetSuggestedProfileNames

func GetSuggestedProfileNames(provider string) []string

GetSuggestedProfileNames returns suggested profile names for a provider.

func IsAuthCooldownBypassedForProfile

func IsAuthCooldownBypassedForProfile(store *ProfileStore, id ProfileID) bool

IsAuthCooldownBypassedForProfile returns true if the profile's provider should bypass auth-related cooldowns. Currently only OpenRouter qualifies because it routes internally and auth errors for one backend don't affect others.

func IsProfileInCooldown

func IsProfileInCooldown(store *ProfileStore, id ProfileID) bool

IsProfileInCooldown returns true if the profile is in cooldown or disabled. OpenRouter profiles bypass auth cooldowns because OpenRouter handles authentication routing internally across multiple providers.

func IsValidProvider

func IsValidProvider(name string) bool

IsValidProvider checks if a provider name is valid.

func MarkProfileFailure

func MarkProfileFailure(store *ProfileStore, id ProfileID, reason FailureReason, cfg *ProfileCooldownConfig)

MarkProfileFailure records a categorized failure for a profile. Rate limit -> short flat cooldown. Billing/auth_permanent -> exponential disable. Other transient errors -> no cooldown (just tracked). cfg is optional — pass nil to use hardcoded defaults.

func NewStore

func NewStore(cfg StoreConfig) (*vaultStore, error)

NewStore creates a new profile store backed by the encrypted vault.

func RegisterCustomProvider

func RegisterCustomProvider(metadata *ProviderMetadata) error

RegisterCustomProvider registers a custom provider at runtime.

func ResolveProfileUnusableUntil

func ResolveProfileUnusableUntil(store *ProfileStore, id ProfileID) *time.Time

ResolveProfileUnusableUntil returns the timestamp until which the profile is unusable, or nil if the profile is available.

func SupportsMode

func SupportsMode(provider string, mode AuthMode) bool

SupportsMode checks if a provider supports a specific authentication mode.

Types

type APIKeyCredential

type APIKeyCredential struct {
	// Key is the API key value.
	Key string `json:"key,omitempty"`

	// KeyRef is a vault reference for the key (e.g., "vault://OPENAI_API_KEY").
	KeyRef string `json:"key_ref,omitempty"`
}

APIKeyCredential represents a static API key authentication.

type AuthMode

type AuthMode string

AuthMode represents the authentication method for a profile.

const (
	// ModeAPIKey uses a static API key.
	ModeAPIKey AuthMode = "api_key"
	// ModeOAuth uses OAuth 2.0 with refresh tokens.
	ModeOAuth AuthMode = "oauth"
	// ModeToken uses a static bearer token (no refresh).
	ModeToken AuthMode = "token"
)

type AuthProfile

type AuthProfile struct {
	// ID is the unique profile identifier (provider:name).
	ID ProfileID `json:"id"`

	// Provider is the authentication provider (e.g., "google", "openai").
	Provider string `json:"provider"`

	// Name is the profile name (e.g., "default", "work", "personal").
	Name string `json:"name"`

	// Mode is the authentication method.
	Mode AuthMode `json:"mode"`

	// Priority determines fallback order (higher = tried first).
	Priority int `json:"priority,omitempty"`

	// Enabled indicates if this profile is active.
	Enabled bool `json:"enabled"`

	// CreatedAt is when the profile was created.
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is when the profile was last updated.
	UpdatedAt time.Time `json:"updated_at"`

	// LastUsedAt is when the profile was last successfully used.
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`

	// LastError is the last error message if authentication failed.
	LastError string `json:"last_error,omitempty"`

	// LastErrorAt is when the last error occurred.
	LastErrorAt *time.Time `json:"last_error_at,omitempty"`

	// Credential data based on Mode.
	APIKey *APIKeyCredential `json:"api_key,omitempty"`
	OAuth  *OAuthCredential  `json:"oauth,omitempty"`
	Token  *TokenCredential  `json:"token,omitempty"`
}

AuthProfile represents a named authentication profile for a provider.

func (*AuthProfile) ClearError

func (p *AuthProfile) ClearError()

ClearError clears the last error.

func (*AuthProfile) GetAPIKey

func (p *AuthProfile) GetAPIKey(vaultGetter func(string) (string, error)) (string, error)

GetAPIKey returns the API key value, resolving vault references if needed.

func (*AuthProfile) GetToken

func (p *AuthProfile) GetToken(vaultGetter func(string) (string, error)) (string, error)

GetToken returns the token value, resolving vault references if needed.

func (*AuthProfile) IsExpired

func (p *AuthProfile) IsExpired() bool

IsExpired returns true if the profile's credentials have expired.

func (*AuthProfile) IsValid

func (p *AuthProfile) IsValid() bool

IsValid returns true if the profile is enabled and has valid credentials.

func (*AuthProfile) MarkError

func (p *AuthProfile) MarkError(err error)

MarkError records an authentication error.

func (*AuthProfile) MarkUsed

func (p *AuthProfile) MarkUsed()

MarkUsed updates the LastUsedAt timestamp.

type FailureReason

type FailureReason string

FailureReason categorizes why a profile authentication failed. Used to determine cooldown strategy (transient vs permanent).

const (
	FailureAuth           FailureReason = "auth"
	FailureAuthPermanent  FailureReason = "auth_permanent"
	FailureRateLimit      FailureReason = "rate_limit"
	FailureBilling        FailureReason = "billing"
	FailureTimeout        FailureReason = "timeout"
	FailureFormat         FailureReason = "format"
	FailureModelNotFound  FailureReason = "model_not_found"
	FailureSessionExpired FailureReason = "session_expired"
	FailureUnknown        FailureReason = "unknown"
)

func ClassifyFailure

func ClassifyFailure(err error) FailureReason

ClassifyFailure determines the failure reason from an error. Used to select the appropriate cooldown strategy.

func ClassifyFailureMessage

func ClassifyFailureMessage(msg string) FailureReason

ClassifyFailureMessage determines the failure reason from an error message string.

type FallbackChain

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

FallbackChain represents a chain of fallback providers.

func NewFallbackChain

func NewFallbackChain(resolver *Resolver, providers ...string) *FallbackChain

NewFallbackChain creates a new fallback chain.

func (*FallbackChain) Resolve

Resolve attempts to resolve each provider in order until one succeeds.

type MultiResolver

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

MultiResolver resolves credentials for multiple providers simultaneously.

func NewMultiResolver

func NewMultiResolver(resolver *Resolver) *MultiResolver

NewMultiResolver creates a new multi-provider resolver.

func (*MultiResolver) ResolveAll

func (m *MultiResolver) ResolveAll(ctx context.Context, providers []string) map[string]*ProfileResolutionResult

ResolveAll resolves credentials for multiple providers in parallel.

type OAuthCredential

type OAuthCredential struct {
	// Provider identifies the OAuth provider.
	Provider string `json:"provider"`

	// ProfileName is the name of this profile (e.g., "work", "personal").
	ProfileName string `json:"profile_name"`

	// AccessToken is the OAuth access token.
	AccessToken string `json:"access_token"`

	// RefreshToken is used to obtain new access tokens.
	RefreshToken string `json:"refresh_token"`

	// ExpiresAt is when the access token expires.
	ExpiresAt time.Time `json:"expires_at"`

	// Email is the user's email associated with the OAuth account.
	Email string `json:"email,omitempty"`

	// ClientID is the OAuth client ID.
	ClientID string `json:"client_id,omitempty"`

	// Scopes are the OAuth scopes granted.
	Scopes []string `json:"scopes,omitempty"`

	// Metadata contains provider-specific data.
	Metadata map[string]string `json:"metadata,omitempty"`
}

OAuthCredential wraps the oauth.OAuthCredential with profile-specific fields.

func (*OAuthCredential) FromOAuthCredential

func (c *OAuthCredential) FromOAuthCredential(oc *oauth.OAuthCredential, profileName string)

FromOAuthCredential populates from an oauth package credential.

func (*OAuthCredential) IsExpired

func (c *OAuthCredential) IsExpired(buffer time.Duration) bool

IsExpired returns true if the credential has expired or will expire within the buffer.

func (*OAuthCredential) IsValid

func (c *OAuthCredential) IsValid() bool

IsValid returns true if the credential has a valid access token.

func (*OAuthCredential) ToOAuthCredential

func (c *OAuthCredential) ToOAuthCredential() *oauth.OAuthCredential

ToOAuthCredential converts to the oauth package format.

type OAuthEndpoint

type OAuthEndpoint struct {
	AuthURL  string   `json:"auth_url,omitempty"`
	TokenURL string   `json:"token_url,omitempty"`
	Scopes   []string `json:"scopes,omitempty"`
}

OAuthEndpoint contains OAuth endpoint URLs.

type OAuthManager

type OAuthManager interface {
	GetValidToken(provider string) (*oauth.OAuthCredential, error)
	SaveCredential(cred *oauth.OAuthCredential) error
}

OAuthManager defines the interface for OAuth operations.

type OAuthTokenRefresher

type OAuthTokenRefresher interface {
	// RefreshToken refreshes an OAuth token for a provider.
	RefreshToken(provider, refreshToken string) (*oauth.OAuthCredential, error)
}

OAuthTokenRefresher defines the interface for refreshing OAuth tokens.

type ProfileAddArgs

type ProfileAddArgs struct {
	Provider string `json:"provider"`           // e.g., "google", "openai"
	Name     string `json:"name"`               // e.g., "work", "personal"
	Mode     string `json:"mode"`               // "api_key", "oauth", "token"
	APIKey   string `json:"api_key,omitempty"`  // For API key mode
	Token    string `json:"token,omitempty"`    // For token mode
	Priority int    `json:"priority,omitempty"` // Higher = tried first
}

ProfileAddArgs contains arguments for adding a profile.

type ProfileAddResult

type ProfileAddResult struct {
	Success   bool   `json:"success"`
	ProfileID string `json:"profile_id,omitempty"`
	Error     string `json:"error,omitempty"`
}

ProfileAddResult contains the result of adding a profile.

type ProfileCooldownConfig

type ProfileCooldownConfig struct {
	RateLimitSeconds    int                                 `yaml:"rate_limit_seconds"`    // Default: 30
	BillingBackoffHours float64                             `yaml:"billing_backoff_hours"` // Default: 5
	BillingMaxHours     float64                             `yaml:"billing_max_hours"`     // Default: 24
	FailureWindowHours  float64                             `yaml:"failure_window_hours"`  // Default: 24
	ByProvider          map[string]ProviderCooldownOverride `yaml:"by_provider"`
}

ProfileCooldownConfig allows overriding default cooldown durations via YAML config. All fields are optional; zero values fall back to hardcoded defaults.

type ProfileDeleteArgs

type ProfileDeleteArgs struct {
	ProfileID string `json:"profile_id"` // Format: "provider:name"
}

ProfileDeleteArgs contains arguments for deleting a profile.

type ProfileDeleteResult

type ProfileDeleteResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

ProfileDeleteResult contains the result of deleting a profile.

type ProfileEnableArgs

type ProfileEnableArgs struct {
	ProfileID string `json:"profile_id"`
	Enable    bool   `json:"enable"`
}

ProfileEnableArgs contains arguments for enabling/disabling a profile.

type ProfileEnableResult

type ProfileEnableResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

ProfileEnableResult contains the result of enabling/disabling a profile.

type ProfileExportArgs

type ProfileExportArgs struct {
	ProfileID string `json:"profile_id"`
}

ProfileExportArgs contains arguments for exporting a profile.

type ProfileExportResult

type ProfileExportResult struct {
	Success bool            `json:"success"`
	Data    json.RawMessage `json:"data,omitempty"`
	Mode    string          `json:"mode,omitempty"`
	Error   string          `json:"error,omitempty"`
}

ProfileExportResult contains the result of exporting a profile.

type ProfileID

type ProfileID string

ProfileID uniquely identifies an auth profile. Format: "{provider}:{name}" e.g., "google:work", "openai:default"

func NewProfileID

func NewProfileID(provider, name string) ProfileID

NewProfileID creates a profile ID from provider and name.

func (ProfileID) Name

func (p ProfileID) Name() string

Name returns the name part of the profile ID.

func (ProfileID) Provider

func (p ProfileID) Provider() string

Provider returns the provider part of the profile ID.

func (ProfileID) String

func (p ProfileID) String() string

String returns the string representation of the profile ID.

type ProfileImportArgs

type ProfileImportArgs struct {
	Provider string          `json:"provider"`
	Name     string          `json:"name"`
	Mode     string          `json:"mode"`
	Data     json.RawMessage `json:"data"` // Provider-specific credential data
}

ProfileImportArgs contains arguments for importing a profile.

type ProfileImportResult

type ProfileImportResult struct {
	Success   bool   `json:"success"`
	ProfileID string `json:"profile_id,omitempty"`
	Error     string `json:"error,omitempty"`
}

ProfileImportResult contains the result of importing a profile.

type ProfileListArgs

type ProfileListArgs struct {
	Provider string `json:"provider,omitempty"` // Filter by provider (optional)
	Mode     string `json:"mode,omitempty"`     // Filter by mode (optional)
	Enabled  *bool  `json:"enabled,omitempty"`  // Filter by enabled status (optional)
}

ProfileListArgs contains arguments for listing profiles.

type ProfileListItem

type ProfileListItem struct {
	ID         string    `json:"id"`
	Provider   string    `json:"provider"`
	Name       string    `json:"name"`
	Mode       string    `json:"mode"`
	Enabled    bool      `json:"enabled"`
	Valid      bool      `json:"valid"`
	Expired    bool      `json:"expired,omitempty"`
	Email      string    `json:"email,omitempty"`
	Priority   int       `json:"priority,omitempty"`
	LastUsedAt time.Time `json:"last_used_at,omitempty"`
	LastError  string    `json:"last_error,omitempty"`
}

ProfileListItem represents a profile in the list.

type ProfileListResult

type ProfileListResult struct {
	Profiles []ProfileListItem `json:"profiles"`
	Total    int               `json:"total"`
}

ProfileListResult contains the result of listing profiles.

type ProfileManager

type ProfileManager interface {
	// Get retrieves a profile by ID.
	Get(id ProfileID) (*AuthProfile, bool)

	// GetByProvider retrieves profiles for a provider, sorted by preference.
	GetByProvider(provider string, preference ProfilePreference) []*AuthProfile

	// Save stores a profile.
	Save(profile *AuthProfile) error

	// Delete removes a profile.
	Delete(id ProfileID) error

	// List returns all profiles.
	List() []*AuthProfile

	// Resolve resolves a profile based on options, with automatic fallback.
	Resolve(opts ResolutionOptions) *ProfileResolutionResult

	// MarkUsed updates the last used timestamp for a profile.
	MarkUsed(id ProfileID)

	// MarkError records an error for a profile.
	MarkError(id ProfileID, err error)

	// MarkFailure records a categorized failure and applies cooldown/disable.
	MarkFailure(id ProfileID, reason FailureReason)

	// IsInCooldown returns true if the profile is currently in cooldown or disabled.
	IsInCooldown(id ProfileID) bool

	// ClearExpiredCooldowns resets cooldown/disabled state for profiles whose windows have passed.
	ClearExpiredCooldowns()
}

ProfileManager defines the interface for managing auth profiles.

type ProfilePreference

type ProfilePreference string

ProfilePreference indicates how to select between multiple profiles.

const (
	// PreferDefault uses the "default" profile or the highest priority.
	PreferDefault ProfilePreference = "default"
	// PreferValid prefers profiles with valid (non-expired) credentials.
	PreferValid ProfilePreference = "valid"
	// PreferRecent prefers the most recently used profile.
	PreferRecent ProfilePreference = "recent"
	// PreferType orders by auth type (oauth > token > api_key), then by
	// least-recently-used within the same type for round-robin distribution.
	PreferType ProfilePreference = "type"
)

type ProfileResolutionResult

type ProfileResolutionResult struct {
	// Profile is the resolved profile (nil if not found).
	Profile *AuthProfile

	// Credential is the resolved credential string (API key, token, or OAuth access token).
	Credential string

	// Provider is the provider name.
	Provider string

	// Email is the associated email (for OAuth).
	Email string

	// Error if resolution failed.
	Error error

	// AttemptedProfiles lists profiles that were tried.
	AttemptedProfiles []ProfileID
}

ProfileResolutionResult contains the result of resolving a profile.

type ProfileSetPriorityArgs

type ProfileSetPriorityArgs struct {
	ProfileID string `json:"profile_id"`
	Priority  int    `json:"priority"`
}

ProfileSetPriorityArgs contains arguments for setting profile priority.

type ProfileSetPriorityResult

type ProfileSetPriorityResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

ProfileSetPriorityResult contains the result of setting priority.

type ProfileStore

type ProfileStore struct {
	Version    int                           `json:"version"`
	Profiles   map[string]*AuthProfile       `json:"profiles"`              // key is "provider:name"
	UsageStats map[string]*ProfileUsageStats `json:"usage_stats,omitempty"` // key is "provider:name"
	LastGood   map[string]string             `json:"last_good,omitempty"`   // provider → profileID of last successful call
}

ProfileStore is the on-disk format for auth profiles.

func NewProfileStore

func NewProfileStore() *ProfileStore

NewProfileStore creates a new empty profile store.

func (*ProfileStore) Delete

func (s *ProfileStore) Delete(id ProfileID)

Delete removes a profile.

func (*ProfileStore) Get

func (s *ProfileStore) Get(id ProfileID) (*AuthProfile, bool)

Get retrieves a profile by ID.

func (*ProfileStore) GetUsageStats

func (s *ProfileStore) GetUsageStats(id ProfileID) *ProfileUsageStats

GetUsageStats returns usage stats for a profile, creating if absent.

func (*ProfileStore) List

func (s *ProfileStore) List() []*AuthProfile

List returns all profiles.

func (*ProfileStore) ListByProvider

func (s *ProfileStore) ListByProvider(provider string) []*AuthProfile

ListByProvider returns all profiles for a specific provider.

func (*ProfileStore) MarkAuthProfileGood

func (s *ProfileStore) MarkAuthProfileGood(provider string, id ProfileID)

MarkAuthProfileGood records a profile as the last known good for its provider.

func (*ProfileStore) MarshalJSON

func (s *ProfileStore) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON representation with sorted keys for consistency.

func (*ProfileStore) Set

func (s *ProfileStore) Set(p *AuthProfile)

Set stores a profile.

type ProfileTestArgs

type ProfileTestArgs struct {
	ProfileID string `json:"profile_id"`
}

ProfileTestArgs contains arguments for testing a profile.

type ProfileTestResult

type ProfileTestResult struct {
	Success   bool          `json:"success"`
	Valid     bool          `json:"valid"`
	Expired   bool          `json:"expired,omitempty"`
	Email     string        `json:"email,omitempty"`
	Error     string        `json:"error,omitempty"`
	ExpiresIn time.Duration `json:"expires_in,omitempty"`
}

ProfileTestResult contains the result of testing a profile.

type ProfileTools

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

ProfileTools provides tool functions for managing authentication profiles.

func NewProfileTools

func NewProfileTools(store ProfileManager, resolver *Resolver) *ProfileTools

NewProfileTools creates a new profile tools instance.

func (*ProfileTools) Add

Add adds a new authentication profile.

func (*ProfileTools) Delete

Delete deletes an authentication profile.

func (*ProfileTools) Enable

Enable enables or disables a profile.

func (*ProfileTools) Export

Export exports a profile's credential data (for backup/migration).

func (*ProfileTools) Import

Import imports a profile from external credential data.

func (*ProfileTools) List

List lists authentication profiles.

func (*ProfileTools) Providers

func (t *ProfileTools) Providers(ctx context.Context) (*ProvidersListResult, error)

Providers lists available authentication providers.

func (*ProfileTools) SetPriority

SetPriority sets the priority of a profile (higher = tried first in fallback).

func (*ProfileTools) Test

Test tests if a profile has valid credentials.

type ProfileUsageStats

type ProfileUsageStats struct {
	LastUsed       *time.Time            `json:"last_used,omitempty"`
	CooldownUntil  *time.Time            `json:"cooldown_until,omitempty"`
	DisabledUntil  *time.Time            `json:"disabled_until,omitempty"`
	DisabledReason FailureReason         `json:"disabled_reason,omitempty"`
	ErrorCount     int                   `json:"error_count,omitempty"`
	FailureCounts  map[FailureReason]int `json:"failure_counts,omitempty"`
	LastFailureAt  *time.Time            `json:"last_failure_at,omitempty"`
}

ProfileUsageStats tracks per-profile cooldown and failure state. Cooldown: short lockout for transient errors (rate limit). Disabled: long lockout for persistent errors (billing, auth_permanent).

type ProviderCooldownOverride

type ProviderCooldownOverride struct {
	RateLimitSeconds    int     `yaml:"rate_limit_seconds"`
	BillingBackoffHours float64 `yaml:"billing_backoff_hours"`
}

ProviderCooldownOverride allows per-provider cooldown tuning.

type ProviderInfo

type ProviderInfo struct {
	Name        string   `json:"name"`
	Label       string   `json:"label"`
	Description string   `json:"description"`
	Modes       []string `json:"modes"`
	EnvKey      string   `json:"env_key,omitempty"`
	Website     string   `json:"website,omitempty"`
}

ProviderInfo represents information about a provider.

type ProviderMetadata

type ProviderMetadata struct {
	// Name is the provider identifier.
	Name string `json:"name"`

	// Label is a human-readable name.
	Label string `json:"label"`

	// Description explains what the provider is for.
	Description string `json:"description"`

	// Modes lists the supported authentication modes.
	Modes []AuthMode `json:"modes"`

	// EnvKey is the environment variable name for API keys.
	EnvKey string `json:"env_key,omitempty"`

	// Website is the URL for obtaining credentials.
	Website string `json:"website,omitempty"`

	// Scopes are the default OAuth scopes.
	Scopes []string `json:"scopes,omitempty"`

	// OAuthEndpoint contains OAuth endpoint configuration.
	OAuthEndpoint OAuthEndpoint `json:"oauth_endpoint,omitempty"`

	// ParentProvider indicates this is a child of another provider.
	ParentProvider string `json:"parent_provider,omitempty"`
}

ProviderMetadata contains metadata about an authentication provider.

func GetProvider

func GetProvider(name string) (*ProviderMetadata, bool)

GetProvider returns metadata for a provider by name.

func GetProviderWithScopes

func GetProviderWithScopes(name string) (*ProviderMetadata, bool)

GetProviderWithScopes returns metadata for a provider with resolved OAuth scopes.

func ListProviders

func ListProviders() []*ProviderMetadata

ListProviders returns all built-in providers.

func ListProvidersByMode

func ListProvidersByMode(mode AuthMode) []*ProviderMetadata

ListProvidersByMode returns providers that support a specific mode.

type ProvidersListResult

type ProvidersListResult struct {
	Providers []ProviderInfo `json:"providers"`
}

ProvidersListResult contains the result of listing available providers.

type ResolutionOptions

type ResolutionOptions struct {
	// Provider is the required provider (e.g., "google", "openai").
	Provider string

	// PreferredProfile is a specific profile name to use (optional).
	PreferredProfile string

	// Preference indicates how to select between multiple profiles.
	Preference ProfilePreference

	// RequireValid requires the profile to have valid (non-expired) credentials.
	RequireValid bool

	// Mode restricts to a specific authentication mode (optional).
	Mode AuthMode
}

ResolutionOptions configures profile resolution behavior.

type Resolver

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

Resolver handles profile resolution with caching and refresh logic.

func NewResolver

func NewResolver(cfg ResolverConfig) *Resolver

NewResolver creates a new profile resolver.

func (*Resolver) GetCacheStats

func (r *Resolver) GetCacheStats() map[string]interface{}

GetCacheStats returns statistics about the resolver cache.

func (*Resolver) InvalidateCache

func (r *Resolver) InvalidateCache(provider string)

InvalidateCache invalidates the cache for a specific provider or all if empty.

func (*Resolver) Resolve

func (r *Resolver) Resolve(ctx context.Context, provider string, preferredProfile string) (*ProfileResolutionResult, error)

Resolve resolves a credential for a provider, with caching and automatic fallback.

func (*Resolver) ResolveAPIKey

func (r *Resolver) ResolveAPIKey(ctx context.Context, provider string) (string, *AuthProfile, error)

ResolveAPIKey resolves an API key for a provider.

func (*Resolver) ResolveAny

func (r *Resolver) ResolveAny(ctx context.Context, provider string) (*ProfileResolutionResult, error)

ResolveAny resolves any valid credential for a provider (tries OAuth first, then API key, then token).

func (*Resolver) ResolveOAuth

func (r *Resolver) ResolveOAuth(ctx context.Context, provider string) (*oauth.OAuthCredential, *AuthProfile, error)

ResolveOAuth resolves an OAuth credential for a provider, with automatic refresh.

func (*Resolver) ResolveWithMode

func (r *Resolver) ResolveWithMode(ctx context.Context, provider string, mode AuthMode) (*ProfileResolutionResult, error)

ResolveWithMode resolves a credential with a specific auth mode requirement.

type ResolverConfig

type ResolverConfig struct {
	Store             ProfileManager
	OAuthManager      OAuthManager
	Logger            *slog.Logger
	DefaultPreference ProfilePreference
}

ResolverConfig contains configuration for the resolver.

type StoreConfig

type StoreConfig struct {
	// Vault is the encrypted vault interface.
	Vault VaultInterface

	// OAuthManager is the OAuth token manager.
	OAuthManager OAuthManager

	// Logger for logging operations.
	Logger *slog.Logger

	// CachePath is an optional path to cache decrypted profiles.
	// If empty, no disk cache is used.
	CachePath string

	// CooldownConfig allows overriding default cooldown durations.
	// If nil, hardcoded defaults are used.
	CooldownConfig *ProfileCooldownConfig
}

StoreConfig contains configuration for the profile store.

type TokenCredential

type TokenCredential struct {
	// Token is the bearer token value.
	Token string `json:"token,omitempty"`

	// TokenRef is a vault reference for the token.
	TokenRef string `json:"token_ref,omitempty"`

	// ExpiresAt is when the token expires (optional).
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
}

TokenCredential represents a static bearer token authentication.

type VaultInterface

type VaultInterface interface {
	Get(name string) (string, error)
	Set(name, value string) error
	Has(name string) bool
	Delete(name string) error
	IsUnlocked() bool
}

VaultInterface defines the interface for vault operations.

Jump to

Keyboard shortcuts

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