auth

package
v0.31.4 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GeneratePKCE

func GeneratePKCE() (verifier, challenge string, err error)

GeneratePKCE generates a cryptographically secure PKCE verifier and challenge pair for the OAuth 2.0 PKCE flow. The verifier is a random 32-byte string encoded as base64url, and the challenge is the SHA256 hash of the verifier, also base64url encoded. Returns the verifier (to be stored securely), challenge (to be sent with auth request), and any error encountered during generation.

func GetAnthropicAPIKey

func GetAnthropicAPIKey(flagValue string) (string, string, error)

GetAnthropicAPIKey retrieves an Anthropic API key from multiple sources in priority order: 1. Command-line flag value (highest priority) 2. Stored credentials (OAuth or API key) 3. ANTHROPIC_API_KEY environment variable (lowest priority) Returns the API key, a description of its source, and any error encountered. For OAuth credentials, it automatically refreshes expired tokens.

func OpenBrowser

func OpenBrowser(url string) error

OpenBrowser opens the default web browser to the specified URL. It automatically detects the operating system and uses the appropriate command to launch the browser (xdg-open on Linux, rundll32 on Windows, open on macOS). Returns an error if the platform is unsupported or if the browser fails to launch.

func TryOpenBrowser

func TryOpenBrowser(url string)

TryOpenBrowser attempts to open the default web browser to the specified URL but silently ignores any errors. This is useful when browser access is optional and users can manually copy and paste the URL if automatic browser launching fails.

Types

type AnthropicCredentials

type AnthropicCredentials struct {
	Type         string    `json:"type"`                    // "oauth" or "api_key"
	APIKey       string    `json:"api_key,omitempty"`       // For API key auth
	AccessToken  string    `json:"access_token,omitempty"`  // For OAuth
	RefreshToken string    `json:"refresh_token,omitempty"` // For OAuth
	ExpiresAt    int64     `json:"expires_at,omitempty"`    // For OAuth
	CreatedAt    time.Time `json:"created_at"`
}

AnthropicCredentials holds Anthropic API credentials supporting both OAuth and API key authentication methods. The Type field indicates which authentication method is being used. For OAuth, tokens are stored with expiration timestamps for automatic refresh. For API keys, only the key itself is stored.

func (*AnthropicCredentials) IsExpired

func (c *AnthropicCredentials) IsExpired() bool

IsExpired checks if the OAuth token is expired based on the ExpiresAt timestamp. Returns false for API key authentication or if no expiration is set.

func (*AnthropicCredentials) NeedsRefresh

func (c *AnthropicCredentials) NeedsRefresh() bool

NeedsRefresh checks if the OAuth token needs refresh, returning true if the token will expire within the next 5 minutes. This allows for proactive token refresh to avoid authentication failures during operations. Returns false for API key authentication or if no expiration is set.

type AuthData

type AuthData struct {
	URL      string
	Verifier string
}

AuthData contains the authorization URL for user authentication and the PKCE verifier needed for the subsequent code exchange. The verifier must be stored securely and used when exchanging the authorization code for tokens.

type CredentialManager

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

CredentialManager handles secure storage and retrieval of authentication credentials. It manages a JSON file stored in the user's config directory with appropriate file permissions for security.

func NewCredentialManager

func NewCredentialManager() (*CredentialManager, error)

NewCredentialManager creates a new credential manager instance. It determines the appropriate credentials path based on XDG_CONFIG_HOME or falls back to ~/.config/.mcphost/credentials.json. Returns an error if the home directory cannot be determined.

func (*CredentialManager) GetAnthropicCredentials

func (cm *CredentialManager) GetAnthropicCredentials() (*AnthropicCredentials, error)

GetAnthropicCredentials retrieves stored Anthropic credentials. Returns nil if no credentials are stored. The returned credentials may be either OAuth or API key type, check the Type field to determine which.

func (*CredentialManager) GetCredentialsPath

func (cm *CredentialManager) GetCredentialsPath() string

GetCredentialsPath returns the absolute path to the credentials JSON file. This is useful for debugging or displaying the storage location to users.

func (*CredentialManager) GetValidAccessToken

func (cm *CredentialManager) GetValidAccessToken() (string, error)

