auth

package
v0.85.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const CredentialSourceOAuth = "stored OAuth credentials"

CredentialSourceOAuth is the source description returned by GetAnthropicAPIKey when the key resolves to stored OAuth credentials. Consumers should compare against this constant (or use IsAnthropicOAuth) rather than matching the string literal.

Variables

This section is empty.

Functions

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 IsAnthropicOAuth added in v0.75.1

func IsAnthropicOAuth(flagValue string) bool

IsAnthropicOAuth reports whether the active Anthropic credential resolves to a stored OAuth token (in which case the user is not billed per-token). flagValue is the --provider-api-key flag value (may be empty).

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 ParseOpenAIAuthorizationInput added in v0.25.0

func ParseOpenAIAuthorizationInput(input string) (code, state string)

ParseOpenAIAuthorizationInput parses various forms of authorization input: - Full callback URL: http://localhost:1455/auth/callback?code=xxx&state=yyy - Code#State format: abc123#state456 - Query string: code=abc123&state=state456 - Just the code: abc123

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
	State    string // Optional state parameter for CSRF protection
}

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 CopilotCredentials added in v0.75.0

type CopilotCredentials struct {
	Type               string    `json:"type"`                           // "oauth"
	GitHubToken        string    `json:"github_token,omitempty"`         // GitHub device-flow OAuth token
	CopilotAccessToken string    `json:"copilot_access_token,omitempty"` // Short-lived Copilot API token
	ExpiresAt          int64     `json:"expires_at,omitempty"`           // Copilot token expiry
	CreatedAt          time.Time `json:"created_at"`
}

CopilotCredentials holds GitHub OAuth credentials and the short-lived GitHub Copilot API token derived from them.

func (*CopilotCredentials) IsExpired added in v0.75.0

func (c *CopilotCredentials) IsExpired() bool

IsExpired checks if the Copilot API token is expired.

func (*CopilotCredentials) NeedsRefresh added in v0.75.0

func (c *CopilotCredentials) NeedsRefresh() bool

NeedsRefresh reports whether the Copilot API token should be renewed.

type CopilotDeviceCode added in v0.75.0

