auth

package
v0.0.27 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package auth implements OAuth PKCE and device-code flows for SSO login.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug added in v0.0.23

func Debug(msg string)

Debug emits a pre-formatted diagnostic line to the debug sink installed via SetDebugLogger. Used by adjacent packages (e.g. provider/openai.go's codex backend transport) so they can share the session logger the TUI already wires for auth events, without each package plumbing its own logger interface.

func FormatTLSPreflightFix

func FormatTLSPreflightFix(result *TLSPreflightResult) string

FormatTLSPreflightFix returns a user-friendly message for TLS preflight failures.

func IsCodexOAuthToken added in v0.0.23

func IsCodexOAuthToken(key string) bool

IsCodexOAuthToken is a convenience wrapper reporting whether key is a ChatGPT OAuth access token (as minted by `/login codex`).

func SaveKey

func SaveKey(envVar, apiKey string) error

SaveKey saves an API key to ~/.pi-go/.env.

func SetDebugLogger added in v0.0.23

func SetDebugLogger(fn func(string))

SetDebugLogger installs a diagnostic sink for auth flows. Passing nil disables logging. The function is invoked from goroutines handling OAuth callbacks, so implementations must be goroutine-safe.

Types

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceCode      string `json:"device_code"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
}

DeviceCodeResponse holds the device authorization response.

func DeviceFlow

func DeviceFlow(ctx context.Context, prov Provider) (*DeviceCodeResponse, error)

DeviceFlow runs the OAuth device authorization grant (RFC 8628). Returns the device code response so the caller can display the user code, then polls for completion.

type KeyKind added in v0.0.23

type KeyKind string

KeyKind identifies the shape of an OpenAI credential. "api-key" is a classic `sk-…` platform key; "codex-oauth" is a ChatGPT OAuth access token (a JWT whose payload carries the `https://api.openai.com/auth` claim). "unknown" is anything else — treat as opaque.

const (
	KeyKindAPIKey     KeyKind = "api-key"
	KeyKindCodexOAuth KeyKind = "codex-oauth"
	KeyKindUnknown    KeyKind = "unknown"
)

func IdentifyKey added in v0.0.23

func IdentifyKey(key string) KeyKind

IdentifyKey classifies an OpenAI credential. Detection is structural — `sk-` / `sk_live_` / `sk-proj-` prefixes indicate a platform API key; a three-segment JWT whose payload decodes to JSON and contains the `https://api.openai.com/auth` claim indicates a codex OAuth token. The token itself is never logged or returned.

type ManualCodeSession added in v0.0.23

type ManualCodeSession struct {
	Provider    Provider
	AuthURL     string
	Verifier    string
	State       string
	RedirectURI string
}

ManualCodeSession holds the state needed to complete a manual-code OAuth flow. The caller builds the auth URL via StartManualCodeFlow, opens a browser, then asks the user to paste the callback URL or authorization code and passes it to CompleteManualCodeFlow.

func StartManualCodeFlow added in v0.0.23

func StartManualCodeFlow(prov Provider) (*ManualCodeSession, error)

StartManualCodeFlow builds an authorization URL for a provider that expects the user to copy a callback URL or code from the browser and paste it into the CLI. No local HTTP listener is started.

type Provider

type Provider struct {
	Name              string
	EnvVar            string
	AuthURL           string // OAuth authorization endpoint
	TokenURL          string // OAuth token endpoint
	ClientID          string // OAuth client ID (public client)
	Scopes            []string
	ExtraParams       map[string]string // additional auth URL params
	TokenToKey        func(tok *TokenResponse) string
	KeyPageURL        string // fallback manual key page
	DeviceURL         string // device authorization endpoint (optional)
	UseDeviceFlow     bool   // prefer device code flow over PKCE
	TLSPreflight      bool   // run TLS preflight before OAuth (OpenAI Codex)
	CodexOAuth        bool   // use Codex OAuth callback + token-exchange semantics
	ManualCode        bool   // user pastes a code or callback URL (no local listener)
	ManualRedirectURI string // fixed redirect URI for manual-code flow
	TokenJSONBody     bool   // POST token exchange as JSON (Anthropic) instead of form-encoded
	APIKeyURL         string // optional: exchange OAuth access_token for an API key via this endpoint
}

Provider holds OAuth configuration for an LLM provider.

func FindProvider

func FindProvider(name string) (Provider, bool)

FindProvider returns a provider by name.

func Providers

func Providers() []Provider

Providers returns the list of configured OAuth providers.

type Result

type Result struct {
	Provider string
	APIKey   string
	EnvVar   string
	Err      error
}

Result is the outcome of an SSO login flow.

func CompleteManualCodeFlow added in v0.0.23

func CompleteManualCodeFlow(ctx context.Context, sess *ManualCodeSession, pasted string) (*Result, error)

CompleteManualCodeFlow exchanges a pasted authorization code for a token. Anthropic's manual-code flow may provide either a full redirect URL ("http://localhost:53692/callback?code=...&state=..."), a query string, a "<code>#<state>" pair, or just the code. When state is present it is validated against the session state before the token exchange. When the provider has an APIKeyURL, the OAuth access token is exchanged for a provider-managed API key.

func PKCEFlow

func PKCEFlow(ctx context.Context, prov Provider, openBrowser func(string) error) (*Result, error)

PKCEFlow runs the OAuth PKCE authorization code flow. It starts a local HTTP server, opens the browser, and waits for the callback.

func PollDeviceToken

func PollDeviceToken(ctx context.Context, prov Provider, deviceCode string, interval int) (*Result, error)

PollDeviceToken polls for the device code token until authorized or expired.

type TLSPreflightResult

type TLSPreflightResult struct {
	OK      bool
	Kind    string // "tls-cert" or "network"
	Code    string
	Message string
}

TLSPreflightResult is the outcome of the OAuth TLS preflight check.

func RunTLSPreflight

func RunTLSPreflight(timeoutMs int) *TLSPreflightResult

RunTLSPreflight probes the OpenAI auth endpoint to detect TLS certificate issues.

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
	IDToken      string `json:"id_token"`
	APIKey       string `json:"api_key"`        // some providers return key directly
	APIKeyCamel  string `json:"apiKey"`         // alternate camelCase response key
	OpenAIAPIKey string `json:"openai_api_key"` // alternate token-exchange response key
	RawKey       string `json:"raw_key"`        // Anthropic create_api_key response
}

TokenResponse holds the OAuth token response.

Jump to

Keyboard shortcuts

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