auth

package
v1.3.24 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProviderGitHubCopilot = "github-copilot"
	ProviderAnthropic     = "anthropic"
)

Variables

View Source
var ProviderPresets = map[string]OAuth2ProviderPreset{
	"github": {
		Name:            "GitHub",
		AuthorizeURL:    "https://github.com/login/oauth/authorize",
		TokenURL:        "https://github.com/login/oauth/access_token",
		DeviceAuthURL:   "https://github.com/login/device/code",
		DefaultScopes:   []string{"read:user", "user:email"},
		DefaultClientID: "Ov23liq0EQyT4VDz3ayn",
		SupportsPKCE:    true,
		SupportsDevice:  true,
	},
	"google": {
		Name:           "Google",
		AuthorizeURL:   "https://accounts.google.com/o/oauth2/v2/auth",
		TokenURL:       "https://oauth2.googleapis.com/token",
		UserInfoURL:    "https://openidconnect.googleapis.com/v1/userinfo",
		OIDCDiscovery:  "https://accounts.google.com/.well-known/openid-configuration",
		DefaultScopes:  []string{"openid", "profile", "email"},
		SupportsPKCE:   true,
		SupportsDevice: false,
	},
	"auth0": {
		Name:           "Auth0",
		AuthorizeURL:   "https://AUTH0_TENANT.auth0.com/authorize",
		TokenURL:       "https://AUTH0_TENANT.auth0.com/oauth/token",
		UserInfoURL:    "https://AUTH0_TENANT.auth0.com/userinfo",
		OIDCDiscovery:  "https://AUTH0_TENANT.auth0.com/.well-known/openid-configuration",
		DefaultScopes:  []string{"openid", "profile", "email"},
		SupportsPKCE:   true,
		SupportsDevice: true,
	},
	"azure": {
		Name:           "Azure AD",
		AuthorizeURL:   "https://login.microsoftonline.com/AZURE_TENANT/oauth2/v2.0/authorize",
		TokenURL:       "https://login.microsoftonline.com/AZURE_TENANT/oauth2/v2.0/token",
		DeviceAuthURL:  "https://login.microsoftonline.com/AZURE_TENANT/oauth2/v2.0/devicecode",
		OIDCDiscovery:  "https://login.microsoftonline.com/AZURE_TENANT/v2.0/.well-known/openid-configuration",
		DefaultScopes:  []string{"openid", "profile", "email"},
		SupportsPKCE:   true,
		SupportsDevice: true,
	},
}

Built-in provider presets.

GitHub has a DefaultClientID embedded because we registered a public OAuth App specifically for ggcode (PKCE-only, no client_secret). This gives users a zero-config experience: just set `provider: "github"` and it works.

Other providers (Google, Auth0, Azure) require users to register their own OAuth App because:

  1. Each OAuth App is bound to specific redirect URIs
  2. Provider terms of service may prohibit shared client_ids
  3. Enterprise providers (Auth0, Azure) have per-tenant URLs

Users can always override DefaultClientID by setting client_id in config.

Functions

func CacheKey added in v1.1.46

func CacheKey(provider, clientID string) string

CacheKey generates a unique cache key from provider and clientID. Different clientIDs for the same provider won't overwrite each other.

func CopilotAPIBaseURL

func CopilotAPIBaseURL(enterpriseURL string) string

func CreateClaudeAPIKey added in v1.1.34

func CreateClaudeAPIKey(ctx context.Context, accessToken string) (string, error)

CreateClaudeAPIKey creates a long-lived API key from an OAuth access token.

func DefaultPath

func DefaultPath() string

func DefaultTokenCacheDir added in v1.1.46

func DefaultTokenCacheDir() string

DefaultTokenCacheDir returns the default cache directory.

func GenerateCodeChallenge added in v1.1.34

func GenerateCodeChallenge(verifier string) string

GenerateCodeChallenge creates a S256 code challenge from a code verifier.

func GenerateCodeVerifier added in v1.1.34

func GenerateCodeVerifier() (string, error)

GenerateCodeVerifier creates a cryptographically random code verifier for PKCE.

func GenerateState added in v1.1.34

func GenerateState() (string, error)

GenerateState creates a random state parameter for OAuth.

func NewTokenProviderFromPreset added in v1.1.46

func NewTokenProviderFromPreset(provider string, clientSecret string, headless bool) (interface {
	GetToken(ctx context.Context) (string, string, time.Time, error)
}, error)

NewTokenProviderFromPreset creates the best TokenProvider for the given provider preset. Prefers PKCE for desktop environments, Device Flow for headless. Set headless=true to force Device Flow.

func NormalizeEnterpriseURL

func NormalizeEnterpriseURL(raw string) (string, error)

func ResolveA2AAuth added in v1.1.46

func ResolveA2AAuth(provider, clientID, issuerURL, scopes string) (authorizeURL, tokenURL, resolvedClientID, resolvedScopes string, err error)

ResolveA2AAuth resolves the provider preset and merges with user config. If provider is set, endpoint URLs and DefaultClientID come from the preset. User can override client_id and scopes. If provider is empty, all fields must be set manually.

