claude

package
v7.2.116 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 33 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 (
	AuthURL = "https://claude.ai/oauth/authorize"
	// TokenURL is the authorization-code exchange endpoint. Claude Code 2.1.220
	// posts the code exchange to platform.claude.com, not api.anthropic.com.
	TokenURL        = "https://platform.claude.com/v1/oauth/token"
	RefreshTokenURL = "https://platform.claude.com/v1/oauth/token"
	ProfileURL      = "https://api.anthropic.com/api/oauth/profile"
	// RolesURL is the claude_cli role endpoint the native client queries right
	// after a successful token exchange, alongside the profile lookup.
	RolesURL         = "https://api.anthropic.com/api/oauth/claude_cli/roles"
	ClientID         = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
	RedirectURI      = "http://localhost:54545/callback"
	ClaudeOAuthScope = "user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload"
)

OAuth configuration constants for Claude/Anthropic

View Source
const (
	ClaudeDeviceIDsMetadataKey = "claude_device_ids"
	ClaudeDevicePoolSize       = 1
)
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 EnsureDeviceIDPool added in v7.2.116

func EnsureDeviceIDPool(metadata map[string]any) ([]string, bool, error)

EnsureDeviceIDPool repairs or creates the single-device pool in credential metadata.

func EnsureDeviceIDPoolFor added in v7.2.116

func EnsureDeviceIDPoolFor(metadata *map[string]any) ([]string, bool, error)

EnsureDeviceIDPoolFor lazily initializes the metadata map and then ensures the pool, both under the device pool lock.

A single *Auth is shared by every concurrent request that selects the same credential, so initializing the map field outside this lock races with the writes below and can abort the process with "concurrent map writes". Callers holding a shared credential must reach the pool through this package rather than touching the map directly.

func EnsureMetadataMap added in v7.2.116

func EnsureMetadataMap(metadata *map[string]any)

EnsureMetadataMap initializes the metadata map under the metadata lock.

func GenerateDeviceIDPool added in v7.2.116

func GenerateDeviceIDPool() ([]string, error)

GenerateDeviceIDPool creates the fixed-size device pool stored with a Claude credential.

func GetUserFriendlyMessage

func GetUserFriendlyMessage(err error) string

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

func HasCanonicalDeviceIDPool added in v7.2.116

func HasCanonicalDeviceIDPool(raw any) bool

HasCanonicalDeviceIDPool reports whether raw stores exactly one valid device ID.

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.

func NewAnthropicHttpClient

func NewAnthropicHttpClient(cfg *config.SDKConfig) *http.Client

func NormalizeDeviceIDPool added in v7.2.116

func NormalizeDeviceIDPool(raw any) []string

NormalizeDeviceIDPool returns the first valid device ID in canonical form.

func ReadDeviceIDPool added in v7.2.116

func ReadDeviceIDPool(metadata *map[string]any) any

ReadDeviceIDPool returns the stored pool value, initializing the map when needed, under the device pool lock. Slice values are copied so a caller can never mutate the stored credential identity after the lock is released.

func ReadMetadataString added in v7.2.116

func ReadMetadataString(metadata *map[string]any, key string) string

ReadMetadataString reads a string-valued metadata entry under the metadata lock, so it cannot observe a map being concurrently written by another path.

func SelectDeviceID added in v7.2.116

func SelectDeviceID(deviceIDs []string, sessionID string) (string, error)

SelectDeviceID returns the credential's sole device ID after validating the conversation session.

func StoreDeviceIDPool added in v7.2.116

func StoreDeviceIDPool(metadata *map[string]any, deviceIDs []string)

StoreDeviceIDPool writes a defensive copy of deviceIDs under the device pool lock.

func StoreMetadataString added in v7.2.116

func StoreMetadataString(metadata *map[string]any, key, value string)

StoreMetadataString writes a string-valued metadata entry under the metadata lock, initializing the map when needed. Empty values are skipped so callers can forward optional fields without erasing a previously resolved value.

func StoreMetadataValue added in v7.2.116

func StoreMetadataValue(metadata *map[string]any, key string, value any)

StoreMetadataValue writes an arbitrary metadata entry under the metadata lock, initializing the map when needed.

func ValidDeviceID added in v7.2.116

func ValidDeviceID(value string) bool

ValidDeviceID reports whether a value matches Claude Code's lowercase 64-hex device format.

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 a custom TLS transport that uses Firefox fingerprint to bypass Cloudflare's TLS fingerprinting on Anthropic domains.

Parameters:

  • cfg: The application configuration containing proxy settings

Returns:

  • *ClaudeAuth: A new Claude authentication service instance

func NewClaudeAuthWithProxyURL

func NewClaudeAuthWithProxyURL(cfg *config.Config, proxyURL string) *ClaudeAuth

NewClaudeAuthWithProxyURL creates a new Anthropic authentication service with a proxy override. proxyURL takes precedence over cfg.ProxyURL when non-empty.

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) FetchOAuthProfile added in v7.2.116

func (o *ClaudeAuth) FetchOAuthProfile(ctx context.Context, accessToken string) (*OAuthProfile, error)

FetchOAuthProfile retrieves the account identity associated with an OAuth access token.

func (*ClaudeAuth) FetchOAuthRoles added in v7.2.116

func (o *ClaudeAuth) FetchOAuthRoles(ctx context.Context, accessToken string) (json.RawMessage, error)

FetchOAuthRoles performs the claude_cli roles lookup the native client issues alongside the profile query after a token exchange. Only the request shape is covered by captured evidence, so the payload stays opaque and is returned raw instead of being decoded into a guessed structure.

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"`
	// DeviceIDs contains the single device identity persisted with this credential.
	DeviceIDs []string `json:"claude_device_ids"`
	// 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"`
	// AccountUUID identifies the Anthropic account returned by OAuth.
	AccountUUID string `json:"account_uuid"`
	// OrganizationUUID identifies the Anthropic organization returned by OAuth.
	OrganizationUUID string `json:"organization_uuid"`
	// OrganizationName is the display name returned by OAuth.
	OrganizationName string `json:"organization_name"`
	// Expire is the timestamp of the token expiry.
	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"`

	// AccountUUID identifies the Anthropic account returned by OAuth.
	AccountUUID string `json:"account_uuid,omitempty"`

	// OrganizationUUID identifies the Anthropic organization returned by OAuth.
	OrganizationUUID string `json:"organization_uuid,omitempty"`

	// OrganizationName is the display name returned by OAuth.
	OrganizationName string `json:"organization_name,omitempty"`

	// DeviceIDs contains the single device identity assigned to this credential.
	DeviceIDs []string `json:"claude_device_ids,omitempty"`

	// 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"`

	// Metadata holds arbitrary key-value pairs injected via hooks.
	// It is not exported to JSON directly to allow flattening during serialization.
	Metadata map[string]any `json:"-"`
}

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. It merges any injected metadata into the top-level JSON object.

Parameters:

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

Returns:

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

func (*ClaudeTokenStorage) SetMetadata

func (ts *ClaudeTokenStorage) SetMetadata(meta map[string]any)

SetMetadata allows external callers to inject metadata into the storage before saving.

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 OAuthProfile added in v7.2.116

type OAuthProfile struct {
	Account struct {
		UUID  string `json:"uuid"`
		Email string `json:"email"`
	} `json:"account"`
	Organization struct {
		UUID string `json:"uuid"`
		Name string `json:"name"`
	} `json:"organization"`
}

OAuthProfile is the account identity returned by Anthropic's OAuth profile endpoint.

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