auth

package
v0.10.3 Latest Latest
Warning

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

Go to latest
Published: May 20, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package auth manages per-machine credential storage for hygge.

What lives here

Provider authentication material — API keys today, OAuth tokens in a future revision. These secrets are intentionally *not* part of the human-edited TOML config files, which often end up checked in to dotfiles repositories. They live in a per-machine JSON file under $XDG_STATE_HOME.

Storage format

JSON at $XDG_STATE_HOME/hygge/auth.json (fallback: $HOME/.local/state/hygge/auth.json). The parent directory is created with mode 0o700; the file itself is written with mode 0o600. Atomic writes via temp-file + rename, matching the internal/state package.

Single-process semantics

Like internal/state, v0.1 does not coordinate writes across processes. Concurrent hygge invocations that mutate the auth store in overlapping windows may lose updates. This is acceptable for v0.1 where hygge is run as a single foreground process.

Index

Constants

This section is empty.

Variables

View Source
var ErrCorrupt = errors.New("auth: corrupt file")

ErrCorrupt is returned (wrapped) when the auth file exists but cannot be decoded as valid JSON conforming to the known schema. It covers empty files, malformed JSON, and files containing unknown top-level fields.

Functions

func CodexAPIEndpoint

func CodexAPIEndpoint() string

CodexAPIEndpoint returns the Codex responses API endpoint.

func ExtractAccountID

func ExtractAccountID(token string) string

ExtractAccountID extracts the ChatGPT account ID from a JWT token.

func Path

func Path(opts LoadOptions) (string, error)

Path returns the resolved path to auth.json for the given options. The file need not exist.

func Remove

func Remove(provider string, opts LoadOptions) error

Remove deletes the credential for provider and persists the store. Idempotent — removing an absent provider is not an error.

func Set

func Set(provider string, cred Credential, opts LoadOptions) error

Set writes (or replaces) the credential for provider and persists the store to disk atomically. If cred.AddedAt is the zero time, Set fills it with the current time. Returns an error if loading the prior store fails or the disk write fails.

Types

type Credential

type Credential struct {
	Type CredentialType `json:"type"`

	// API key shape:
	APIKey string `json:"api_key,omitempty"`

	// OAuth shape:
	AccessToken  string    `json:"access_token,omitempty"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	ExpiresAt    time.Time `json:"expires_at"`
	// AccountID is the ChatGPT account ID extracted from the JWT.
	// Used as the ChatGPT-Account-Id header for organization subscriptions.
	AccountID string `json:"account_id,omitempty"`

	// Common:
	AddedAt time.Time `json:"added_at"`
}

Credential is one provider's stored auth material. Only one of the two shape-specific field groups is populated, determined by Type.

type CredentialType

type CredentialType string

CredentialType discriminates the shape of a stored Credential.

const (
	// CredAPIKey selects the API-key shape: the [Credential.APIKey] field
	// is populated; the OAuth-related fields are zero.
	CredAPIKey CredentialType = "api_key"

	// CredOAuth selects the OAuth shape: the AccessToken, RefreshToken,
	// and ExpiresAt fields are populated.
	CredOAuth CredentialType = "oauth"
)

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceAuthID string
	UserCode     string
	Interval     int    // poll interval in seconds
	VerifyURL    string // auth.openai.com/codex/device
}

DeviceCodeResponse is returned by the device authorization endpoint.

func StartDeviceAuth

func StartDeviceAuth(ctx context.Context) (*DeviceCodeResponse, error)

StartDeviceAuth initiates the OpenAI Codex device authorization flow.

type LoadOptions

type LoadOptions struct {
	// HomeDir overrides $HOME for XDG fallback computation.  Empty =
	// real HOME.
	HomeDir string

	// XDGStateHome overrides $XDG_STATE_HOME.  Empty = real env or
	// fallback.
	XDGStateHome string
}

LoadOptions configures Load, [Save], Path, Set, and Remove. The zero value uses real environment variables and the real home directory. Mirrors internal/state.LoadOptions.

type OAuthTokens

type OAuthTokens struct {
	IDToken      string `json:"id_token"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
}

OAuthTokens is the token response from the OAuth token endpoint.

func PollDeviceAuth

func PollDeviceAuth(ctx context.Context, deviceAuthID, userCode string, intervalSec int) (*OAuthTokens, error)

PollDeviceAuth polls the token endpoint until the user approves or the context is cancelled.

func RefreshAccessToken

func RefreshAccessToken(ctx context.Context, refreshToken string) (*OAuthTokens, error)

RefreshAccessToken uses a refresh token to obtain new access/refresh tokens.

type Store

type Store struct {
	// Providers maps provider name → credential.
	Providers map[string]Credential `json:"providers"`
}

Store is the loaded auth file. Construct via Load. The zero value is valid and represents an empty store.

func Load

func Load(opts LoadOptions) (*Store, error)

Load reads the auth file from disk. If the file does not exist, Load returns an empty Store (with an initialised Providers map) and a nil error — a missing file on first run is not an error. If the file exists but cannot be decoded, Load returns ErrCorrupt wrapping the underlying error.

func (*Store) Get

func (s *Store) Get(provider string) (Credential, bool)

Get returns the credential stored for provider and a found flag. The second return value is false when the provider is not in the store.

func (*Store) List

func (s *Store) List() []string

List returns the provider names in the store, sorted ascending.

Jump to

Keyboard shortcuts

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