type CopilotDeviceCode struct {
	DeviceCode      string `json:"device_code"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
}

CopilotDeviceCode contains data returned by GitHub's device-code endpoint.

type CopilotOAuthClient added in v0.75.0

type CopilotOAuthClient struct {
	ClientID      string
	DeviceURL     string
	TokenURL      string
	CopilotURL    string
	Scopes        string
	PollTimeout   time.Duration
	ClientTimeout time.Duration
}

CopilotOAuthClient handles GitHub device-flow OAuth and exchanges the GitHub token for a short-lived GitHub Copilot API token.

The GitHub token comes from GitHub's OAuth device flow. It is then presented to GitHub's internal Copilot token endpoint, which returns the bearer token used by api.githubcopilot.com.

func NewCopilotOAuthClient added in v0.75.0

func NewCopilotOAuthClient() *CopilotOAuthClient

NewCopilotOAuthClient creates a GitHub Copilot OAuth client.

func (*CopilotOAuthClient) ExchangeGitHubToken added in v0.75.0

func (c *CopilotOAuthClient) ExchangeGitHubToken(ctx context.Context, githubToken string) (*CopilotCredentials, error)

ExchangeGitHubToken converts a GitHub OAuth token into a Copilot API token. It is a semantic wrapper over RefreshCopilotToken used by the login flow.

func (*CopilotOAuthClient) PollDeviceToken added in v0.75.0

func (c *CopilotOAuthClient) PollDeviceToken(ctx context.Context, deviceCode *CopilotDeviceCode) (string, error)

PollDeviceToken waits until the user authorizes the device code and returns the resulting GitHub OAuth token.

It follows GitHub's device-flow polling contract: authorization_pending keeps polling, slow_down increases the interval, and polling stops at the earlier of the client timeout or the device-code expiry.

func (*CopilotOAuthClient) RefreshCopilotToken added in v0.75.0

func (c *CopilotOAuthClient) RefreshCopilotToken(ctx context.Context, githubToken string) (*CopilotCredentials, error)

RefreshCopilotToken obtains a fresh short-lived Copilot token from GitHub.

GitHub may return expires_at as either a Unix timestamp or RFC3339 string. parseCopilotExpiry handles both forms and falls back to a conservative 20-minute lifetime when the field is absent or unrecognized.

func (*CopilotOAuthClient) StartDeviceFlow added in v0.75.0

func (c *CopilotOAuthClient) StartDeviceFlow(ctx context.Context) (*CopilotDeviceCode, error)

StartDeviceFlow requests a GitHub device code for browser login.

The returned user code and verification URI are displayed by loginCopilot. GitHub's response may omit interval, so this method normalizes it to the documented five-second default.

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/.kit/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) GetCopilotCredentials added in v0.75.0

func (cm *CredentialManager) GetCopilotCredentials() (*CopilotCredentials, error)

GetCopilotCredentials retrieves stored GitHub Copilot credentials.

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) GetOpenAICredentials added in v0.25.0

func (cm *CredentialManager) GetOpenAICredentials() (*OpenAICredentials, error)

GetOpenAICredentials retrieves stored OpenAI 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) 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) GetValidCopilotAccessToken added in v0.75.0

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

GetValidCopilotAccessToken returns a fresh Copilot API token, renewing it with the stored GitHub OAuth token when needed.

func (*CredentialManager) GetValidCopilotAccessTokenContext added in v0.75.0

func (cm *CredentialManager) GetValidCopilotAccessTokenContext(ctx context.Context) (string, error)

GetValidCopilotAccessTokenContext returns a fresh Copilot API token, renewing it with the stored GitHub OAuth token when needed.

func (*CredentialManager) GetValidOpenAIAccessToken added in v0.25.0

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

GetValidOpenAIAccessToken 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) HasCopilotCredentials added in v0.75.0

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

HasCopilotCredentials checks if valid GitHub Copilot credentials are stored.

func (*CredentialManager) HasOpenAICredentials added in v0.25.0

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

HasOpenAICredentials checks if valid OpenAI 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) RemoveCopilotCredentials added in v0.75.0

func (cm *CredentialManager) RemoveCopilotCredentials() error

RemoveCopilotCredentials removes stored GitHub Copilot credentials.

func (*CredentialManager) RemoveOpenAICredentials added in v0.25.0

func (cm *CredentialManager) RemoveOpenAICredentials() error

RemoveOpenAICredentials removes stored OpenAI 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) SetCopilotOAuthCredentials added in v0.75.0

func (cm *CredentialManager) SetCopilotOAuthCredentials(creds *CopilotCredentials) error

SetCopilotOAuthCredentials stores GitHub Copilot OAuth credentials.

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.

func (*CredentialManager) SetOpenAIOAuthCredentials added in v0.25.0

func (cm *CredentialManager) SetOpenAIOAuthCredentials(creds *OpenAICredentials) error

SetOpenAIOAuthCredentials stores OpenAI 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"`
	OpenAI    *OpenAICredentials    `json:"openai,omitempty"`
	Copilot   *CopilotCredentials   `json:"copilot,omitempty"`
}

CredentialStore holds stored credentials for Anthropic, OpenAI, and GitHub Copilot.

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.

type OpenAICredentials added in v0.25.0

type OpenAICredentials 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
	AccountID    string    `json:"account_id,omitempty"`    // For OAuth (ChatGPT account ID)
	CreatedAt    time.Time `json:"created_at"`
}

OpenAICredentials holds OpenAI 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 (*OpenAICredentials) IsExpired added in v0.25.0

func (c *OpenAICredentials) 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 (*OpenAICredentials) NeedsRefresh added in v0.25.0

func (c *OpenAICredentials) 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 OpenAIOAuthClient added in v0.25.0

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

OpenAIOAuthClient handles OAuth 2.0 authentication flow with OpenAI Codex (ChatGPT Plus/Pro). This uses OpenAI's auth0-based OAuth service for ChatGPT account authentication.

func NewOpenAIOAuthClient added in v0.25.0

func NewOpenAIOAuthClient() *OpenAIOAuthClient

NewOpenAIOAuthClient creates a new OAuth client configured for OpenAI Codex OAuth. This uses the public client ID for CLI applications with PKCE for security.

func (*OpenAIOAuthClient) ExchangeCode added in v0.25.0

func (c *OpenAIOAuthClient) ExchangeCode(code, verifier string) (*OpenAICredentials, 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 OpenAICredentials containing the tokens, expiration, and account ID.

func (*OpenAIOAuthClient) GetAuthorizationURL added in v0.25.0

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

GetAuthorizationURL generates a complete authorization URL for the OAuth flow with PKCE parameters. Returns an AuthData structure containing the URL for user authentication and the PKCE verifier for the subsequent code exchange.

func (*OpenAIOAuthClient) RefreshToken added in v0.25.0

func (c *OpenAIOAuthClient) RefreshToken(refreshToken string) (*OpenAICredentials, error)

RefreshToken refreshes an expired or expiring access token using a refresh token. Returns new OpenAICredentials 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