auth

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

pi: auth/oauth/device-code.ts.

pi: auth/helpers.ts.

pi: auth/oauth/anthropic.ts.

Anthropic OAuth flow (Claude Pro/Max). pi uses Node's http.createServer for the OAuth callback server (CLI-only); pig uses net/http directly. The token-exchange HTTP call goes through the anthropicOAuthPostJSON seam so tests can stub it (pi: vi.stubGlobal("fetch")).

pi: auth/oauth/callback-server.ts.

Loopback OAuth redirect handler shared by the browser sign-in flows. pi uses node:http; pig uses net/http directly. The 2026-09-12 port-leak fix (close the raw listener before Server.Close so a close racing Serve startup cannot leak the bind) is baked into Close, and Go's http.Server.Close already drops spare keep-alive connections — pi's chatgpt flow needs an explicit closeAllConnections for the same hazard.

pi: auth/oauth/github-copilot.ts — GitHub Copilot OAuth device flow.

Segment deviations (declared):

  • pi's static import of the generated GITHUB_COPILOT_MODELS catalog becomes the githubCopilotKnownModelIDs hook: the catalog lives in package ai, which package auth cannot import (layering); ai/providers/github_copilot.go injects the lookup at init.
  • Extra token fields (availableModelIds, enterpriseUrl) ride OAuth credential Extra (pi: open index signature on OAuthCredentials).
  • pi's fetch calls go through the githubCopilotOAuthDo transport seam (pi: vi.stubGlobal("fetch") in tests); Date.now() shares the deviceCodeNow fake-clock seam.

pi: auth/oauth/kimi-coding.ts.

Kimi Code (subscription) OAuth flow — RFC 8628 device authorization grant against https://auth.kimi.com with JSON responses. The access token authenticates requests to https://api.kimi.com/coding as an Authorization: Bearer header.

pi: auth/oauth/meta.ts.

Meta Model API OAuth flow

RFC 8628 device authorization grant against https://auth.meta.com (JSON responses). Meta splits identity from API access: the resulting identity token is not accepted for inference, so it is exchanged for a Model API key via the Muse Code key-mint endpoint (minted keys live about a day). The identity token is stored as `refresh` and the minted key as `access`, so the standard OAuth scheduler re-mints the key when it expires with no bespoke renewal machinery. The identity token itself is not renewable (auth.meta.com answers grant_type=refresh_token with 404 and issues no refresh_token), so a 401/403 from mint means the session is dead and the user must sign in again.

pi: auth/oauth/openai-chatgpt.ts.

