claude

package
v6.0.19 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package claude provides OAuth2 authentication functionality for Anthropic's Claude API. This package implements the complete OAuth2 flow with PKCE (Proof Key for Code Exchange) for secure authentication with Claude API, including token exchange, refresh, and storage.

Package claude provides authentication and token management functionality for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Claude API.

Package claude provides authentication and token management functionality for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Claude API.

Package claude provides authentication and token management functionality for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Claude API.

Package claude provides authentication and token management functionality for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Claude API.

Package claude provides authentication and token management functionality for Anthropic's Claude AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Claude API.

Index

Constants

View Source
const LoginSuccessHtml = `` /* 5957-byte string literal not displayed */

LoginSuccessHtml is the HTML template displayed to users after successful OAuth authentication. This template provides a user-friendly success page with options to close the window or navigate to the Claude platform. It includes automatic window closing functionality and keyboard accessibility features.

View Source
const SetupNoticeHtml = `` /* 238-byte string literal not displayed */

SetupNoticeHtml is the HTML template for the setup notice section. This template is embedded within the success page to inform users about additional setup steps required to complete their Claude account configuration.

Variables

View Source
var (

	// ErrInvalidState represents an error for invalid OAuth state parameter.
	ErrInvalidState = &AuthenticationError{
		Type:    "invalid_state",
		Message: "OAuth state parameter is invalid",
		Code:    http.StatusBadRequest,
	}

	// ErrCodeExchangeFailed represents an error when exchanging authorization code for tokens fails.
	ErrCodeExchangeFailed = &AuthenticationError{
		Type:    "code_exchange_failed",
		Message: "Failed to exchange authorization code for tokens",
		Code:    http.StatusBadRequest,
	}

	// ErrServerStartFailed represents an error when starting the OAuth callback server fails.
	ErrServerStartFailed = &AuthenticationError{
		Type:    "server_start_failed",
		Message: "Failed to start OAuth callback server",
		Code:    http.StatusInternalServerError,
	}

	// ErrPortInUse represents an error when the OAuth callback port is already in use.
	ErrPortInUse = &AuthenticationError{
		Type:    "port_in_use",
		Message: "OAuth callback port is already in use",
		Code:    13,
	}

	// ErrCallbackTimeout represents an error when waiting for OAuth callback times out.
	ErrCallbackTimeout = &AuthenticationError{
		Type:    "callback_timeout",
		Message: "Timeout waiting for OAuth callback",
		Code:    http.StatusRequestTimeout,
	}
)

Common authentication error types.

Functions

func GetUserFriendlyMessage

func GetUserFriendlyMessage(err error) string

GetUserFriendlyMessage returns a user-friendly error message based on the error type.

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError checks if an error is an authentication error.

func IsOAuthError

func IsOAuthError(err error) bool

IsOAuthError checks if an error is an OAuth error.

Types

type AuthenticationError

type AuthenticationError struct {
	// Type is the type of authentication error.
	Type string `json:"type"`
	// Message is a human-readable message describing the error.
	Message string `json:"message"`
	// Code is the HTTP status code associated with the error.
	Code int `json:"code"`
	// Cause is the underlying error that caused this authentication error.
	Cause error `json:"-"`
}

AuthenticationError represents authentication-related errors.

func NewAuthenticationError

func NewAuthenticationError(baseErr *AuthenticationError, cause error) *AuthenticationError

NewAuthenticationError creates a new authentication error with a cause based on a base error.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

Error returns a string representation of the authentication error.

type ClaudeAuth

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

ClaudeAuth handles Anthropic OAuth2 authentication flow. It provides methods for generating authorization URLs, exchanging codes for tokens, and refreshing expired tokens using PKCE for enhanced security.

func NewClaudeAuth

func NewClaudeAuth(cfg *config.Config) *ClaudeAuth

NewClaudeAuth creates a new Anthropic authentication service. It initializes the HTTP client with proxy settings from the configuration.

Parameters:

  • cfg: The application configuration containing proxy settings

Returns:

  • *ClaudeAuth: A new Claude authentication service instance

func (*ClaudeAuth) CreateTokenStorage

func (o *ClaudeAuth) CreateTokenStorage(bundle *ClaudeAuthBundle) *ClaudeTokenStorage

CreateTokenStorage creates a new ClaudeTokenStorage from auth bundle and user info. This method converts the authentication bundle into a token storage structure suitable for persistence and later use.

Parameters:

  • bundle: The authentication bundle containing token data

