Documentation
¶
Overview ¶
Package oauth provides OAuth token management for LLM providers.
Index ¶
- Constants
- Variables
- func AllProviderConfigs() map[string]*ProviderConfig
- func CloudCodeStreamEndpoint(baseURL string) string
- func ConvertToCloudCodeModel(model string) string
- func CopilotSKUToTier(sku string) (string, string)
- func GetCopilotToken(ctx context.Context, githubToken string) (string, time.Time, string, error)
- func ParseCopilotSKU(tokenStr string) string
- func PollDeviceToken(ctx context.Context, cfg *ProviderConfig, deviceCode string, interval int) (*tokenResponse, error)
- func RewriteModelInBody(body []byte, newModel string) ([]byte, error)
- func SetCloudCodeHeaders(headers map[string]string, providerType, version string)
- func UnwrapCloudCodeSSEData(data []byte) ([]byte, error)
- func WrapCloudCodeRequest(body []byte, projectID, userAgent string) ([]byte, error)
- type AuthStartResult
- type CallbackServer
- type DeviceCodeResponse
- type FileStore
- func (s *FileStore) DeleteToken(providerID, tokenID string) error
- func (s *FileStore) ListTokens() (map[string]*Token, error)
- func (s *FileStore) LoadToken(providerID, tokenID string) (*Token, error)
- func (s *FileStore) LoadTokenByEmail(providerID, email string) (*Token, error)
- func (s *FileStore) LoadTokens(providerID string) ([]*Token, error)
- func (s *FileStore) SaveToken(providerID string, token *Token) error
- type FlowType
- type LazyManager
- func (m *LazyManager) CompleteDeviceFlow(ctx context.Context, deviceCode string, interval int) (*Token, error)
- func (m *LazyManager) Disconnect(providerID, tokenID string) error
- func (m *LazyManager) GetAccessToken(providerID string) (string, error)
- func (m *LazyManager) GetAccessTokenByID(providerID, tokenID string) (string, error)
- func (m *LazyManager) GetCopilotAccessToken(providerID string) (string, error)
- func (m *LazyManager) GetCopilotEndpoint() string
- func (m *LazyManager) GetTokens(providerID string) ([]*Token, error)
- func (m *LazyManager) HandleCallback(ctx context.Context, state, code string) (*Token, error)
- func (m *LazyManager) ImportToken(token *Token) error
- func (m *LazyManager) IsReady() bool
- func (m *LazyManager) OnReady(cb func(*Manager))
- func (m *LazyManager) SetPort(port int)
- func (m *LazyManager) StartAuth(ctx context.Context, providerID, providerType string) (*AuthStartResult, error)
- func (m *LazyManager) StartAutoRefresh(ctx context.Context, interval time.Duration)
- func (m *LazyManager) WarmAsync()
- type Manager
- func (m *Manager) CleanupPending()
- func (m *Manager) CompleteDeviceFlow(ctx context.Context, deviceCode string, interval int) (*Token, error)
- func (m *Manager) Disconnect(providerID, tokenID string) error
- func (m *Manager) GetAccessToken(providerID string) (string, error)
- func (m *Manager) GetAccessTokenByID(providerID, tokenID string) (string, error)
- func (m *Manager) GetCopilotAccessToken(providerID string) (string, error)
- func (m *Manager) GetCopilotEndpoint() string
- func (m *Manager) GetToken(providerID, tokenID string) (*Token, error)
- func (m *Manager) GetTokens(providerID string) ([]*Token, error)
- func (m *Manager) HandleCallback(ctx context.Context, state, code string) (*Token, error)
- func (m *Manager) ImportToken(token *Token) error
- func (m *Manager) ListTokens() (map[string]*Token, error)
- func (m *Manager) RefreshAllTokens()
- func (m *Manager) SetPort(port int)
- func (m *Manager) StartAuth(ctx context.Context, providerID, providerType string) (*AuthStartResult, error)
- func (m *Manager) StartAutoRefresh(ctx context.Context, interval time.Duration)
- type ModelQuotaInfo
- type OAuthQuotaInfo
- type ProviderConfig
- type RuntimeManager
- type SQLiteTokenStore
- func (s *SQLiteTokenStore) Deduplicate() error
- func (s *SQLiteTokenStore) DeleteToken(providerID, tokenID string) error
- func (s *SQLiteTokenStore) ListTokens() (map[string]*Token, error)
- func (s *SQLiteTokenStore) LoadToken(providerID, tokenID string) (*Token, error)
- func (s *SQLiteTokenStore) LoadTokenByEmail(providerID, email string) (*Token, error)
- func (s *SQLiteTokenStore) LoadTokens(providerID string) ([]*Token, error)
- func (s *SQLiteTokenStore) MigrateFromJSON(jsonPath string) error
- func (s *SQLiteTokenStore) SaveToken(providerID string, token *Token) error
- type Token
- type TokenStore
Constants ¶
const ( // EnvAntigravityClientSecret overrides Google Antigravity OAuth client secret. EnvAntigravityClientSecret = "ZIMA_OAUTH_ANTIGRAVITY_CLIENT_SECRET" // EnvGeminiCLIClientSecret overrides Gemini CLI OAuth client secret. EnvGeminiCLIClientSecret = "ZIMA_OAUTH_GEMINI_CLI_CLIENT_SECRET" )
Variables ¶
var ErrTokenExpiredReconnectRequired = errors.New("oauth token expired and reconnect is required")
Functions ¶
func AllProviderConfigs ¶
func AllProviderConfigs() map[string]*ProviderConfig
AllProviderConfigs returns all supported OAuth provider configs.
func CloudCodeStreamEndpoint ¶
CloudCodeStreamEndpoint returns the streaming endpoint for Cloud Code.
func ConvertToCloudCodeModel ¶
ConvertToCloudCodeModel maps common model names to Cloud Code model identifiers.
func CopilotSKUToTier ¶
CopilotSKUToTier maps a Copilot SKU string to a display tier and name. Known SKUs: copilot_for_individual, copilot_for_business_seat, copilot_enterprise, free_educational, copilot_free, copilot_for_individual_pro_plus
func GetCopilotToken ¶
GetCopilotToken exchanges a GitHub OAuth token for a Copilot-specific token. GitHub Copilot requires a separate token obtained from the Copilot API. Returns: token, expiry time, API endpoint, error
func ParseCopilotSKU ¶
ParseCopilotSKU extracts the sku field from a Copilot token string. Token format: "tid=...;exp=...;sku=copilot_individual;..."
func PollDeviceToken ¶
func PollDeviceToken(ctx context.Context, cfg *ProviderConfig, deviceCode string, interval int) (*tokenResponse, error)
PollDeviceToken polls GitHub for the access token after the user authorizes. Blocks until the user completes auth, the code expires, or ctx is cancelled.
func RewriteModelInBody ¶
RewriteModelInBody replaces the model field in the request body.
func SetCloudCodeHeaders ¶
SetCloudCodeHeaders sets the required headers for Cloud Code API requests.
func UnwrapCloudCodeSSEData ¶
UnwrapCloudCodeSSEData extracts the inner response data from a Cloud Code SSE data line. Cloud Code SSE format: data: {"candidates":[{"content":{"parts":[{"text":"..."}]}}]} We need to convert this to OpenAI SSE format.
func WrapCloudCodeRequest ¶
WrapCloudCodeRequest wraps an OpenAI-format request body in a Cloud Code envelope.
Input (OpenAI format):
{"model":"claude-opus-4-6","messages":[...],"stream":true}
Output (Cloud Code format):
{"project":"<projectID>","model":"claude-opus-4-6","request":{...},"userAgent":"blue","requestType":"agent"}
Types ¶
type AuthStartResult ¶
type AuthStartResult struct {
// For authorization code flow
AuthURL string `json:"auth_url,omitempty"`
State string `json:"state,omitempty"`
// For device code flow
DeviceCode string `json:"device_code,omitempty"`
UserCode string `json:"user_code,omitempty"`
VerificationURI string `json:"verification_uri,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Interval int `json:"interval,omitempty"`
}
AuthStartResult is returned when starting an OAuth flow.
type CallbackServer ¶
type CallbackServer struct {
// contains filtered or unexported fields
}
CallbackServer runs a temporary local HTTP server to capture OAuth callbacks.
func NewCallbackServer ¶
func NewCallbackServer(port int, path string) *CallbackServer
NewCallbackServer creates a callback server on the given port and path.
func (*CallbackServer) RedirectURI ¶
func (s *CallbackServer) RedirectURI() string
RedirectURI returns the full redirect URI for this callback server.
type DeviceCodeResponse ¶
type DeviceCodeResponse 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"`
}
DeviceCodeResponse is the response from the device code request.
func RequestDeviceCode ¶
func RequestDeviceCode(ctx context.Context, cfg *ProviderConfig) (*DeviceCodeResponse, error)
RequestDeviceCode initiates the GitHub device code flow.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore persists OAuth tokens to a JSON file on disk.
func NewFileStore ¶
NewFileStore creates a new file-based OAuth token store.
func (*FileStore) DeleteToken ¶
DeleteToken removes a specific token for the given provider.
func (*FileStore) ListTokens ¶
ListTokens returns all stored tokens.
func (*FileStore) LoadTokenByEmail ¶
LoadTokenByEmail loads an OAuth token by email address for a given provider. This is used to find existing tokens when re-authenticating to avoid duplicates.
func (*FileStore) LoadTokens ¶
LoadTokens retrieves all tokens for the given provider.
type LazyManager ¶
type LazyManager struct {
// contains filtered or unexported fields
}
LazyManager defers OAuth manager construction until first use or an explicit warmup. Initialization retries on failure so transient startup DB contention does not permanently disable OAuth features for the process lifetime.
func NewLazyManager ¶
func NewLazyManager(initFn func() (*Manager, error)) *LazyManager
NewLazyManager creates a new lazy OAuth manager wrapper.
func (*LazyManager) CompleteDeviceFlow ¶
func (*LazyManager) Disconnect ¶
func (m *LazyManager) Disconnect(providerID, tokenID string) error
func (*LazyManager) GetAccessToken ¶
func (m *LazyManager) GetAccessToken(providerID string) (string, error)
func (*LazyManager) GetAccessTokenByID ¶
func (m *LazyManager) GetAccessTokenByID(providerID, tokenID string) (string, error)
func (*LazyManager) GetCopilotAccessToken ¶
func (m *LazyManager) GetCopilotAccessToken(providerID string) (string, error)
func (*LazyManager) GetCopilotEndpoint ¶
func (m *LazyManager) GetCopilotEndpoint() string
func (*LazyManager) GetTokens ¶
func (m *LazyManager) GetTokens(providerID string) ([]*Token, error)
func (*LazyManager) HandleCallback ¶
func (*LazyManager) ImportToken ¶
func (m *LazyManager) ImportToken(token *Token) error
func (*LazyManager) IsReady ¶
func (m *LazyManager) IsReady() bool
IsReady reports whether the real OAuth manager has been initialized successfully.
func (*LazyManager) OnReady ¶
func (m *LazyManager) OnReady(cb func(*Manager))
OnReady registers a callback that runs once the real manager is available.
func (*LazyManager) SetPort ¶
func (m *LazyManager) SetPort(port int)
SetPort stores the callback port and applies it immediately when the manager is ready.
func (*LazyManager) StartAuth ¶
func (m *LazyManager) StartAuth(ctx context.Context, providerID, providerType string) (*AuthStartResult, error)
func (*LazyManager) StartAutoRefresh ¶
func (m *LazyManager) StartAutoRefresh(ctx context.Context, interval time.Duration)
StartAutoRefresh records the refresh policy and applies it once the manager is ready.
func (*LazyManager) WarmAsync ¶
func (m *LazyManager) WarmAsync()
WarmAsync starts best-effort initialization in the background.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager handles OAuth token lifecycle for LLM providers.
func NewManager ¶
func NewManager(store TokenStore) *Manager
NewManager creates a new OAuth manager.
func (*Manager) CleanupPending ¶
func (m *Manager) CleanupPending()
CleanupPending removes expired pending auth states.
func (*Manager) CompleteDeviceFlow ¶
func (m *Manager) CompleteDeviceFlow(ctx context.Context, deviceCode string, interval int) (*Token, error)
CompleteDeviceFlow polls for the device code flow completion.
func (*Manager) Disconnect ¶
Disconnect revokes and removes a specific OAuth token.
func (*Manager) GetAccessToken ¶
GetAccessToken returns a valid access token for the provider, refreshing if needed. It tries all tokens for the provider and returns the first valid one.
func (*Manager) GetAccessTokenByID ¶
GetAccessTokenByID returns a valid access token for a specific token ID.
func (*Manager) GetCopilotAccessToken ¶
GetCopilotAccessToken returns a Copilot-specific JWT for the provider. GitHub Copilot API requires exchanging the GitHub OAuth token for a short-lived Copilot JWT via https://api.github.com/copilot_internal/v2/token. The JWT is cached until 5 minutes before expiry.
func (*Manager) GetCopilotEndpoint ¶
GetCopilotEndpoint returns the Copilot API endpoint from the token response. Returns empty string if not available (will use default).
func (*Manager) HandleCallback ¶
HandleCallback processes an OAuth callback with an authorization code.
func (*Manager) ImportToken ¶
ImportToken imports an externally obtained token (e.g., from IDE scan).
func (*Manager) ListTokens ¶
ListTokens returns all stored tokens.
func (*Manager) RefreshAllTokens ¶
func (m *Manager) RefreshAllTokens()
RefreshAllTokens tries to refresh all stored OAuth tokens that are expired or near expiry. Invalid/unrefreshable tokens are pruned by getOrRefreshToken.
type ModelQuotaInfo ¶
type ModelQuotaInfo struct {
Model string `json:"model"`
RemainingPercent int `json:"remaining_percent"`
ResetTime string `json:"reset_time,omitempty"`
}
ModelQuotaInfo represents per-model remaining quota.
type OAuthQuotaInfo ¶
type OAuthQuotaInfo struct {
ProviderType string `json:"provider_type"`
Tier string `json:"tier"`
TierName string `json:"tier_name"`
ModelQuotas []ModelQuotaInfo `json:"model_quotas,omitempty"`
Error string `json:"error,omitempty"`
FetchedAt int64 `json:"fetched_at"`
}
OAuthQuotaInfo is the unified response for OAuth provider quota/tier queries.
func FetchCloudCodeQuota ¶
func FetchCloudCodeQuota(ctx context.Context, accessToken, projectID, providerType string) (*OAuthQuotaInfo, error)
FetchCloudCodeQuota fetches subscription tier and per-model quota from Google Cloud Code API.
type ProviderConfig ¶
type ProviderConfig struct {
ID string // "antigravity", "gemini-cli", "copilot"
Name string // Display name
FlowType FlowType // authorization_code or device_code
ClientID string
ClientSecret string
AuthURL string
TokenURL string
UserInfoURL string
Scopes []string
RedirectPort int // Local callback port (for auth code flow)
RedirectPath string // Callback path
// Google Cloud Code specific
CloudCodeEndpoints []string // Ordered list of endpoints to try
LoadCodeAssistURL string // Project discovery endpoint
// GitHub specific
DeviceCodeURL string // For device code flow
// API endpoint (for providers like Codex where API URL differs from auth URL)
APIEndpoint string
}
ProviderConfig holds OAuth configuration for a specific LLM provider.
func AntigravityConfig ¶
func AntigravityConfig() *ProviderConfig
AntigravityConfig returns the OAuth config for Google Antigravity.
func CodexConfig ¶
func CodexConfig() *ProviderConfig
CodexConfig returns the OAuth config for OpenAI Codex CLI.
func CopilotConfig ¶
func CopilotConfig() *ProviderConfig
CopilotConfig returns the OAuth config for GitHub Copilot.
func GeminiCLIConfig ¶
func GeminiCLIConfig() *ProviderConfig
GeminiCLIConfig returns the OAuth config for Google Gemini CLI.
func GetProviderConfig ¶
func GetProviderConfig(providerType string) *ProviderConfig
GetProviderConfig returns the OAuth config for a provider type.
type RuntimeManager ¶
type RuntimeManager interface {
StartAuth(ctx context.Context, providerID, providerType string) (*AuthStartResult, error)
HandleCallback(ctx context.Context, state, code string) (*Token, error)
CompleteDeviceFlow(ctx context.Context, deviceCode string, interval int) (*Token, error)
GetAccessToken(providerID string) (string, error)
GetCopilotAccessToken(providerID string) (string, error)
GetCopilotEndpoint() string
GetAccessTokenByID(providerID, tokenID string) (string, error)
GetTokens(providerID string) ([]*Token, error)
Disconnect(providerID, tokenID string) error
ImportToken(token *Token) error
}
RuntimeManager is the OAuth manager surface used by provider/pipeline runtime code.
type SQLiteTokenStore ¶
type SQLiteTokenStore struct {
// contains filtered or unexported fields
}
SQLiteTokenStore persists OAuth tokens in a SQLite database.
func NewSQLiteTokenStore ¶
func NewSQLiteTokenStore(db *sql.DB) (*SQLiteTokenStore, error)
NewSQLiteTokenStore creates a new SQLite-backed OAuth token store.
func NewSQLiteTokenStoreWithReadDB ¶
func NewSQLiteTokenStoreWithReadDB(writeDB, readDB *sql.DB) (*SQLiteTokenStore, error)
NewSQLiteTokenStoreWithReadDB creates a new SQLite-backed OAuth token store with separate write and read database handles.
func (*SQLiteTokenStore) Deduplicate ¶
func (s *SQLiteTokenStore) Deduplicate() error
Deduplicate removes duplicate tokens for each provider, keeping only the most recent one per email. This can be called to clean up any duplicates that may have been created due to bugs.
func (*SQLiteTokenStore) DeleteToken ¶
func (s *SQLiteTokenStore) DeleteToken(providerID, tokenID string) error
func (*SQLiteTokenStore) ListTokens ¶
func (s *SQLiteTokenStore) ListTokens() (map[string]*Token, error)
func (*SQLiteTokenStore) LoadToken ¶
func (s *SQLiteTokenStore) LoadToken(providerID, tokenID string) (*Token, error)
func (*SQLiteTokenStore) LoadTokenByEmail ¶
func (s *SQLiteTokenStore) LoadTokenByEmail(providerID, email string) (*Token, error)
LoadTokenByEmail loads an OAuth token by email address for a given provider. This is used to find existing tokens when re-authenticating to avoid duplicates.
func (*SQLiteTokenStore) LoadTokens ¶
func (s *SQLiteTokenStore) LoadTokens(providerID string) ([]*Token, error)
func (*SQLiteTokenStore) MigrateFromJSON ¶
func (s *SQLiteTokenStore) MigrateFromJSON(jsonPath string) error
MigrateFromJSON imports tokens from a legacy JSON file into this store.
type Token ¶
type Token struct {
ID string `json:"id"`
ProviderID string `json:"provider_id"`
ProviderType string `json:"provider_type"` // "antigravity", "gemini-cli", "copilot"
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenExpiry time.Time `json:"token_expiry"`
Scopes []string `json:"scopes,omitempty"`
Email string `json:"email,omitempty"`
ProjectID string `json:"project_id,omitempty"` // Google Cloud Code project
Endpoint string `json:"endpoint,omitempty"` // API endpoint URL
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Token represents a stored OAuth token with metadata.
type TokenStore ¶
type TokenStore interface {
SaveToken(providerID string, token *Token) error
LoadToken(providerID, tokenID string) (*Token, error)
LoadTokenByEmail(providerID, email string) (*Token, error)
LoadTokens(providerID string) ([]*Token, error)
DeleteToken(providerID, tokenID string) error
ListTokens() (map[string]*Token, error)
}
TokenStore is the interface for OAuth token persistence.