func WaitForClaudeAuthCode added in v1.1.34

func WaitForClaudeAuthCode(ctx context.Context, flow *ClaudeOAuthFlow) (string, bool, error)

WaitForClaudeAuthCode waits for the authorization code from the local callback.

Types

type A2AOAuth2Config added in v1.1.46

type A2AOAuth2Config struct {
	ClientID     string
	ClientSecret string // optional; GitHub requires this even with PKCE
	AuthorizeURL string
	TokenURL     string
	Scopes       []string
}

A2AOAuth2Config is the runtime config for A2A OAuth2 authentication.

type ClaudeOAuthFlow added in v1.1.34

type ClaudeOAuthFlow struct {
	AutoURL      string
	ManualURL    string
	CodeVerifier string
	State        string
	Port         int
	// contains filtered or unexported fields
}

ClaudeOAuthFlow holds the state for an in-progress OAuth 2.0 + PKCE flow.

func StartClaudeOAuthFlow added in v1.1.34

func StartClaudeOAuthFlow(_ context.Context) (*ClaudeOAuthFlow, error)

StartClaudeOAuthFlow initiates a new OAuth 2.0 + PKCE flow.

func (*ClaudeOAuthFlow) Close added in v1.1.34

func (f *ClaudeOAuthFlow) Close()

Close shuts down the callback HTTP server.

type ClaudeProfile added in v1.1.34

type ClaudeProfile struct {
	SubscriptionType string
	DisplayName      string
	RateLimitTier    string
}

ClaudeProfile holds user profile information from the Anthropic API.

func FetchClaudeProfile added in v1.1.34

func FetchClaudeProfile(ctx context.Context, accessToken string) (*ClaudeProfile, error)

FetchClaudeProfile fetches the user's profile information.

type ClaudeTokenResponse added in v1.1.34

type ClaudeTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
	Scope        string `json:"scope"`
}

ClaudeTokenResponse holds the parsed token exchange response.

func ExchangeClaudeCodeForTokens added in v1.1.34

func ExchangeClaudeCodeForTokens(ctx context.Context, code, codeVerifier string, isManual bool, port int) (*ClaudeTokenResponse, error)

ExchangeClaudeCodeForTokens exchanges an authorization code for OAuth tokens.

type CopilotDeviceFlow

type CopilotDeviceFlow struct {
	Domain          string
	EnterpriseURL   string
	VerificationURI string
	UserCode        string
	DeviceCode      string
	Interval        time.Duration
}

func StartCopilotDeviceFlow

func StartCopilotDeviceFlow(ctx context.Context, enterpriseURL string) (*CopilotDeviceFlow, error)

type DeviceFlowTokenProvider added in v1.1.46

type DeviceFlowTokenProvider struct {
	Config   A2AOAuth2Config
	Provider string      // provider name for cache key
	Cache    *TokenCache // optional token cache
}

DeviceFlowTokenProvider is a TokenProvider that uses the Device Authorization flow. It caches tokens to disk so they survive restarts.

func (*DeviceFlowTokenProvider) GetToken added in v1.1.46

GetToken returns a cached token if valid, otherwise displays a device code.

type Info

type Info struct {
	ProviderID    string    `json:"provider_id"`
	Type          string    `json:"type"`
	AccessToken   string    `json:"access_token,omitempty"`
	RefreshToken  string    `json:"refresh_token,omitempty"`
	EnterpriseURL string    `json:"enterprise_url,omitempty"`
	ExpiresAt     time.Time `json:"expires_at,omitempty"`
	UpdatedAt     time.Time `json:"updated_at"`
}

func PollCopilotDeviceFlow

func PollCopilotDeviceFlow(ctx context.Context, flow *CopilotDeviceFlow) (*Info, error)

func RefreshClaudeToken added in v1.1.34

func RefreshClaudeToken(ctx context.Context, refreshToken string) (*Info, error)

RefreshClaudeToken refreshes an expired access token using the refresh token.

func (*Info) IsExpired added in v1.1.34

func (i *Info) IsExpired() bool

IsExpired returns true if the token is expired or will expire within 5 minutes.

type MTLSConfig added in v1.1.46

type MTLSConfig struct {
	CertFile string
	KeyFile  string
	CAFile   string
}

MTLSConfig holds the runtime mTLS configuration.

func (*MTLSConfig) BuildTLSConfig added in v1.1.46

func (c *MTLSConfig) BuildTLSConfig() (*tls.Config, error)

BuildTLSConfig creates a *tls.Config for mutual TLS.

type OAuth2ProviderPreset added in v1.1.46

type OAuth2ProviderPreset struct {
	Name            string   // display name
	AuthorizeURL    string   // authorization endpoint
	TokenURL        string   // token endpoint
	DeviceAuthURL   string   // device authorization endpoint (empty if unsupported)
	UserInfoURL     string   // userinfo endpoint (for OIDC)
	OIDCDiscovery   string   // /.well-known/openid-configuration URL (empty if not OIDC)
	DefaultScopes   []string // recommended scopes
	DefaultClientID string   // pre-registered public client_id for zero-config experience
	SupportsPKCE    bool     // Authorization Code + PKCE
	SupportsDevice  bool     // Device Authorization Flow
}

