oauth

package
v0.0.0-...-c5791a9 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultClientID is the OAuth client ID for Claude Code.
	DefaultClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"

	// DefaultAuthorizeURL is the OAuth authorization endpoint.
	// Uses claude.com/cai/ path to match official Claude Code's attribution flow.
	DefaultAuthorizeURL = "https://claude.com/cai/oauth/authorize"

	// DefaultTokenURL is the OAuth token exchange endpoint.
	DefaultTokenURL = "https://platform.claude.com/v1/oauth/token"

	// DefaultProfileURL is the user profile endpoint.
	DefaultProfileURL = "https://api.anthropic.com/api/oauth/profile"

	// DefaultAPIKeyURL is the endpoint to create an API key from an OAuth token.
	DefaultAPIKeyURL = "https://api.anthropic.com/api/oauth/claude_cli/create_api_key"

	// DefaultManualRedirectURI is used when browser redirect isn't available.
	DefaultManualRedirectURI = "https://platform.claude.com/oauth/code/callback"
)

Variables

View Source
var ConsoleScopes = []string{
	"org:create_api_key",
	"user:profile",
}

ConsoleScopes for Anthropic Console (API key generation).

View Source
var DefaultScopes = []string{
	"user:profile",
	"user:inference",
	"user:sessions:claude_code",
	"user:mcp_servers",
	"user:file_upload",
}

DefaultScopes for Claude.ai subscribers.

Functions

func GenerateCodeChallenge

func GenerateCodeChallenge(verifier string) string

GenerateCodeChallenge computes the S256 PKCE code challenge from a verifier.

func GenerateCodeVerifier

func GenerateCodeVerifier() (string, error)

GenerateCodeVerifier creates a PKCE code verifier (32 random bytes, base64url encoded).

func GenerateState

func GenerateState() (string, error)

GenerateState creates a random state parameter for CSRF protection.

Types

type Account

type Account struct {
	UUID             string `json:"uuid"`
	EmailAddress     string `json:"emailAddress"`
	OrganizationUUID string `json:"organizationUuid"`
}

Account holds OAuth account info from the token exchange response.

type AuthCodeListener

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

AuthCodeListener is a temporary HTTP server that captures the OAuth callback.

func NewAuthCodeListener

func NewAuthCodeListener() *AuthCodeListener

NewAuthCodeListener creates a listener for OAuth redirects.

func (*AuthCodeListener) Port

func (l *AuthCodeListener) Port() int

Port returns the port the listener is running on.

func (*AuthCodeListener) RedirectURI

func (l *AuthCodeListener) RedirectURI() string

RedirectURI returns the callback URL.

func (*AuthCodeListener) Shutdown

func (l *AuthCodeListener) Shutdown()

Shutdown stops the listener.

func (*AuthCodeListener) Start

func (l *AuthCodeListener) Start() (int, error)

Start begins listening on a random available port. Returns the port number.

func (*AuthCodeListener) WaitForCode

func (l *AuthCodeListener) WaitForCode(ctx context.Context, state string) (string, error)

WaitForCode blocks until the OAuth redirect is received or context is cancelled.

type Client

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

Client handles OAuth token operations.

func NewClient

func NewClient(cfg Config) *Client

NewClient creates a new OAuth client with the given config.

func (*Client) BuildAuthorizeURL

func (c *Client) BuildAuthorizeURL(challenge, state, redirectURI string) string

BuildAuthorizeURL constructs the OAuth authorization URL with PKCE parameters.

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(accessToken string) (string, error)

CreateAPIKey exchanges an OAuth access token for a persistent API key.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(code, verifier, redirectURI, state string) (*Tokens, error)

ExchangeCode exchanges an authorization code for tokens.

func (*Client) FetchProfile

func (c *Client) FetchProfile(accessToken string) (*Profile, error)

FetchProfile retrieves the user profile using an access token.

func (*Client) RefreshToken

func (c *Client) RefreshToken(refreshToken string, scopes []string) (*Tokens, error)

RefreshToken refreshes an expired access token.

type Config

type Config struct {
	ClientID     string
	AuthorizeURL string
	TokenURL     string
	ProfileURL   string
	APIKeyURL    string
	Scopes       []string
}

Config holds OAuth configuration, which can be overridden via env vars.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the standard OAuth config with env var overrides.

type Profile

type Profile struct {
	Name             string `json:"name,omitempty"`
	Email            string `json:"email,omitempty"`
	SubscriptionType string `json:"subscription_type,omitempty"`
	RateLimitTier    string `json:"rate_limit_tier,omitempty"`
}

Profile holds user profile info from the profile endpoint.

type Service

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

Service orchestrates the full OAuth PKCE login flow.

func NewService

func NewService(cfg Config) *Service

NewService creates a new OAuth service.

func (*Service) Login

func (s *Service) Login(ctx context.Context) (*Tokens, error)

Login performs the full OAuth PKCE flow: 1. Generate PKCE verifier + challenge 2. Start local callback server 3. Open browser to authorize URL 4. Wait for callback with auth code 5. Exchange code for tokens 6. Fetch user profile

func (*Service) RefreshIfNeeded

func (s *Service) RefreshIfNeeded(tokens *Tokens) (*Tokens, bool, error)

RefreshIfNeeded checks token expiry and refreshes if needed.

type TokenExchangeResponse

type TokenExchangeResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
	Scope        string `json:"scope"`
	TokenType    string `json:"token_type"`
	Account      *struct {
		UUID             string `json:"uuid"`
		EmailAddress     string `json:"email_address"`
		OrganizationUUID string `json:"organization_uuid"`
	} `json:"account,omitempty"`
}

TokenExchangeResponse is the raw response from /v1/oauth/token.

type Tokens

type Tokens struct {
	AccessToken      string    `json:"accessToken"`
	RefreshToken     string    `json:"refreshToken,omitempty"`
	ExpiresAt        time.Time `json:"expiresAt,omitempty"`
	Scopes           []string  `json:"scopes,omitempty"`
	SubscriptionType string    `json:"subscriptionType,omitempty"` // pro, max, team, enterprise
	RateLimitTier    string    `json:"rateLimitTier,omitempty"`
	Account          *Account  `json:"tokenAccount,omitempty"`
	Profile          *Profile  `json:"profile,omitempty"`
	APIKey           string    `json:"apiKey,omitempty"` // API key created from OAuth token
}

Tokens holds OAuth token data returned from the token endpoint.

func (*Tokens) IsExpired

func (t *Tokens) IsExpired(buffer time.Duration) bool

IsExpired reports whether the access token has expired or will expire within the given buffer.

Jump to

Keyboard shortcuts

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