Documentation
¶
Overview ¶
Package codex provides authentication and token management for OpenAI's Codex API. It handles the OAuth2 flow, including generating authorization URLs, exchanging authorization codes for tokens, and refreshing expired tokens. The package also defines data structures for storing and managing Codex authentication credentials.
Package codex provides authentication and token management functionality for OpenAI's Codex AI services. It handles OAuth2 token storage, serialization, and retrieval for maintaining authenticated sessions with the Codex API.
Index ¶
- Constants
- func CredentialFileName(email, planType, hashAccountID string, includeProviderPrefix bool) string
- type Auth
- func (o *Auth) CreateTokenStorage(bundle *AuthBundle) *TokenStorage
- func (o *Auth) ExchangeCodeForTokens(ctx context.Context, code string, pkceCodes *misc.PKCECodes) (*AuthBundle, error)
- func (o *Auth) ExchangeCodeForTokensWithRedirect(ctx context.Context, code, redirectURI string, pkceCodes *misc.PKCECodes) (*AuthBundle, error)
- func (o *Auth) GenerateAuthURL(state string, pkceCodes *misc.PKCECodes) (string, error)
- func (o *Auth) RefreshTokens(ctx context.Context, refreshToken string) (*TokenData, error)
- func (o *Auth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) (*TokenData, error)
- func (o *Auth) UpdateTokenStorage(storage *TokenStorage, TokenData *TokenData)
- type AuthBundle
- type JWTClaims
- type TokenData
- type TokenStorage
Constants ¶
const (
ClientID = "app_EMoamEEZ73f0CkXaXp7hrann"
)
OAuth configuration constants for OpenAI Codex
Variables ¶
This section is empty.
Functions ¶
func CredentialFileName ¶
CredentialFileName returns the filename used to persist Codex OAuth credentials. When planType is available (e.g. "plus", "team"), it is appended after the email as a suffix to disambiguate subscriptions.
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth handles the OpenAI OAuth2 authentication flow. It manages the HTTP client and provides methods for generating authorization URLs, exchanging authorization codes for tokens, and refreshing access tokens.
func NewAuth ¶
NewAuth creates a new Auth service instance. It initializes an HTTP client with proxy settings from the provided configuration.
func (*Auth) CreateTokenStorage ¶
func (o *Auth) CreateTokenStorage(bundle *AuthBundle) *TokenStorage
CreateTokenStorage creates a new TokenStorage from an AuthBundle. It populates the storage struct with token data, user information, and timestamps.
func (*Auth) ExchangeCodeForTokens ¶
func (o *Auth) ExchangeCodeForTokens(ctx context.Context, code string, pkceCodes *misc.PKCECodes) ( *AuthBundle, error, )
ExchangeCodeForTokens exchanges an authorization code for access and refresh tokens. It performs an HTTP POST request to the OpenAI token endpoint with the provided authorization code and PKCE verifier.
func (*Auth) ExchangeCodeForTokensWithRedirect ¶
func (o *Auth) ExchangeCodeForTokensWithRedirect( ctx context.Context, code, redirectURI string, pkceCodes *misc.PKCECodes, ) (*AuthBundle, error)
ExchangeCodeForTokensWithRedirect exchanges an authorization code for tokens using a caller-provided redirect URI. This supports alternate auth flows such as device login while preserving the existing token parsing and storage behavior.
func (*Auth) GenerateAuthURL ¶
GenerateAuthURL creates the OAuth authorization URL with PKCE (Proof Key for Code Exchange). It constructs the URL with the necessary parameters, including the client ID, response type, redirect URI, scopes, and PKCE challenge.
func (*Auth) RefreshTokens ¶
RefreshTokens refreshes an access token using a refresh token. This method is called when an access token has expired. It makes a request to the token endpoint to obtain a new set of tokens.
func (*Auth) RefreshTokensWithRetry ¶
func (o *Auth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) ( *TokenData, error, )
RefreshTokensWithRetry refreshes tokens with a built-in retry mechanism. It attempts to refresh the tokens up to a specified maximum number of retries, with an exponential backoff strategy to handle transient network errors.
func (*Auth) UpdateTokenStorage ¶
func (o *Auth) UpdateTokenStorage(storage *TokenStorage, TokenData *TokenData)
UpdateTokenStorage updates an existing TokenStorage with new token data. This is typically called after a successful token refresh to persist the new credentials.
type AuthBundle ¶
type AuthBundle struct {
// APIKey is the OpenAI API key obtained from token exchange
APIKey string `json:"api_key"`
// TokenData contains the OAuth tokens from the authentication flow
TokenData TokenData `json:"token_data"`
// LastRefresh is the timestamp of the last token refresh
LastRefresh string `json:"last_refresh"`
}
AuthBundle aggregates all authentication-related data after the OAuth flow is complete. This includes the API key, token data, and the timestamp of the last refresh.
type JWTClaims ¶
type JWTClaims struct {
AtHash string `json:"at_hash"`
Aud []string `json:"aud"`
AuthProvider string `json:"auth_provider"`
AuthTime int `json:"auth_time"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Exp int `json:"exp"`
AuthInfo authInfo `json:"https://api.openai.com/auth"`
Iat int `json:"iat"`
Iss string `json:"iss"`
Jti string `json:"jti"`
Rat int `json:"rat"`
Sid string `json:"sid"`
Sub string `json:"sub"`
}
JWTClaims represents the claims section of a JSON Web Token (JWT). It includes standard claims like issuer, subject, and expiration time, as well as custom claims specific to OpenAI's authentication.
func ParseJWTToken ¶
ParseJWTToken parses a JWT token string and extracts its claims without performing cryptographic signature verification. This is useful for introspecting the token's contents to retrieve user information from an ID token after it has been validated by the authentication server.
func (*JWTClaims) GetAccountID ¶
GetAccountID extracts the user's account ID (subject) from the JWT claims. It retrieves the unique identifier for the user's ChatGPT account.
type TokenData ¶
type TokenData struct {
// IDToken is the JWT ID token containing user claims
IDToken string `json:"id_token"`
// 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"`
// AccountID is the OpenAI account identifier
AccountID string `json:"account_id"`
// Email is the OpenAI account email
Email string `json:"email"`
// Expire is the timestamp of the token expire
Expire string `json:"expired"`
}
TokenData holds the OAuth token information obtained from OpenAI. It includes the ID token, access token, refresh token, and associated user details.
type TokenStorage ¶
type TokenStorage 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"`
// AccountID is the OpenAI account identifier associated with this token.
AccountID string `json:"account_id"`
// LastRefresh is the timestamp of the last token refresh operation.
LastRefresh string `json:"last_refresh"`
// Email is the OpenAI account email address associated with this token.
Email string `json:"email"`
// Type indicates the authentication provider type, always "codex" 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:"-"`
}
TokenStorage stores OAuth2 token information for OpenAI Codex API authentication. It maintains compatibility with the existing auth system while adding Codex-specific fields for managing access tokens, refresh tokens, and user account information.
func (*TokenStorage) SaveTokenToFile ¶
func (ts *TokenStorage) SaveTokenToFile(authFilePath string) error
SaveTokenToFile serializes the Codex 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 (*TokenStorage) SetMetadata ¶
func (ts *TokenStorage) SetMetadata(meta map[string]any)
SetMetadata allows external callers to inject metadata into the storage before saving.