OpenAI Responses API token sharing through Sign in with ChatGPT. This public-client flow uses no client secret and sends the resulting user access token directly to api.openai.com. pi keeps a flow-local callback server here (it needs the issued client_id from the callback query, and its page texts differ from the shared server's); pig mirrors that 1:1. All OAuth HTTP traffic goes through the chatGPTOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).

pi: auth/oauth/openai-codex.ts.

OpenAI Codex (ChatGPT OAuth) flow. pi uses Node's crypto/http for the callback server (CLI-only); pig uses net/http directly. All OAuth HTTP traffic goes through the codexOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).

pi: auth/oauth/openrouter.ts.

OpenRouter OAuth PKCE flow. OpenRouter exchanges an authorization code for a permanent, user-controlled API key rather than an expiring access/refresh token pair. The callback is handled by a one-shot loopback server on an ephemeral port, raced against a manual prompt so remote/headless sessions can paste the redirect URL when the browser cannot reach the loopback server. All OAuth HTTP traffic goes through the openRouterOAuthDo seam so tests can stub it (pi: vi.stubGlobal("fetch")).

pi: auth/oauth/oauth-page.ts.

pi: auth/oauth/xai.ts.

xAI OAuth device-code flow (RFC 8628) against https://auth.x.ai with JSON responses. The access token authenticates requests to https://api.x.ai/v1 as an Authorization: Bearer header.

pi: auth/oauth/pkce.ts.

pi: auth/types.ts.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GeneratePKCE

func GeneratePKCE() (verifier string, challenge string, err error)

GeneratePKCE produces a PKCE code verifier and S256 challenge (pi: generatePKCE): a 32-byte base64url verifier plus its SHA-256 digest.

func GitHubCopilotAvailableModelIDs

func GitHubCopilotAvailableModelIDs(credential *OAuthCredential) (ids []string, ok bool)

GitHubCopilotAvailableModelIDs reads the account's available model ids from an OAuth credential (pi: credential.availableModelIds). ok is false when the field is absent or malformed — both mean "do not filter".

func OAuthErrorHTML

func OAuthErrorHTML(message string, details string) string

OAuthErrorHTML is the callback page shown after a failed login (pi: oauthErrorHtml).

func OAuthSuccessHTML

func OAuthSuccessHTML(message string) string

OAuthSuccessHTML is the callback page shown after a completed login (pi: oauthSuccessHtml).

func PollOAuthDeviceCodeFlow

func PollOAuthDeviceCodeFlow[T any](options DeviceCodePollOptions[T]) (T, error)

PollOAuthDeviceCodeFlow runs the RFC 8628 polling loop (pi: pollOAuthDeviceCodeFlow).

func SetGitHubCopilotKnownModelIDs

func SetGitHubCopilotKnownModelIDs(fn func() map[string]bool)

SetGitHubCopilotKnownModelIDs installs the catalog-membership lookup used by the policy-model filter during login (see the file header for why this is a hook rather than a static reference).

Types

type AnthropicOAuth

type AnthropicOAuth struct{}

AnthropicOAuth is the Claude Pro/Max OAuth auth (pi: anthropicOAuth).

func (AnthropicOAuth) IsSubscription

func (AnthropicOAuth) IsSubscription() bool

func (AnthropicOAuth) Login

func (AnthropicOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow, asking for the method first (pi: login with the method select prompt — browser default, copy code headless).

func (AnthropicOAuth) LoginLabel

func (AnthropicOAuth) LoginLabel() string

func (AnthropicOAuth) Name

func (AnthropicOAuth) Name() string

func (AnthropicOAuth) Refresh

func (AnthropicOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh exchanges the refresh token.

func (AnthropicOAuth) ToAuth

func (AnthropicOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from a valid credential.

type ApiKeyAuth

type ApiKeyAuth interface {
	// Name is a display name, e.g. "Anthropic API key".
	Name() string
	// Resolve derives auth from the stored credential and/or ambient
	// sources, merging per field (credential key ?? env(...), credential env
	// ?? env(...)). A nil result means not configured. Resolution is
	// provider-scoped; model-specific endpoint preparation happens after
	// auth has been resolved.
	Resolve(input ApiKeyAuthInput) (*AuthResult, error)
}

ApiKeyAuth is api-key auth: stored key/provider env plus ambient sources (env vars, AWS profiles, ADC files). Ambient-only providers omit the login capability (ApiKeyAuthLogin).

func EnvAPIKeyAuth

func EnvAPIKeyAuth(name string, envVars []string) ApiKeyAuth

EnvAPIKeyAuth is standard api-key auth: a stored credential key wins, otherwise the first set env var resolves. Includes a Login that prompts for the key (pi: envApiKeyAuth; pi's returned object carries resolve and the optional login member — pig expresses the optional member as the ApiKeyAuthLogin capability, satisfied by the same value).

Providers with non-standard resolution (provider env, ambient files, IAM) write their own ApiKeyAuth.

type ApiKeyAuthChecker

type ApiKeyAuthChecker interface {
	Check(input ApiKeyAuthInput) (*AuthCheck, error)
}

ApiKeyAuthChecker is the optional side-effect-free availability check capability of an ApiKeyAuth (pi: optional check member). Use it when Resolve may execute commands or other request-time work; when absent, Models checks availability by resolving auth.

type ApiKeyAuthInput

type ApiKeyAuthInput struct {
	// Ctx is pi's ctx: the AuthContext for env/file access.
	Ctx AuthContext
	// Credential is the stored api-key credential, nil when none stored.
	Credential *ApiKeyCredential
	// Context is pi's signal.
	Context context.Context
}

ApiKeyAuthInput is the input of ApiKeyAuth Resolve and Check (pi: { ctx, credential?, signal }).

type ApiKeyAuthLogin

type ApiKeyAuthLogin interface {
	Login(ctx context.Context, interaction AuthInteraction) (*ApiKeyCredential, error)
}

ApiKeyAuthLogin is the optional interactive-setup capability of an ApiKeyAuth (pi: optional login member; absent = ambient-only).

type ApiKeyCredential

type ApiKeyCredential struct {
	Key string            `json:"key,omitempty"`
	Env types.ProviderEnv `json:"env,omitempty"`
}

ApiKeyCredential is a stored api-key credential. Env holds provider-scoped environment/config values such as Cloudflare account/gateway ids.

func (*ApiKeyCredential) CredentialType

func (*ApiKeyCredential) CredentialType() CredentialType

func (*ApiKeyCredential) MarshalJSON

func (c *ApiKeyCredential) MarshalJSON() ([]byte, error)

func (*ApiKeyCredential) UnmarshalJSON

func (c *ApiKeyCredential) UnmarshalJSON(data []byte) error

type AuthCheck

type AuthCheck struct {
	Source string   `json:"source,omitempty"`
	Type   AuthType `json:"type"`
}

AuthCheck reports whether a provider has complete auth configuration.

type AuthContext

type AuthContext interface {
	// Env resolves one environment variable; ok is false when unset or
	// blank.
	Env(name string) (value string, ok bool)
	// FileExists reports whether a file exists. Supports a leading ~.
	FileExists(path string) bool
}

AuthContext is environment access for auth resolution. Injectable for tests.

func DefaultProviderAuthContext

func DefaultProviderAuthContext() AuthContext

DefaultProviderAuthContext returns the ambient AuthContext: env vars from the process environment, file existence via the filesystem (pi reads process.env and node:fs; pig uses os and always supports files).

type AuthEvent

type AuthEvent struct {
	Type string `json:"type"`
	// info
	Message string         `json:"message,omitempty"`
	Links   []AuthInfoLink `json:"links,omitempty"`
	// auth_url
	URL          string `json:"url,omitempty"`
	Instructions string `json:"instructions,omitempty"`
	// device_code
	UserCode         string `json:"userCode,omitempty"`
	VerificationURI  string `json:"verificationUri,omitempty"`
	IntervalSeconds  *int64 `json:"intervalSeconds,omitempty"`
	ExpiresInSeconds *int64 `json:"expiresInSeconds,omitempty"`
}

AuthEvent is one progress notification from a login flow. Type is "info", "auth_url", "device_code", or "progress"; exactly the matching fields are set.

type AuthInfoLink struct {
	URL   string `json:"url"`
	Label string `json:"label,omitempty"`
}

AuthInfoLink is a link rendered alongside an info event.

type AuthInteraction

type AuthInteraction interface {
	Prompt(prompt AuthPrompt) (string, error)
	Notify(event AuthEvent)
}

AuthInteraction serves both api-key and OAuth login flows.

Prompt shows one prompt and returns the entered/selected string (select returns the option id); an error means cancel/abort. Per-prompt cancellation uses the prompt context. Notify delivers a non-blocking progress event.

type AuthOperationOptions

type AuthOperationOptions struct{}

AuthOperationOptions carried cancellation in pi; pig passes a Go context at call sites instead.

type AuthPrompt

type AuthPrompt struct {
	Type        string             `json:"type"` // "text" | "secret" | "select" | "manual_code"
	Message     string             `json:"message"`
	Placeholder string             `json:"placeholder,omitempty"`
	Options     []AuthPromptOption `json:"options,omitempty"`
}

AuthPrompt is a prompt shown to the user during login. pi attaches a per-prompt AbortSignal so a flow can cancel a pending prompt when an out-of-band event resolves the step; pig hands the prompt's context to the interaction call instead (see AuthInteraction).

type AuthPromptOption

type AuthPromptOption struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
}

AuthPromptOption is one selectable option of a select prompt.

type AuthResolutionOverrides

type AuthResolutionOverrides struct {
	APIKey string
	Env    types.ProviderEnv
	// MinOAuthValidityMs requires this much remaining OAuth-token validity;
	// defaults to five minutes.
	MinOAuthValidityMs int64
}

AuthResolutionOverrides adjust one auth resolution.

type AuthResult

type AuthResult struct {
	Auth ModelAuth
	// Env holds provider-scoped environment/config values resolved from
	// credentials and ambient context.
	Env types.ProviderEnv `json:"env,omitempty"`
	// Source is a human-readable label for status UI: "ANTHROPIC_API_KEY",
	// "OAuth", "~/.aws/credentials".
	Source string `json:"source,omitempty"`
}

AuthResult is the result of resolving auth for a model.

func ResolveProviderAuth

func ResolveProviderAuth(ctx context.Context, source AuthSource, credentials CredentialStore, authContext AuthContext, overrides *AuthResolutionOverrides) (*AuthResult, error)

ResolveProviderAuth resolves auth shared by the Models and the (deferred) image-generation chain collections. A stored credential owns the provider: ambient/env is consulted only when nothing is stored. No silent env fallback after a failed refresh or for a credential type without a matching handler.

type AuthSource

type AuthSource interface {
	ID() string
	Auth() ProviderAuth
}

AuthSource is the structural provider input of ResolveProviderAuth (pi: { id, auth }).

type AuthType

type AuthType string

AuthType discriminates auth methods.

const (
	AuthTypeAPIKey AuthType = "api_key"
	AuthTypeOAuth  AuthType = "oauth"
)

type Credential

type Credential interface {
	CredentialType() CredentialType
}

Credential is one type-tagged credential per provider — the shape of today's auth.json. Concrete types: ApiKeyCredential, OAuthCredential.

func UnmarshalCredential

func UnmarshalCredential(data []byte) (Credential, error)

UnmarshalCredential decodes one credential, dispatching on its "type" field.

type CredentialInfo

type CredentialInfo struct {
	ProviderID string         `json:"providerId"`
	Type       CredentialType `json:"type"`
}

CredentialInfo is non-secret credential metadata for account/status enumeration.

type CredentialStore

type CredentialStore interface {
	// Read the stored credential, possibly expired. Display/status use;
	// resolved request auth comes from Models.GetAuth.
	Read(ctx context.Context, providerID string) (Credential, error)
	// List stored credential metadata without resolving or exposing secrets.
	// Implementations must not execute configured API-key commands while
	// listing.
	List(ctx context.Context) ([]CredentialInfo, error)
	// Modify is the serialized write path. fn sees the current credential
	// because correct writes (refresh, login-during-refresh) depend on it;
	// return the new credential, or nil to leave the entry unchanged.
	// Mutual exclusion is per provider id, cross-process too where the
	// backing store supports it (e.g. a file lock). Returns the post-write
	// credential; fn errors propagate.
	Modify(ctx context.Context, providerID string, fn func(current Credential) (Credential, error)) (Credential, error)
	// Delete removes a credential (logout). Implementations serialize this
	// against Modify.
	Delete(ctx context.Context, providerID string) error
}

CredentialStore is app-owned credential storage, keyed by provider id, one credential per provider. Modify is the only write path, so every mutation is a serialized read-modify-write; Models runs OAuth refresh inside Modify so concurrent requests cannot double-refresh a rotated token. The app persists a credential after login via Modify(providerID, func(Credential) (Credential, error)).

Error semantics: Read returns (nil, nil) for missing entries. Methods fail only on storage failure; Models wraps such errors in a ModelsError with code "auth". Best-effort stores that serve an in-memory view and record persistence errors internally (like coding-agent's AuthStorage) are valid implementations.

type CredentialType

type CredentialType string

CredentialType discriminates stored credentials.

const (
	CredentialTypeAPIKey CredentialType = "api_key"
	CredentialTypeOAuth  CredentialType = "oauth"
)

type DeviceCodePollOptions

type DeviceCodePollOptions[T any] struct {
	// IntervalSeconds is the initial poll interval; 0 uses the RFC default.
	IntervalSeconds int64
	// ExpiresInSeconds bounds the whole flow; 0 means no deadline.
	ExpiresInSeconds    int64
	WaitBeforeFirstPoll bool
	Poll                func() DeviceCodePollResult[T]
	// Ctx cancels the wait (pi: signal; pi's cancel message becomes the
	// ctx-caused error text).
	Ctx context.Context
}

DeviceCodePollOptions bounds one device-code poll loop (pi: OAuthDeviceCodePollOptions; signal → ctx).

type DeviceCodePollResult

type DeviceCodePollResult[T any] struct {
	Status DeviceCodePollStatus
	// IntervalSeconds carries the server-provided new interval of a
	// slow_down response (pi: optional intervalSeconds).
	IntervalSeconds int64
	Message         string
	Value           T
}

DeviceCodePollResult is one poll callback outcome (pi: OAuthDeviceCodePollResult<T>).

type DeviceCodePollStatus

type DeviceCodePollStatus string

DeviceCodePollStatus discriminates one poll outcome.

const (
	DeviceCodePending  DeviceCodePollStatus = "pending"
	DeviceCodeSlowDown DeviceCodePollStatus = "slow_down"
	DeviceCodeFailed   DeviceCodePollStatus = "failed"
	DeviceCodeComplete DeviceCodePollStatus = "complete"
)

type GitHubCopilotOAuth

type GitHubCopilotOAuth struct{}

GitHubCopilotOAuth is the GitHub Copilot subscription OAuth auth (pi: githubCopilotOAuth).

func (GitHubCopilotOAuth) IsSubscription

func (GitHubCopilotOAuth) IsSubscription() bool

func (GitHubCopilotOAuth) Login

func (GitHubCopilotOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

func (GitHubCopilotOAuth) LoginLabel

func (GitHubCopilotOAuth) LoginLabel() string

func (GitHubCopilotOAuth) Name

func (GitHubCopilotOAuth) Name() string

func (GitHubCopilotOAuth) Refresh

func (GitHubCopilotOAuth) ToAuth

func (GitHubCopilotOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives the credential-specific proxy endpoint for each request (pi: toAuth).

type InMemoryCredentialStore

type InMemoryCredentialStore struct {
	// contains filtered or unexported fields
}

InMemoryCredentialStore is the default in-memory credential store. Apps inject persistent stores. Keyed by provider id, one credential per provider; see CredentialStore. Writes are serialized per provider.

func (*InMemoryCredentialStore) Delete

func (s *InMemoryCredentialStore) Delete(ctx context.Context, providerID string) error

Delete removes a credential (logout), serialized against Modify.

func (*InMemoryCredentialStore) List

List returns stored credential metadata without exposing secrets.

func (*InMemoryCredentialStore) Modify

func (s *InMemoryCredentialStore) Modify(ctx context.Context, providerID string, fn func(current Credential) (Credential, error)) (Credential, error)

Modify is the serialized write path: fn runs under the provider's lock and sees the current credential; returning nil leaves the entry unchanged. The post-write credential is returned.

func (*InMemoryCredentialStore) Read

func (s *InMemoryCredentialStore) Read(ctx context.Context, providerID string) (Credential, error)

Read returns the stored credential, possibly expired; (nil, nil) when missing.

type KimiCodingOAuth

type KimiCodingOAuth struct{}

KimiCodingOAuth is the Kimi Code subscription OAuth auth (pi: kimiCodingOAuth).

func (KimiCodingOAuth) IsSubscription

func (KimiCodingOAuth) IsSubscription() bool

func (KimiCodingOAuth) Login

func (KimiCodingOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow.

func (KimiCodingOAuth) LoginLabel

func (KimiCodingOAuth) LoginLabel() string

func (KimiCodingOAuth) Name

func (KimiCodingOAuth) Name() string

func (KimiCodingOAuth) Refresh

func (KimiCodingOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh exchanges the refresh token.

func (KimiCodingOAuth) ToAuth

func (KimiCodingOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from a valid credential.

type LoginOptions added in v1.0.0

type LoginOptions struct {
	// GetDeviceId returns the stable ID of this app installation, e.g. sent
	// to OpenAI as its agent host ID. Called only by login flows that need
	// it, so apps can create the ID on first use and must return the same
	// ID on every later call.
	GetDeviceId func() string
	// AgentName is the name this app introduces itself with during login,
	// e.g. OpenAI's agent name hint and Codex originator. Defaults to pi's
	// own name (pig keeps the pi spelling as the default protocol value).
	AgentName string
}

LoginOptions is app-supplied context for OAuth login (pi: LoginOptions).

type MetaOAuth added in v0.86.1

type MetaOAuth struct{}

MetaOAuth is the Meta (Muse subscription) OAuth auth method (pi: metaOAuth).

func (MetaOAuth) IsSubscription added in v0.86.1

func (MetaOAuth) IsSubscription() bool

func (MetaOAuth) Login added in v0.86.1

func (MetaOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow.

func (MetaOAuth) LoginLabel added in v0.86.1

func (MetaOAuth) LoginLabel() string

func (MetaOAuth) Name added in v0.86.1

func (MetaOAuth) Name() string

func (MetaOAuth) Refresh added in v0.86.1

func (MetaOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh re-mints the API key from the stored identity token.

func (MetaOAuth) ToAuth added in v0.86.1

func (MetaOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from the stored credential (pi: toAuth).

type ModelAuth

type ModelAuth struct {
	APIKey  string                `json:"apiKey,omitempty"`
	Headers types.ProviderHeaders `json:"headers,omitempty"`
	BaseURL string                `json:"baseUrl,omitempty"`
}

ModelAuth is the request auth for a single model request. If a value cannot be expressed as APIKey, Headers, or BaseURL, it is provider config, not auth.

type ModelsError

type ModelsError struct {
	Code ModelsErrorCode
	// contains filtered or unexported fields
}

ModelsError carries a Models error code. Callers surface Error() only, so the underlying reason is folded into the message (pi: withCauseDetail) and remains reachable via Unwrap.

func NewModelsError

func NewModelsError(code ModelsErrorCode, message string, cause error) *ModelsError

NewModelsError builds a ModelsError; cause may be nil.

func (*ModelsError) Error

func (e *ModelsError) Error() string

func (*ModelsError) Unwrap

func (e *ModelsError) Unwrap() error

type ModelsErrorCode

type ModelsErrorCode string

ModelsErrorCode classifies Models failures.

const (
	ModelsErrorModelSource     ModelsErrorCode = "model_source"
	ModelsErrorModelValidation ModelsErrorCode = "model_validation"
	ModelsErrorProvider        ModelsErrorCode = "provider"
	ModelsErrorStream          ModelsErrorCode = "stream"
	ModelsErrorAuth            ModelsErrorCode = "auth"
	ModelsErrorOAuth           ModelsErrorCode = "oauth"
)

type OAuthAuth

type OAuthAuth interface {
	// Name is a display name, e.g. "Anthropic (Claude Pro/Max)".
	Name() string
	// IsSubscription reports whether access through this auth method is
	// backed by a provider subscription (pi: optional isSubscription).
	IsSubscription() bool
	// LoginLabel is the selector label for the OAuth login option, e.g.
	// "Sign in with SuperGrok or X Premium"; empty when none (pi: optional
	// loginLabel).
	LoginLabel() string
	// Login runs the provider-owned login flow.
	Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)
	// Refresh exchanges the refresh token. Network call; errors on failure
	// (invalid_grant etc.). Models runs it under the store lock.
	Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)
	// ToAuth derives request auth from a valid credential,
	// side-effect-free. Covers per-credential baseUrl (GitHub Copilot).
	ToAuth(credential *OAuthCredential) (*ModelAuth, error)
}

OAuthAuth is OAuth auth. The Refresh/ToAuth split lets Models own the locked refresh pattern: Refresh produces a credential, ToAuth derives request auth from whatever credential ends up stored.

type OAuthCallbackOrManual added in v1.0.0

type OAuthCallbackOrManual[T any] struct {
	// Type is "callback" or "manual".
	Type string
	// Value is the completed callback value when Type is "callback".
	Value T
	// Input is the pasted text when Type is "manual".
	Input string
}

OAuthCallbackOrManual is the result of waiting for the browser callback or a pasted code (pi: the { type: "callback", value } | { type: "manual", input } union).

func WaitForCallbackOrManualInput added in v1.0.0

func WaitForCallbackOrManualInput[T any](interaction AuthInteraction, callback *OAuthCallbackServer[T], message string, placeholder string) (OAuthCallbackOrManual[T], error)

WaitForCallbackOrManualInput waits for the browser callback, or for the user to paste the code or redirect URL when the browser cannot reach the loopback server (for example over SSH). Without a callback server only the manual prompt is used (pi: waitForCallbackOrManualInput). pig's AuthInteraction has no per-prompt abort, so a prompt that returns after the callback settles is simply ignored (declared deviation — the UI layer cancels its own dialog).

type OAuthCallbackOutcome added in v1.0.0

type OAuthCallbackOutcome[T any] struct {
	Value     T
	Err       error
	Cancelled bool
}

OAuthCallbackOutcome is one resolution of the callback wait. Cancel resolves with Cancelled set and a zero Value (pi: wait() → undefined).

type OAuthCallbackServer added in v1.0.0

type OAuthCallbackServer[T any] struct {
	// contains filtered or unexported fields
}

OAuthCallbackServer is one loopback callback listener (pi: OAuthCallbackServer<T>).

func StartOAuthCallbackServer added in v1.0.0

func StartOAuthCallbackServer[T any](options OAuthCallbackServerOptions[T]) (*OAuthCallbackServer[T], error)

StartOAuthCallbackServer listens and serves the callback route (pi: startOAuthCallbackServer). The listen is synchronous: an occupied port fails the call, and each flow decides whether to degrade to manual input (anthropic/codex catch) or propagate (openrouter).

func (*OAuthCallbackServer[T]) Cancel added in v1.0.0

func (s *OAuthCallbackServer[T]) Cancel()

Cancel stops waiting for the browser unless a callback is already being completed (pi: cancel).

func (*OAuthCallbackServer[T]) Close added in v1.0.0

func (s *OAuthCallbackServer[T]) Close()

Close stops waiting (with an error, matching pi) and releases the port (pi: close).

func (*OAuthCallbackServer[T]) OutcomeChan added in v1.0.0

func (s *OAuthCallbackServer[T]) OutcomeChan() <-chan OAuthCallbackOutcome[T]

OutcomeChan resolves with the single wait outcome (pi: wait()).

func (*OAuthCallbackServer[T]) RedirectURI added in v1.0.0

func (s *OAuthCallbackServer[T]) RedirectURI() string

RedirectURI is the loopback URL the provider redirects to (pi: redirectUri).

func (*OAuthCallbackServer[T]) Wait added in v1.0.0

func (s *OAuthCallbackServer[T]) Wait() (T, error)

Wait blocks until the callback completes or the wait is cancelled; a cancelled wait returns the zero value and a nil error (pi: wait() → undefined).

type OAuthCallbackServerOptions added in v1.0.0

type OAuthCallbackServerOptions[T any] struct {
	// ProviderName is used on the browser page, for example `OpenAI`.
	ProviderName string
	// Host is the address to listen on.
	Host string
	// Port is the port to listen on; 0 picks a free port.
	Port int
	Path string
	// RedirectHost is the host in the redirect URI when it differs from
	// Host, for example `localhost`.
	RedirectHost string
	// State is the expected state parameter; empty skips the state check
	// (pi: omit when the provider does not send one — no provider sends an
	// empty state, so the empty-string encoding is safe).
	State string
	// Complete finishes the sign-in with the received code before the
	// browser page is sent, so the page can show exchange failures. Pass an
	// identity function to exchange the code later.
	Complete func(ctx context.Context, code string) (T, error)
	// Ctx is pi's signal: aborting cancels the wait ("Login cancelled"),
	// and an already-cancelled Ctx fails the start.
	Ctx context.Context
	// Timeout fails the wait after this long; zero waits indefinitely (pi:
	// timeoutMs).
	Timeout time.Duration
}

OAuthCallbackServerOptions configures one shared callback server (pi: OAuthCallbackServerOptions<T>).

type OAuthCredential

type OAuthCredential struct {
	OAuthCredentials
}

OAuthCredential is a stored canonical OAuth credential.

func RefreshStoredOAuthCredential added in v1.0.3

func RefreshStoredOAuthCredential(ctx context.Context, credentials CredentialStore, providerID string, oauth OAuthAuth, needsRefresh func(*OAuthCredential) bool) (*OAuthCredential, error)

RefreshStoredOAuthCredential refreshes a stored OAuth credential under the credential-store lock and persists the result before the lock is released. needsRefresh is re-checked under the lock, so concurrent callers and processes refresh only once.

ctx cancels only the wait for the lock. Once a refresh starts, the provider may already have rotated the refresh token, so the refresh and its persistence ignore ctx and are bounded only by the refresh timeout — a cancelled caller must not discard the only valid refresh token (pi v1.0.3 bde882c74). pi arms a dedicated lock-wait signal and disarms it from inside fn; pig's CredentialStore.Modify cannot detach the two, so the modify runs on a context the caller cannot cancel and ctx is re-checked at fn entry instead: an aborted caller waits out the lock acquisition and then errors without refreshing (recorded deviation, same observable outcome). Request auth and model-list refresh share this path (v1.0.3).

func (*OAuthCredential) CredentialType

func (*OAuthCredential) CredentialType() CredentialType

func (*OAuthCredential) MarshalJSON

func (c *OAuthCredential) MarshalJSON() ([]byte, error)

func (*OAuthCredential) UnmarshalJSON

func (c *OAuthCredential) UnmarshalJSON(data []byte) error

type OAuthCredentials

type OAuthCredentials struct {
	Refresh string `json:"refresh"`
	Access  string `json:"access"`
	// Expires is a Unix timestamp in milliseconds.
	Expires int64          `json:"expires"`
	Extra   map[string]any `json:"-"`
}

OAuthCredentials is the OAuth token data returned by extension compatibility flows; Extra preserves further token fields on roundtrip.

type OpenAIChatGPTOAuth added in v1.0.0

type OpenAIChatGPTOAuth struct{}

OpenAIChatGPTOAuth is the OpenAI (ChatGPT subscription) OAuth auth (pi: openaiChatGPTOAuth).

func (OpenAIChatGPTOAuth) IsSubscription added in v1.0.0

func (OpenAIChatGPTOAuth) IsSubscription() bool

func (OpenAIChatGPTOAuth) Login added in v1.0.0

func (OpenAIChatGPTOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow.

func (OpenAIChatGPTOAuth) LoginLabel added in v1.0.0

func (OpenAIChatGPTOAuth) LoginLabel() string

func (OpenAIChatGPTOAuth) Name added in v1.0.0

func (OpenAIChatGPTOAuth) Name() string

func (OpenAIChatGPTOAuth) Refresh added in v1.0.0

Refresh exchanges the refresh token (pi: refresh).

func (OpenAIChatGPTOAuth) ToAuth added in v1.0.0

func (OpenAIChatGPTOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from a valid credential (pi: toAuth).

type OpenAICodexOAuth

type OpenAICodexOAuth struct{}

OpenAICodexOAuth is the OpenAI Codex (ChatGPT Plus/Pro) OAuth auth (pi: openaiCodexOAuth). pi has no loginLabel; LoginLabel stays empty.

func (OpenAICodexOAuth) IsSubscription

func (OpenAICodexOAuth) IsSubscription() bool

func (OpenAICodexOAuth) Login

func (OpenAICodexOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow, dispatching on the method select (pi: login).

func (OpenAICodexOAuth) LoginLabel

func (OpenAICodexOAuth) LoginLabel() string

func (OpenAICodexOAuth) Name

func (OpenAICodexOAuth) Name() string

func (OpenAICodexOAuth) Refresh

func (OpenAICodexOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh exchanges the refresh token (pi: refreshOpenAICodexToken).

func (OpenAICodexOAuth) ToAuth

func (OpenAICodexOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from a valid credential (pi: toAuth — the access token authenticates as the API key).

type OpenRouterOAuth added in v1.0.0

type OpenRouterOAuth struct{}

OpenRouterOAuth is the OpenRouter OAuth auth (pi: openRouterOAuth).

func (OpenRouterOAuth) IsSubscription added in v1.0.0

func (OpenRouterOAuth) IsSubscription() bool

func (OpenRouterOAuth) Login added in v1.0.0

func (OpenRouterOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow.

func (OpenRouterOAuth) LoginLabel added in v1.0.0

func (OpenRouterOAuth) LoginLabel() string

func (OpenRouterOAuth) Name added in v1.0.0

func (OpenRouterOAuth) Name() string

func (OpenRouterOAuth) Refresh added in v1.0.0

func (OpenRouterOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh is a no-op: the stored credential is a permanent API key (pi: refresh returns the credential unchanged).

func (OpenRouterOAuth) ToAuth added in v1.0.0

func (OpenRouterOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from a valid credential.

type ProviderAuth

type ProviderAuth struct {
	APIKey ApiKeyAuth
	OAuth  OAuthAuth
}

ProviderAuth is provider auth. At least one of APIKey/OAuth must be present: even ambient-credential providers and keyless local servers provide APIKey auth whose Resolve reports whether the provider is configured.

type XaiOAuth

type XaiOAuth struct{}

XaiOAuth is the xAI (Grok/X subscription) OAuth auth method (pi: xaiOAuth).

func (XaiOAuth) IsSubscription

func (XaiOAuth) IsSubscription() bool

func (XaiOAuth) Login

func (XaiOAuth) Login(ctx context.Context, interaction AuthInteraction, options *LoginOptions) (*OAuthCredential, error)

Login runs the provider-owned login flow.

func (XaiOAuth) LoginLabel

func (XaiOAuth) LoginLabel() string

func (XaiOAuth) Name

func (XaiOAuth) Name() string

func (XaiOAuth) Refresh

func (XaiOAuth) Refresh(ctx context.Context, credential *OAuthCredential) (*OAuthCredential, error)

Refresh exchanges the refresh token.

func (XaiOAuth) ToAuth

func (XaiOAuth) ToAuth(credential *OAuthCredential) (*ModelAuth, error)

ToAuth derives request auth from the stored credential (pi: toAuth).

Jump to

Keyboard shortcuts

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