GetValidAccessToken returns a valid access token for API requests. For OAuth credentials, it automatically refreshes the token if it's expired or about to expire. For API key credentials, it simply returns the API key. Returns an error if no credentials are found, if token refresh fails, or if the credential type is unknown.

func (*CredentialManager) HasAnthropicCredentials

func (cm *CredentialManager) HasAnthropicCredentials() (bool, error)

HasAnthropicCredentials checks if valid Anthropic credentials are stored. Returns true if either a non-empty OAuth access token or API key is present, false otherwise. Returns an error if credentials cannot be loaded.

func (*CredentialManager) LoadCredentials

func (cm *CredentialManager) LoadCredentials() (*CredentialStore, error)

LoadCredentials loads credentials from the JSON file. If the file doesn't exist, it returns an empty CredentialStore instead of an error, allowing for graceful initialization. Returns an error if the file exists but cannot be read or parsed.

func (*CredentialManager) RemoveAnthropicCredentials

func (cm *CredentialManager) RemoveAnthropicCredentials() error

RemoveAnthropicCredentials removes stored Anthropic credentials from storage. If this was the only credential stored, the entire credentials file is removed. Returns an error if the removal fails.

func (*CredentialManager) SaveCredentials

func (cm *CredentialManager) SaveCredentials(store *CredentialStore) error

SaveCredentials saves credentials to the JSON file with secure permissions (0600). It creates the parent directory if it doesn't exist. The file is written atomically to prevent corruption. Returns an error if the directory cannot be created or the file cannot be written.

func (*CredentialManager) SetAnthropicCredentials

func (cm *CredentialManager) SetAnthropicCredentials(apiKey string) error

SetAnthropicCredentials stores Anthropic API key credentials. It validates the API key format before storing. The API key must start with "sk-ant-" and be at least 20 characters long. Returns an error if the API key is invalid or if storage fails.

func (*CredentialManager) SetOAuthCredentials

func (cm *CredentialManager) SetOAuthCredentials(creds *AnthropicCredentials) error

SetOAuthCredentials stores OAuth credentials in the credential manager's secure storage. The credentials should include access token, refresh token, and expiration information. Returns an error if the credentials cannot be saved.

type CredentialStore

type CredentialStore struct {
	Anthropic *AnthropicCredentials `json:"anthropic,omitempty"`
}

CredentialStore holds all stored credentials for various providers. Currently supports Anthropic credentials with both OAuth and API key authentication methods.

type OAuthClient

type OAuthClient struct {
	ClientID     string
	AuthorizeURL string
	TokenURL     string
	RedirectURI  string
	Scopes       string
}

OAuthClient handles OAuth 2.0 authentication flow with Anthropic using the PKCE (Proof Key for Code Exchange) extension for enhanced security in public clients. It manages the authorization URL generation, code exchange, and token refresh operations.

func NewOAuthClient

func NewOAuthClient() *OAuthClient

NewOAuthClient creates a new OAuth client configured for Anthropic's OAuth service. The client uses a public client ID (as per OAuth 2.0 public client specification) with PKCE for security. The configuration includes the authorization endpoint, token endpoint, redirect URI, and required scopes for API key creation and inference.

func (*OAuthClient) ExchangeCode

func (c *OAuthClient) ExchangeCode(code, verifier string) (*AnthropicCredentials, error)

ExchangeCode exchanges an authorization code for access and refresh tokens. The code parameter should be the authorization code received from the OAuth callback. The verifier parameter must be the same PKCE verifier generated during GetAuthorizationURL. Returns AnthropicCredentials containing the tokens and expiration information.

func (*OAuthClient) GetAuthorizationURL

func (c *OAuthClient) GetAuthorizationURL() (*AuthData, error)

GetAuthorizationURL generates a complete authorization URL for the OAuth flow with PKCE parameters. The URL includes the client ID, redirect URI, requested scopes, and PKCE challenge. Returns an AuthData structure containing the URL for user authentication and the PKCE verifier for the subsequent code exchange.

func (*OAuthClient) RefreshToken

func (c *OAuthClient) RefreshToken(refreshToken string) (*AnthropicCredentials, error)

RefreshToken refreshes an expired or expiring access token using a refresh token. Returns new AnthropicCredentials with updated access token, refresh token (may be rotated), and new expiration timestamp. Returns an error if the refresh fails or the refresh token is invalid.

Jump to

Keyboard shortcuts

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