auth

package
v1.65.6 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Anthropic (Claude)
	// NOTE: Anthropic's OAuth does not support localhost redirect URIs.
	// The only registered redirect is console.anthropic.com which displays the code for the user to copy.
	AnthropicOAuthClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
	AnthropicAuthURL       = "https://claude.ai/oauth/authorize"
	AnthropicTokenURL      = "https://console.anthropic.com/v1/oauth/token"
	AnthropicRedirectURI   = "https://console.anthropic.com/oauth/code/callback"
	AnthropicScopes        = "org:create_api_key user:profile user:inference"

	OpenAIAuthURL      = "https://auth.openai.com/oauth/authorize"
	OpenAITokenURL     = "https://auth.openai.com/oauth/token"
	OpenAIRedirectURI  = "http://localhost:1455/auth/callback"
	OpenAIScopes       = "openid profile email offline_access"
	OpenAICallbackPort = "1455"
)
View Source
const (
	ClaudeCliProfileID = "anthropic:claude-cli"
	CodexCliProfileID  = "openai-codex:codex-cli"
)

ProfileID constants para CLIs externos.

Variables

This section is empty.

Functions

func DefaultStorePath

func DefaultStorePath() string

DefaultStorePath retorna o caminho padrão do arquivo de perfis de autenticação.

func DeleteProfile

func DeleteProfile(profileID string, logger *zap.Logger) error

DeleteProfile remove um perfil do store.

func EnsureStoreDir

func EnsureStoreDir(path string) error

EnsureStoreDir ensures the directory for the store file exists.

func FormatAuthStatus

func FormatAuthStatus(logger *zap.Logger) string

func FormatExpiry

func FormatExpiry(expiresMs int64) string

FormatExpiry retorna uma string legível do tempo restante.

func GenerateState

func GenerateState() (string, error)

GenerateState gera um state aleatório para OAuth.

func InvalidateCache

func InvalidateCache()

InvalidateCache limpa o cache em memória.

func ListProfilesForProvider

func ListProfilesForProvider(provider ProviderID, logger *zap.Logger) []string

ListProfilesForProvider retorna todos os profile IDs para um provedor.

func LoginAnthropicOAuth

func LoginAnthropicOAuth(ctx context.Context, logger *zap.Logger) (profileID string, err error)

LoginAnthropicOAuth authenticates via OAuth with Anthropic. Anthropic's OAuth does not support localhost redirect URIs, so the flow opens the browser and the user copies the authorization code displayed on the Anthropic console page.

func LoginOpenAICodexOAuth

func LoginOpenAICodexOAuth(ctx context.Context, logger *zap.Logger) (profileID string, err error)

func Logout

func Logout(provider ProviderID, logger *zap.Logger) error

func OpenAICodexClientID

func OpenAICodexClientID() string

OpenAICodexClientID returns the OpenAI Codex client ID, allowing override via env var.

func SaveStore

func SaveStore(store *AuthProfileStore, logger *zap.Logger) error

SaveStore salva o store no disco.

func StripAuthPrefix

func StripAuthPrefix(key string) string

StripAuthPrefix removes the "oauth:", "token:", or "apikey:" prefix from a resolved API key, returning the raw credential suitable for HTTP headers.

func SyncExternalCliCreds

func SyncExternalCliCreds(logger *zap.Logger) (bool, error)

TEMPORARY: stub para destravar o build. A versão anterior deste arquivo ficou corrompida (bytes não-UTF-8) durante escrita em base64 e quebrou a compilação. Vamos reimplementar o sync Claude Code / Codex CLI em passos pequenos com write valido.

func UpsertProfile

func UpsertProfile(profileID string, cred *AuthProfileCredential, logger *zap.Logger) error

UpsertProfile adiciona ou atualiza um perfil no store.

Types

type AuthMode

type AuthMode string

AuthMode indica como a autenticação foi resolvida.

const (
	AuthModeOAuth  AuthMode = "oauth"
	AuthModeAPIKey AuthMode = "api-key"
	AuthModeToken  AuthMode = "token"
	AuthModeEnv    AuthMode = "env"
)

type AuthProfileCredential