Returns:

  • *ClaudeTokenStorage: A new token storage instance

func (*ClaudeAuth) ExchangeCodeForTokens

func (o *ClaudeAuth) ExchangeCodeForTokens(ctx context.Context, code, state string, pkceCodes *PKCECodes) (*ClaudeAuthBundle, error)

ExchangeCodeForTokens exchanges authorization code for access tokens. This method implements the OAuth2 token exchange flow using PKCE for security. It sends the authorization code along with PKCE verifier to get access and refresh tokens.

Parameters:

  • ctx: The context for the request
  • code: The authorization code received from OAuth callback
  • state: The state parameter for verification
  • pkceCodes: The PKCE codes for secure verification

Returns:

  • *ClaudeAuthBundle: The complete authentication bundle with tokens
  • error: An error if token exchange fails

func (*ClaudeAuth) GenerateAuthURL

func (o *ClaudeAuth) GenerateAuthURL(state string, pkceCodes *PKCECodes) (string, string, error)

GenerateAuthURL creates the OAuth authorization URL with PKCE. This method generates a secure authorization URL including PKCE challenge codes for the OAuth2 flow with Anthropic's API.

Parameters:

  • state: A random state parameter for CSRF protection
  • pkceCodes: The PKCE codes for secure code exchange

Returns:

  • string: The complete authorization URL
  • string: The state parameter for verification
  • error: An error if PKCE codes are missing or URL generation fails

func (*ClaudeAuth) RefreshTokens

func (o *ClaudeAuth) RefreshTokens(ctx context.Context, refreshToken string) (*ClaudeTokenData, error)

RefreshTokens refreshes the access token using the refresh token. This method exchanges a valid refresh token for a new access token, extending the user's authenticated session.

Parameters:

  • ctx: The context for the request
  • refreshToken: The refresh token to use for getting new access token

Returns:

  • *ClaudeTokenData: The new token data with updated access token
  • error: An error if token refresh fails

func (*ClaudeAuth) RefreshTokensWithRetry

func (o *ClaudeAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) (*ClaudeTokenData, error)

RefreshTokensWithRetry refreshes tokens with automatic retry logic. This method implements exponential backoff retry logic for token refresh operations, providing resilience against temporary network or service issues.

Parameters:

  • ctx: The context for the request
  • refreshToken: The refresh token to use
  • maxRetries: The maximum number of retry attempts

Returns:

  • *ClaudeTokenData: The refreshed token data
  • error: An error if all retry attempts fail

func (*ClaudeAuth) UpdateTokenStorage

func (o *ClaudeAuth) UpdateTokenStorage(storage *ClaudeTokenStorage, tokenData *ClaudeTokenData)

UpdateTokenStorage updates an existing token storage with new token data. This method refreshes the token storage with newly obtained access and refresh tokens, updating timestamps and expiration information.

Parameters:

  • storage: The existing token storage to update
  • tokenData: The new token data to apply

type ClaudeAuthBundle

type ClaudeAuthBundle struct {
	// APIKey is the Anthropic API key obtained from token exchange
	APIKey string `json:"api_key"`
	// TokenData contains the OAuth tokens from the authentication flow
	TokenData ClaudeTokenData `json:"token_data"`
	// LastRefresh is the timestamp of the last token refresh
	LastRefresh string `json:"last_refresh"`
}

ClaudeAuthBundle aggregates authentication data after OAuth flow completion

type ClaudeTokenData

type ClaudeTokenData struct {
	// AccessToken is the OAuth2 access token for API access
	AccessToken string `json:"access_token"`
	// RefreshToken is used to obtain new access tokens
	RefreshToken string `json:"refresh_token"`
	// Email is the Anthropic account email
	Email string `json:"email"`
	// Expire is the timestamp of the token expire
	Expire string `json:"expired"`
}

ClaudeTokenData holds OAuth token information from Anthropic

type ClaudeTokenStorage

type ClaudeTokenStorage struct {
	// IDToken is the JWT ID token containing user claims and identity information.
	IDToken string `json:"id_token"`

	// AccessToken is the OAuth2 access token used for authenticating API requests.
	AccessToken string `json:"access_token"`

	// RefreshToken is used to obtain new access tokens when the current one expires.
	RefreshToken string `json:"refresh_token"`

	// LastRefresh is the timestamp of the last token refresh operation.
	LastRefresh string `json:"last_refresh"`

	// Email is the Anthropic account email address associated with this token.
	Email string `json:"email"`

	// Type indicates the authentication provider type, always "claude" for this storage.
	Type string `json:"type"`

	// Expire is the timestamp when the current access token expires.
	Expire string `json:"expired"`
}