OAuth2ProviderPreset contains the public configuration for an OAuth2 provider.

func ResolveProviderPreset added in v1.1.46

func ResolveProviderPreset(provider string) *OAuth2ProviderPreset

ResolveProviderPreset returns the preset for the given provider name. Returns nil if the provider is not found.

type PKCEToken added in v1.1.46

type PKCEToken struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type"`
	Expiry       time.Time `json:"expiry,omitempty"`
	Scope        string    `json:"scope,omitempty"`
}

PKCEToken holds tokens obtained via OAuth2 + PKCE flow.

func StartDeviceFlow added in v1.1.46

func StartDeviceFlow(ctx context.Context, cfg A2AOAuth2Config) (*PKCEToken, error)

StartDeviceFlow starts a Device Authorization flow. No client_secret or browser needed. User visits a URL and enters a code.

func StartPKCEFlow added in v1.1.46

func StartPKCEFlow(ctx context.Context, cfg A2AOAuth2Config) (*PKCEToken, error)

StartPKCEFlow starts an Authorization Code + PKCE flow. It opens a browser for user consent and waits for the callback. Returns the tokens on success.

type PKCETokenProvider added in v1.1.46

type PKCETokenProvider struct {
	Config   A2AOAuth2Config
	Provider string      // provider name for cache key (e.g. "github")
	Cache    *TokenCache // optional token cache
}

PKCETokenProvider is a TokenProvider that uses OAuth2 + PKCE authorization code flow. It caches tokens to disk so they survive restarts.

func (*PKCETokenProvider) GetToken added in v1.1.46

func (p *PKCETokenProvider) GetToken(ctx context.Context) (string, string, time.Time, error)

GetToken returns a cached token if valid, otherwise opens a browser for authorization.

type Store

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

func DefaultStore

func DefaultStore() *Store

func NewStore

func NewStore(path string) *Store

func (*Store) Delete

func (s *Store) Delete(providerID string) error

func (*Store) HasUsableToken

func (s *Store) HasUsableToken(providerID string) (bool, error)

func (*Store) Load

func (s *Store) Load(providerID string) (*Info, error)

func (*Store) Save

func (s *Store) Save(info *Info) error

type TokenCache added in v1.1.46

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

TokenCache persists OAuth2 tokens to disk so they survive restarts. File location: ~/.ggcode/oauth-tokens/{provider}.json

func NewTokenCache added in v1.1.46

func NewTokenCache(dir string) *TokenCache

NewTokenCache creates a token cache in the given directory.

func (*TokenCache) Delete added in v1.1.46

func (tc *TokenCache) Delete(provider string) error

Delete removes a cached token.

func (*TokenCache) Load added in v1.1.46

func (tc *TokenCache) Load(provider string) *PKCEToken

Load reads a cached token for the given provider. Returns nil if no cache exists or if the token is expired.

func (*TokenCache) LoadValid added in v1.1.46

func (tc *TokenCache) LoadValid(provider string) *PKCEToken

LoadValid reads a cached token that is still valid (not expired). Returns nil if expired or no cache.

func (*TokenCache) Save added in v1.1.46

func (tc *TokenCache) Save(provider string, token *PKCEToken, clientID string) error

Save writes a token to the cache.

type TokenValidator added in v1.1.46

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

TokenValidator validates incoming Bearer tokens on the A2A server side. Supports:

  • JWT tokens: verifies signature (via JWKS or HMAC), expiration, issuer, audience
  • Opaque tokens: uses token introspection endpoint

func NewTokenValidator added in v1.1.46

func NewTokenValidator(clientID, issuerURL string, opts ...ValidatorOption) (*TokenValidator, error)

NewTokenValidator creates a validator for the given OAuth2/OIDC issuer.

func (*TokenValidator) ValidateToken added in v1.1.46

func (v *TokenValidator) ValidateToken(ctx context.Context, token string) (map[string]interface{}, error)

ValidateToken checks if a Bearer token is valid. For JWT tokens, it verifies signature, expiration, issuer, and audience. For opaque tokens, it uses token introspection.

type ValidatorOption added in v1.3.19

type ValidatorOption func(*TokenValidator)

ValidatorOption configures a TokenValidator.

func WithHMACSecret added in v1.3.19

func WithHMACSecret(secret string) ValidatorOption

WithHMACSecret sets the HMAC signing key. This must be a secret shared between the A2A server and the token issuer — never use clientID which is public.

func WithValidIssuers added in v1.3.19

func WithValidIssuers(issuers []string) ValidatorOption

WithValidIssuers sets additional allowed issuer URLs. The configured issuerURL is always allowed; this adds extras for providers that return different issuers in different contexts (e.g. tenant-specific URLs).

Jump to

Keyboard shortcuts

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