oauth

package
v0.0.0-...-9e5e0b2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oauth provides OAuth token management for LLM providers.

Index

Constants

View Source
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

View Source
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

func CloudCodeStreamEndpoint(baseURL string) string

CloudCodeStreamEndpoint returns the streaming endpoint for Cloud Code.

func ConvertToCloudCodeModel

func ConvertToCloudCodeModel(model string) string

ConvertToCloudCodeModel maps common model names to Cloud Code model identifiers.

func CopilotSKUToTier

func CopilotSKUToTier(sku string) (string, string)

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

func GetCopilotToken(ctx context.Context, githubToken string) (string, time.Time, string, error)

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

func ParseCopilotSKU(tokenStr string) string

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

func RewriteModelInBody(body []byte, newModel string) ([]byte, error)

RewriteModelInBody replaces the model field in the request body.

func SetCloudCodeHeaders

func SetCloudCodeHeaders(headers map[string]string, providerType, version string)

SetCloudCodeHeaders sets the required headers for Cloud Code API requests.

func UnwrapCloudCodeSSEData

func UnwrapCloudCodeSSEData(data []byte) ([]byte, error)

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

func WrapCloudCodeRequest(body []byte, projectID, userAgent string) ([]byte, error)

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.

func (*CallbackServer) Start

func (s *CallbackServer) Start(ctx context.Context) (string, error)

Start starts the callback server and blocks until a callback is received or ctx is cancelled. Returns the authorization code or an error.

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

func NewFileStore(dataDir string) (*FileStore, error)

NewFileStore creates a new file-based OAuth token store.

func (*FileStore) DeleteToken

func (s *FileStore) DeleteToken(providerID, tokenID string) error

DeleteToken removes a specific token for the given provider.

func (*FileStore) ListTokens

func (s *FileStore) ListTokens() (map[string]*Token, error)

ListTokens returns all stored tokens.

func (*FileStore) LoadToken

func (s *FileStore) LoadToken(providerID, tokenID string) (*Token, error)

LoadToken retrieves a specific token for the given provider.

func (*FileStore) LoadTokenByEmail

func (s *FileStore) 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 (*FileStore) LoadTokens

func (s *FileStore) LoadTokens(providerID string) ([]*Token, error)

LoadTokens retrieves all tokens for the given provider.

func (*FileStore) SaveToken

func (s *FileStore) SaveToken(providerID string, token *Token) error

SaveToken persists a token for the given provider.

type FlowType

type FlowType string

FlowType represents the OAuth flow type.

const (
	FlowTypeAuthCode   FlowType = "authorization_code"
	FlowTypeDeviceCode FlowType = "device_code"
)

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 (m *LazyManager) CompleteDeviceFlow(ctx context.Context, deviceCode string, interval int) (*Token, error)

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 (m *LazyManager) HandleCallback(ctx context.Context, state, code string) (*Token, error)

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

func (m *Manager) Disconnect(providerID, tokenID string) error

Disconnect revokes and removes a specific OAuth token.

func (*Manager) GetAccessToken

func (m *Manager) GetAccessToken(providerID string) (string, error)

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

func (m *Manager) GetAccessTokenByID(providerID, tokenID string) (string, error)

GetAccessTokenByID returns a valid access token for a specific token ID.

func (*Manager) GetCopilotAccessToken

func (m *Manager) GetCopilotAccessToken(providerID string) (string, error)

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

func (m *Manager) GetCopilotEndpoint() string

GetCopilotEndpoint returns the Copilot API endpoint from the token response. Returns empty string if not available (will use default).

func (*Manager) GetToken

func (m *Manager) GetToken(providerID, tokenID string) (*Token, error)

GetToken returns the full token for a specific provider and token ID.

func (*Manager) GetTokens

func (m *Manager) GetTokens(providerID string) ([]*Token, error)

GetTokens returns all tokens for a provider.

func (*Manager) HandleCallback

func (m *Manager) HandleCallback(ctx context.Context, state, code string) (*Token, error)

HandleCallback processes an OAuth callback with an authorization code.

func (*Manager) ImportToken

func (m *Manager) ImportToken(token *Token) error

ImportToken imports an externally obtained token (e.g., from IDE scan).

func (*Manager) ListTokens

func (m *Manager) ListTokens() (map[string]*Token, error)

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.

func (*Manager) SetPort

func (m *Manager) SetPort(port int)

SetPort sets the actual server port for OAuth callbacks.

func (*Manager) StartAuth

func (m *Manager) StartAuth(ctx context.Context, providerID, providerType string) (*AuthStartResult, error)

StartAuth begins an OAuth flow for the given provider type. providerID is the provider pool ID to associate the token with.

func (*Manager) StartAutoRefresh

func (m *Manager) StartAutoRefresh(ctx context.Context, interval time.Duration)

StartAutoRefresh starts a background loop that periodically refreshes OAuth tokens. Safe to call multiple times; only one loop will run.

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.

func (*SQLiteTokenStore) SaveToken

func (s *SQLiteTokenStore) SaveToken(providerID string, token *Token) error

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.

func (*Token) Expired

func (t *Token) Expired() bool

Expired returns true if the access token has expired (with 60s buffer).

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.

Jump to

Keyboard shortcuts

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