ClaudeTokenStorage stores OAuth2 token information for Anthropic Claude API authentication. It maintains compatibility with the existing auth system while adding Claude-specific fields for managing access tokens, refresh tokens, and user account information.

func (*ClaudeTokenStorage) SaveTokenToFile

func (ts *ClaudeTokenStorage) SaveTokenToFile(authFilePath string) error

SaveTokenToFile serializes the Claude token storage to a JSON file. This method creates the necessary directory structure and writes the token data in JSON format to the specified file path for persistent storage.

Parameters:

  • authFilePath: The full path where the token file should be saved

Returns:

  • error: An error if the operation fails, nil otherwise

type OAuthError

type OAuthError struct {
	// Code is the OAuth error code.
	Code string `json:"error"`
	// Description is a human-readable description of the error.
	Description string `json:"error_description,omitempty"`
	// URI is a URI identifying a human-readable web page with information about the error.
	URI string `json:"error_uri,omitempty"`
	// StatusCode is the HTTP status code associated with the error.
	StatusCode int `json:"-"`
}

OAuthError represents an OAuth-specific error.

func NewOAuthError

func NewOAuthError(code, description string, statusCode int) *OAuthError

NewOAuthError creates a new OAuth error with the specified code, description, and status code.

func (*OAuthError) Error

func (e *OAuthError) Error() string

Error returns a string representation of the OAuth error.

type OAuthResult

type OAuthResult struct {
	// Code is the authorization code received from the OAuth provider
	Code string
	// State is the state parameter used to prevent CSRF attacks
	State string
	// Error contains any error message if the OAuth flow failed
	Error string
}

OAuthResult contains the result of the OAuth callback. It holds either the authorization code and state for successful authentication or an error message if the authentication failed.

type OAuthServer

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

OAuthServer handles the local HTTP server for OAuth callbacks. It listens for the authorization code response from the OAuth provider and captures the necessary parameters to complete the authentication flow.

func NewOAuthServer

func NewOAuthServer(port int) *OAuthServer

NewOAuthServer creates a new OAuth callback server. It initializes the server with the specified port and creates channels for handling OAuth results and errors.

Parameters:

  • port: The port number on which the server should listen

Returns:

  • *OAuthServer: A new OAuthServer instance

func (*OAuthServer) IsRunning

func (s *OAuthServer) IsRunning() bool

IsRunning returns whether the server is currently running.

Returns:

  • bool: True if the server is running, false otherwise

func (*OAuthServer) Start

func (s *OAuthServer) Start() error

Start starts the OAuth callback server. It sets up the HTTP handlers for the callback and success endpoints, and begins listening on the specified port.

Returns:

  • error: An error if the server fails to start

func (*OAuthServer) Stop

func (s *OAuthServer) Stop(ctx context.Context) error

Stop gracefully stops the OAuth callback server. It performs a graceful shutdown of the HTTP server with a timeout.

Parameters:

  • ctx: The context for controlling the shutdown process

Returns:

  • error: An error if the server fails to stop gracefully

func (*OAuthServer) WaitForCallback

func (s *OAuthServer) WaitForCallback(timeout time.Duration) (*OAuthResult, error)

WaitForCallback waits for the OAuth callback with a timeout. It blocks until either an OAuth result is received, an error occurs, or the specified timeout is reached.

Parameters:

  • timeout: The maximum time to wait for the callback

Returns:

  • *OAuthResult: The OAuth result if successful
  • error: An error if the callback times out or an error occurs

type PKCECodes

type PKCECodes struct {
	// CodeVerifier is the cryptographically random string used to correlate
	// the authorization request to the token request
	CodeVerifier string `json:"code_verifier"`
	// CodeChallenge is the SHA256 hash of the code verifier, base64url-encoded
	CodeChallenge string `json:"code_challenge"`
}

PKCECodes holds PKCE verification codes for OAuth2 PKCE flow

func GeneratePKCECodes

func GeneratePKCECodes() (*PKCECodes, error)

GeneratePKCECodes generates a PKCE code verifier and challenge pair following RFC 7636 specifications for OAuth 2.0 PKCE extension. This provides additional security for the OAuth flow by ensuring that only the client that initiated the request can exchange the authorization code.

Returns:

  • *PKCECodes: A struct containing the code verifier and challenge
  • error: An error if the generation fails, nil otherwise

Jump to

Keyboard shortcuts

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