type AuthProfileCredential struct {
	CredType CredentialType `json:"type"`
	Provider ProviderID     `json:"provider"`
	Email    string         `json:"email,omitempty"`

	// Campos OAuth
	Access    string `json:"access,omitempty"`
	Refresh   string `json:"refresh,omitempty"`
	Expires   int64  `json:"expires,omitempty"`
	AccountID string `json:"account_id,omitempty"`
	ClientID  string `json:"client_id,omitempty"`

	// Campo API Key
	Key string `json:"key,omitempty"`

	// Campo Token
	Token string `json:"token,omitempty"`
}

AuthProfileCredential é um wrapper polimórfico para qualquer tipo de credencial.

func GetProfile

func GetProfile(profileID string, logger *zap.Logger) *AuthProfileCredential

GetProfile retorna um perfil pelo ID.

func RefreshOAuth

func RefreshOAuth(ctx context.Context, cred *AuthProfileCredential, logger *zap.Logger) (*AuthProfileCredential, error)

RefreshOAuth refreshes an OAuth credential in-place and returns it. Supported: anthropic, openai-codex.

func (*AuthProfileCredential) GetAccessToken

func (c *AuthProfileCredential) GetAccessToken() string

GetAccessToken retorna o token de acesso dependendo do tipo.

func (*AuthProfileCredential) IsExpired

func (c *AuthProfileCredential) IsExpired() bool

IsExpired verifica se a credencial está expirada.

func (*AuthProfileCredential) IsExpiringSoon

func (c *AuthProfileCredential) IsExpiringSoon(withinMinutes int) bool

IsExpiringSoon verifica se expira nos próximos N minutos.

func (*AuthProfileCredential) String

func (c *AuthProfileCredential) String() string

String returns a redacted representation safe for logging/debugging.

type AuthProfileStore

type AuthProfileStore struct {
	Version  int                               `json:"version"`
	Profiles map[string]*AuthProfileCredential `json:"profiles"`
	Order    map[string][]string               `json:"order,omitempty"`
	LastGood map[string]string                 `json:"last_good,omitempty"`
}

AuthProfileStore é o armazém principal de credenciais.

func LoadStore

func LoadStore(logger *zap.Logger) *AuthProfileStore

LoadStore carrega o store do disco.

func NewAuthProfileStore

func NewAuthProfileStore() *AuthProfileStore

NewAuthProfileStore cria um store vazio.

type CredentialType

type CredentialType string

CredentialType representa o tipo de credencial armazenada.

const (
	CredentialOAuth  CredentialType = "oauth"
	CredentialAPIKey CredentialType = "api_key"
	CredentialToken  CredentialType = "token"
)

type OAuthTokenResponse

type OAuthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
	TokenType    string `json:"token_type"`
	Scope        string `json:"scope"`
}

OAuthTokenResponse representa a resposta de um endpoint de token OAuth.

type PKCE

type PKCE struct {
	Verifier  string
	Challenge string
}

PKCE contém verifier e challenge para OAuth PKCE flow.

func GeneratePKCE

func GeneratePKCE() (*PKCE, error)

GeneratePKCE gera um par verifier/challenge para OAuth PKCE. Usa 32 bytes aleatórios para o verifier e SHA256 para o challenge.

type ProviderID

type ProviderID string

ProviderID identifica o provedor de autenticação.

const (
	ProviderAnthropic   ProviderID = "anthropic"
	ProviderOpenAI      ProviderID = "openai"
	ProviderOpenAICodex ProviderID = "openai-codex"
)

type ResolvedAuth

type ResolvedAuth struct {
	APIKey    string
	ProfileID string
	Source    string
	Mode      AuthMode
	Provider  ProviderID
	Email     string
}

ResolvedAuth representa o resultado da resolução de autenticação.

func ResolveAuth

func ResolveAuth(ctx context.Context, provider ProviderID, logger *zap.Logger) (*ResolvedAuth, error)

ResolveAuth resolves a chave a usar (um apikey OU access token) para um provedor. Ordem: 1) auth-profiles store (first match for provider) 2) env vars

Nota: para manter backward compatibility com seus clients atuais, retornamos uma string "oauth:eaxxxx" quando for token OAuth, e uma string "apikey:exxxxx" quando for API key.

Jump to

Keyboard shortcuts

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