class Authentication

Loads and refreshes the local Codex CLI ChatGPT credentials.

Nested Classes and Modules

class Error

Raised when Codex credentials are missing, invalid, or cannot be refreshed.

Definitions

def initialize(codex_home: ENV.fetch("CODEX_HOME", DEFAULT_CODEX_HOME), client: nil, endpoint: ISSUER)

Initialize credential loading for a Codex home directory.

Signature

option :codex_home String

The directory containing auth.json.

option :client Interface(:call) | Nil

An optional OAuth HTTP client.

option :endpoint String | Async::HTTP::Endpoint

The OAuth issuer endpoint.

Implementation

def initialize(codex_home: ENV.fetch("CODEX_HOME", DEFAULT_CODEX_HOME), client: nil, endpoint: ISSUER)
	@codex_home = codex_home
	@auth_path = File.join(codex_home, "auth.json")
	@endpoint = Async::HTTP::Endpoint[endpoint]
	@client = client || Async::HTTP::Client.new(@endpoint)
	@owns_client = client.nil?
	@semaphore = Async::Semaphore.new(1)
end

def credentials(refresh: false)

Load valid credentials and refresh them when requested or stale.

Signature

option :refresh Boolean

Force a credential refresh.

returns Hash

The access token, account ID, and optional residency.

raises Laiya::Provider::Codex::Authentication::Error

If the credentials cannot be used.

Implementation

def credentials(refresh: false)
	@semaphore.acquire do
		with_auth_lock do
			document = read_auth
			validate_auth(document)
			tokens = document.fetch("tokens")
			
			if refresh || stale?(tokens, document)
				document = refresh_auth(document)
				tokens = document.fetch("tokens")
			end
			
			account = account_id(tokens)
			raise Error, "Codex ChatGPT account ID is missing" unless account
			
			{
				access_token: tokens.fetch("access_token"),
				account_id: account,
				residency: residency(tokens.fetch("access_token")),
			}
		end
	end
end

def close

Close the OAuth client when this object created it.

Implementation

def close
	@client.close if @owns_client
end