Documentation
¶
Overview ¶
Package copilot provides authentication and token management for GitHub Copilot API. It handles the OAuth2 device flow for secure authentication with the Copilot API.
Package copilot provides authentication and token management functionality for GitHub Copilot AI services. It handles OAuth2 device flow token storage, serialization, and retrieval for maintaining authenticated sessions with the Copilot API.
Index ¶
- Variables
- func GetUserFriendlyMessage(err error) string
- func IsAuthenticationError(err error) bool
- func IsOAuthError(err error) bool
- type AuthenticationError
- type CopilotAPIToken
- type CopilotAuth
- func (c *CopilotAuth) CreateTokenStorage(bundle *CopilotAuthBundle) *CopilotTokenStorage
- func (c *CopilotAuth) GetAPIEndpoint() string
- func (c *CopilotAuth) GetCopilotAPIToken(ctx context.Context, githubAccessToken string) (*CopilotAPIToken, error)
- func (c *CopilotAuth) ListModels(ctx context.Context, apiToken *CopilotAPIToken) ([]CopilotModelEntry, error)
- func (c *CopilotAuth) ListModelsWithGitHubToken(ctx context.Context, githubAccessToken string) ([]CopilotModelEntry, error)
- func (c *CopilotAuth) LoadAndValidateToken(ctx context.Context, storage *CopilotTokenStorage) (bool, error)
- func (c *CopilotAuth) MakeAuthenticatedRequest(ctx context.Context, method, url string, body io.Reader, ...) (*http.Request, error)
- func (c *CopilotAuth) StartDeviceFlow(ctx context.Context) (*DeviceCodeResponse, error)
- func (c *CopilotAuth) ValidateToken(ctx context.Context, accessToken string) (bool, string, error)
- func (c *CopilotAuth) WaitForAuthorization(ctx context.Context, deviceCode *DeviceCodeResponse) (*CopilotAuthBundle, error)
- type CopilotAuthBundle
- type CopilotModelEntry
- type CopilotModelsResponse
- type CopilotTokenData
- type CopilotTokenStorage
- type DeviceCodeResponse
- type DeviceFlowClient
- func (c *DeviceFlowClient) FetchUserInfo(ctx context.Context, accessToken string) (GitHubUserInfo, error)
- func (c *DeviceFlowClient) PollForToken(ctx context.Context, deviceCode *DeviceCodeResponse) (*CopilotTokenData, error)
- func (c *DeviceFlowClient) RequestDeviceCode(ctx context.Context) (*DeviceCodeResponse, error)
- type GitHubUserInfo
- type OAuthError
Constants ¶
This section is empty.
Variables ¶
var ( // ErrDeviceCodeFailed represents an error when requesting the device code fails. ErrDeviceCodeFailed = &AuthenticationError{ Type: "device_code_failed", Message: "Failed to request device code from GitHub", Code: http.StatusBadRequest, } // ErrDeviceCodeExpired represents an error when the device code has expired. ErrDeviceCodeExpired = &AuthenticationError{ Type: "device_code_expired", Message: "Device code has expired. Please try again.", Code: http.StatusGone, } // ErrAuthorizationPending represents a pending authorization state (not an error, used for polling). ErrAuthorizationPending = &AuthenticationError{ Type: "authorization_pending", Message: "Authorization is pending. Waiting for user to authorize.", Code: http.StatusAccepted, } // ErrSlowDown represents a request to slow down polling. ErrSlowDown = &AuthenticationError{ Type: "slow_down", Message: "Polling too frequently. Slowing down.", Code: http.StatusTooManyRequests, } // ErrAccessDenied represents an error when the user denies authorization. ErrAccessDenied = &AuthenticationError{ Type: "access_denied", Message: "User denied authorization", Code: http.StatusForbidden, } // ErrTokenExchangeFailed represents an error when token exchange fails. ErrTokenExchangeFailed = &AuthenticationError{ Type: "token_exchange_failed", Message: "Failed to exchange device code for access token", Code: http.StatusBadRequest, } // ErrPollingTimeout represents an error when polling times out. ErrPollingTimeout = &AuthenticationError{ Type: "polling_timeout", Message: "Timeout waiting for user authorization", Code: http.StatusRequestTimeout, } // ErrUserInfoFailed represents an error when fetching user info fails. ErrUserInfoFailed = &AuthenticationError{ Type: "user_info_failed", Message: "Failed to fetch GitHub user information", Code: http.StatusBadRequest, } )
Common authentication error types for GitHub Copilot device flow.
Functions ¶
func GetUserFriendlyMessage ¶
GetUserFriendlyMessage returns a user-friendly error message based on the error type.
func IsAuthenticationError ¶
IsAuthenticationError checks if an error is an authentication error.
func IsOAuthError ¶
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.
func (*AuthenticationError) Unwrap ¶
func (e *AuthenticationError) Unwrap() error
Unwrap returns the underlying cause of the error.
type CopilotAPIToken ¶
type CopilotAPIToken struct {
// Token is the JWT token for authenticating with the Copilot API.
Token string `json:"token"`
// ExpiresAt is the Unix timestamp when the token expires.
ExpiresAt int64 `json:"expires_at"`
// Endpoints contains the available API endpoints.
Endpoints struct {
API string `json:"api"`
Proxy string `json:"proxy"`
OriginTracker string `json:"origin-tracker"`
Telemetry string `json:"telemetry"`
} `json:"endpoints,omitempty"`
// ErrorDetails contains error information if the request failed.
ErrorDetails *struct {
URL string `json:"url"`
Message string `json:"message"`
DocumentationURL string `json:"documentation_url"`
} `json:"error_details,omitempty"`
}
CopilotAPIToken represents the Copilot API token response.
type CopilotAuth ¶
type CopilotAuth struct {
// contains filtered or unexported fields
}
CopilotAuth handles GitHub Copilot authentication flow. It provides methods for device flow authentication and token management.
func NewCopilotAuth ¶
func NewCopilotAuth(cfg *config.Config) *CopilotAuth
NewCopilotAuth creates a new CopilotAuth service instance. It initializes an HTTP client with proxy settings from the provided configuration.
func (*CopilotAuth) CreateTokenStorage ¶
func (c *CopilotAuth) CreateTokenStorage(bundle *CopilotAuthBundle) *CopilotTokenStorage
CreateTokenStorage creates a new CopilotTokenStorage from auth bundle.
func (*CopilotAuth) GetAPIEndpoint ¶
func (c *CopilotAuth) GetAPIEndpoint() string
GetAPIEndpoint returns the Copilot API endpoint URL.
func (*CopilotAuth) GetCopilotAPIToken ¶
func (c *CopilotAuth) GetCopilotAPIToken(ctx context.Context, githubAccessToken string) (*CopilotAPIToken, error)
GetCopilotAPIToken exchanges a GitHub access token for a Copilot API token. This token is used to make authenticated requests to the Copilot API.
func (*CopilotAuth) ListModels ¶
func (c *CopilotAuth) ListModels(ctx context.Context, apiToken *CopilotAPIToken) ([]CopilotModelEntry, error)
ListModels fetches the list of available models from the Copilot API. It requires a valid Copilot API token (not the GitHub access token).
func (*CopilotAuth) ListModelsWithGitHubToken ¶
func (c *CopilotAuth) ListModelsWithGitHubToken(ctx context.Context, githubAccessToken string) ([]CopilotModelEntry, error)
ListModelsWithGitHubToken is a convenience method that exchanges a GitHub access token for a Copilot API token and then fetches the available models.
func (*CopilotAuth) LoadAndValidateToken ¶
func (c *CopilotAuth) LoadAndValidateToken(ctx context.Context, storage *CopilotTokenStorage) (bool, error)
LoadAndValidateToken loads a token from storage and validates it. Returns the storage if valid, or an error if the token is invalid or expired.
func (*CopilotAuth) MakeAuthenticatedRequest ¶
func (c *CopilotAuth) MakeAuthenticatedRequest(ctx context.Context, method, url string, body io.Reader, apiToken *CopilotAPIToken) (*http.Request, error)
MakeAuthenticatedRequest creates an authenticated HTTP request to the Copilot API.
func (*CopilotAuth) StartDeviceFlow ¶
func (c *CopilotAuth) StartDeviceFlow(ctx context.Context) (*DeviceCodeResponse, error)
StartDeviceFlow initiates the device flow authentication. Returns the device code response containing the user code and verification URI.
func (*CopilotAuth) ValidateToken ¶
ValidateToken checks if a GitHub access token is valid by attempting to fetch user info.
func (*CopilotAuth) WaitForAuthorization ¶
func (c *CopilotAuth) WaitForAuthorization(ctx context.Context, deviceCode *DeviceCodeResponse) (*CopilotAuthBundle, error)
WaitForAuthorization polls for user authorization and returns the auth bundle.
type CopilotAuthBundle ¶
type CopilotAuthBundle struct {
// TokenData contains the OAuth token information.
TokenData *CopilotTokenData
// Username is the GitHub username.
Username string
// Email is the GitHub email address.
Email string
// Name is the GitHub display name.
Name string
}
CopilotAuthBundle bundles authentication data for storage.
type CopilotModelEntry ¶
type CopilotModelEntry struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
OwnedBy string `json:"owned_by"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Capabilities map[string]any `json:"capabilities,omitempty"`
}
CopilotModelEntry represents a single model entry returned by the Copilot /models API.
type CopilotModelsResponse ¶
type CopilotModelsResponse struct {
Data []CopilotModelEntry `json:"data"`
Object string `json:"object"`
}
CopilotModelsResponse represents the response from the Copilot /models endpoint.
type CopilotTokenData ¶
type CopilotTokenData struct {
// AccessToken is the OAuth2 access token.
AccessToken string `json:"access_token"`
// TokenType is the type of token, typically "bearer".
TokenType string `json:"token_type"`
// Scope is the OAuth2 scope granted to the token.
Scope string `json:"scope"`
}
CopilotTokenData holds the raw OAuth token response from GitHub.
type CopilotTokenStorage ¶
type CopilotTokenStorage struct {
// AccessToken is the OAuth2 access token used for authenticating API requests.
AccessToken string `json:"access_token"`
// TokenType is the type of token, typically "bearer".
TokenType string `json:"token_type"`
// Scope is the OAuth2 scope granted to the token.
Scope string `json:"scope"`
// ExpiresAt is the timestamp when the access token expires (if provided).
ExpiresAt string `json:"expires_at,omitempty"`
// Username is the GitHub username associated with this token.
Username string `json:"username"`
// Email is the GitHub email address associated with this token.
Email string `json:"email,omitempty"`
// Name is the GitHub display name associated with this token.
Name string `json:"name,omitempty"`
// Type indicates the authentication provider type, always "github-copilot" for this storage.
Type string `json:"type"`
}
CopilotTokenStorage stores OAuth2 token information for GitHub Copilot API authentication. It maintains compatibility with the existing auth system while adding Copilot-specific fields for managing access tokens and user account information.
func (*CopilotTokenStorage) SaveTokenToFile ¶
func (ts *CopilotTokenStorage) SaveTokenToFile(authFilePath string) error
SaveTokenToFile serializes the Copilot 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 DeviceCodeResponse ¶
type DeviceCodeResponse struct {
// DeviceCode is the device verification code.
DeviceCode string `json:"device_code"`
// UserCode is the code the user must enter at the verification URI.
UserCode string `json:"user_code"`
// VerificationURI is the URL where the user should enter the code.
VerificationURI string `json:"verification_uri"`
// ExpiresIn is the number of seconds until the device code expires.
ExpiresIn int `json:"expires_in"`
// Interval is the minimum number of seconds to wait between polling requests.
Interval int `json:"interval"`
}
DeviceCodeResponse represents GitHub's device code response.
type DeviceFlowClient ¶
type DeviceFlowClient struct {
// contains filtered or unexported fields
}
DeviceFlowClient handles the OAuth2 device flow for GitHub Copilot.
func NewDeviceFlowClient ¶
func NewDeviceFlowClient(cfg *config.Config) *DeviceFlowClient
NewDeviceFlowClient creates a new device flow client.
func (*DeviceFlowClient) FetchUserInfo ¶
func (c *DeviceFlowClient) FetchUserInfo(ctx context.Context, accessToken string) (GitHubUserInfo, error)
FetchUserInfo retrieves the GitHub user profile for the authenticated user.
func (*DeviceFlowClient) PollForToken ¶
func (c *DeviceFlowClient) PollForToken(ctx context.Context, deviceCode *DeviceCodeResponse) (*CopilotTokenData, error)
PollForToken polls the token endpoint until the user authorizes or the device code expires.
func (*DeviceFlowClient) RequestDeviceCode ¶
func (c *DeviceFlowClient) RequestDeviceCode(ctx context.Context) (*DeviceCodeResponse, error)
RequestDeviceCode initiates the device flow by requesting a device code from GitHub.
type GitHubUserInfo ¶
type GitHubUserInfo struct {
// Login is the GitHub username.
Login string
// Email is the primary email address (may be empty if not public).
Email string
// Name is the display name.
Name string
}
GitHubUserInfo holds GitHub user profile information.
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.