codexauth

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 17 Imported by: 0 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

Package codexauth is ccdad's Codex credential: the record it stores, the hash the needs-relogin mark is made of, and (from a later change) the device login, the token refresh and the refresh classifier.

The record is ccdad's OWN. Nothing in Claude Code reads it, nothing in codex's own auth.json is read to produce it, and it never reaches Claude Code's credentials file: the key is deliberately absent from the list of keys that travel with a Claude login.

Index

Constants

View Source
const (
	// ClientID is the public client codex ships. There is no third-party client
	// registration for this API, so ccdad presents the same one rather than
	// inventing an identity the issuer has never seen.
	ClientID = "app_EMoamEEZ73f0CkXaXp7hrann"

	// DeviceAuthURL mints a user code.
	DeviceAuthURL = AuthBaseURL + deviceAuthPath
	// DeviceTokenURL is polled until the user approves the code.
	DeviceTokenURL = AuthBaseURL + deviceTokenPath
	// DeviceVerifyURL is the page the user opens to type the code.
	DeviceVerifyURL = AuthBaseURL + deviceVerifyPath
	// DeviceRedirectURI is what the authorization-code exchange must declare.
	// It is not a listener ccdad binds — no device-code login has one — but the
	// issuer matches it against the grant, so it has to be exactly this.
	DeviceRedirectURI = AuthBaseURL + deviceCallbackPath
	// TokenURL serves both the authorization-code exchange and the refresh.
	// They are not the same request: the exchange is form-encoded and the
	// refresh is JSON, and sending either encoding to the other is refused.
	TokenURL = AuthBaseURL + tokenPath
)
View Source
const (
	// DeviceLoginWindow is how long a user code lives. The prompt codex prints
	// says fifteen minutes and its own poll loop caps at the same figure.
	//
	// It is ccdad's own clock rather than a field off the wire. The user-code
	// response does carry an expiry, and its TYPE is not determinable: codex's
	// response struct ignores the field entirely, so nothing in the source says
	// whether it is an ISO string, epoch seconds or a duration. Guessing wrong
	// is either a login that gives up in seconds or one that never gives up, so
	// ccdad uses the documented window instead of reading a field it cannot
	// type.
	DeviceLoginWindow = 15 * time.Minute

	// DefaultDeviceInterval is the wait when the response advertised none, or
	// advertised one that does not parse.
	//
	// Zero is what the wire's own default decodes to, and zero is a hot loop
	// against an endpoint that has no advertised budget — which would burn the
	// code before the user finished typing it. A floor is the only safe reading
	// of "the server did not say".
	DefaultDeviceInterval = 5 * time.Second
)
View Source
const (
	// AuthBaseURL is the issuer. Every URL below is built from it, so the set
	// cannot drift a path at a time.
	AuthBaseURL = "https://auth.openai.com"
)

The OAuth surface, measured against codex-cli 0.151.0 and its matching source. Every one of these is a public value: the client id is a PUBLIC client with no secret, and the three URLs are the ones codex itself posts to.

ccdad uses the DEVICE-CODE flow and never the browser one. The authorize page is Cloudflare-challenged — a GET with the full parameter set answers 403 and a "Just a moment..." interstitial under every user agent tried — so a Go client must not fetch it, while the device endpoints answer a bare client with no cookies and no challenge.

Three endpoints ccdad deliberately does NOT have:

  • /oauth/revoke. codex's own login and logout both revoke the stored refresh token server-side before doing anything else, with no undo. ccdad never calls it and never execs those two commands, so a managed account cannot be destroyed by a switch.
  • the RFC-8693 api-key exchange codex runs after a browser login. Its result is stored as OPENAI_API_KEY, and a credential carrying that key infers api-key mode, where refresh is a no-op forever — a subscription account silently converted to a different meter.
  • anything that acquires, stores or replays an anti-bot clearance token, cookie or TLS fingerprint. If an endpoint starts challenging, this feature degrades; it does not evade.
View Source
const DefaultRefreshCooldown = 30 * time.Second

DefaultRefreshCooldown is how long a transiently-failed account is left alone.

It exists because of what the CLIENT does with a 401: codex retries six times over six seconds. Without a cooldown each of those six reaches the token endpoint, so one bad minute upstream becomes six exchanges against a single-use grant.

View Source
const Key = "codexOAuth"

Key is the one ccdad-owned top-level key in a Codex account's credential blob. It is the on-disk name and cannot be renamed: a stored account would become one with no login.

Variables

This section is empty.

Functions

func AccessExpiry

func AccessExpiry(c Credential) (time.Time, bool)

AccessExpiry is when c's ACCESS token expires, and whether that could be read at all.

There is no stored expiry field anywhere in a Codex credential, so this decode is the only source of the figure. Unknown is never zero: a caller handed the zero time would read every unreadable credential as expired in 1970 and refresh the whole fleet on sight, spending a single-use grant per account for nothing.

func NeedsRelogin added in v0.11.0

func NeedsRelogin(a store.Account, b cclink.Blob) bool

NeedsRelogin answers store.Account.NeedsRelogin from the account's stored credential blob, which is where the CURRENT refresh token is.

The mark is a hash of the refresh token whose grant the endpoint rejected, and it means "needs a login" only while the account still holds that token. That is what makes a re-login self-clearing: `ccdad add codex` stores a new token, the hash stops matching, and nothing had to remember to clear a flag.

A blob that carries no codex credential, or one that cannot be parsed, answers FALSE. Such an account is already excluded by the eligibility rule's "has a codex credential" term, and answering true here would put a second refusal on it wearing the wrong reason -- the surface would tell a user to run `ccdad add codex` about an account whose real problem is a missing file.

func RefreshTokenHash

func RefreshTokenHash(refreshToken string) string

RefreshTokenHash names a refresh token without being one.

It is what the needs-relogin mark holds, and the mark lives in accounts.toml -- the 0600-but-plaintext file people paste into an issue -- so the value stored there must not be a credential. A 64-bit prefix is enough: the only comparison ever made is against the hash of the token stored for the SAME account moments later, so the space being guarded is one account's token history rather than every token in the world.

The empty token hashes to the empty string rather than to the hash of "". The mark is compared with equality, and an account that has no refresh token at all must not match a mark written when it had one.

Types

type Claims

type Claims struct {
	// Exp is the token's expiry, and the zero time means the payload carried
	// none. Absent is not an expiry at the epoch.
	Exp time.Time
	// Email is the top-level `email` claim: the human label for the account.
	Email string
	// UserID is the ACCOUNT, and it is the uuid ccdad keys a Codex row on. It
	// comes from the namespaced chatgpt_user_id, falling back to a top-level
	// user_id.
	UserID string
	// AccountID is the WORKSPACE, not the user. Two seats in one team
	// workspace share it, so keying an account on it would let a colleague's
	// login overwrite the first one. It is the quota and sharing-group key and
	// the value the ChatGPT-Account-Id header carries.
	AccountID string
	// PlanType is the raw subscription tier, e.g. free, plus, pro, team,
	// enterprise. It is kept verbatim: an unrecognized tier is a tier this
	// build has not seen rather than an error.
	PlanType string
	// Organizations is the workspaces this identity belongs to, with the role
	// it holds in each. `ccdad add codex` reads it to tell an owner from a
	// member.
	Organizations []Organization
}

Claims is a decoded Codex JWT payload.

NOTHING here is verified. There is no signature check, no issuer check and no audience check, and that is deliberate rather than a shortcut: codex itself parses the payload the same way, and the token ccdad decodes is one ccdad received over TLS from the issuer and stored itself. A signature check would need the issuer's key set, which is a network call on every read of a value that is already trusted by provenance.

The one field that drives behaviour is Exp, and only ever the ACCESS token's. The id_token's exp is one hour, so reading it for expiry would report every stored account as dead within the hour of being added.

func DecodeClaims

func DecodeClaims(jwt string) (Claims, error)

DecodeClaims reads a JWT's payload segment.

A malformed token is an error and a missing CLAIM is not. The difference is the one that decides behaviour: a token ccdad cannot parse at all is a stored credential it must not act on, while a token that simply does not carry a plan type is a perfectly good login about which one field is unknown.

type Credential

type Credential struct {
	IDToken      string    `json:"id_token"`
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	AccountID    string    `json:"account_id"`
	UserID       string    `json:"user_id"`
	LastRefresh  time.Time `json:"last_refresh"`
}

Credential is the JSON object stored under Key.

The two identity fields are named for what the endpoint calls them, because they are easy to swap and the symptom of swapping them is a bearer that is valid for the wrong workspace. AccountID is chatgpt_account_id -- the WORKSPACE -- and is what the proxy sends as the ChatGPT-Account-Id header. UserID is chatgpt_user_id, which is the account's uuid in ccdad's store.

func FromBlob

func FromBlob(b cclink.Blob) (Credential, bool, error)

FromBlob reads the Codex record out of a stored credential blob.

The three answers are distinct on purpose. Absent is the ORDINARY state -- every Claude account is one -- so it is (zero, false, nil) and a caller can ask about every account without treating the majority as broken. Present and unparseable is an error, because reading a truncated write as "no Codex record" would send the account down the Claude path with a token sitting in its file.

func PollDeviceLogin

func PollDeviceLogin(ctx context.Context, client *http.Client, start DeviceStart, sleep func(time.Duration)) (Credential, error)

PollDeviceLogin waits for the user to approve start, then exchanges the authorization code for tokens.

sleep is an argument rather than a call to time.Sleep so a test can drive the wait loop without waiting. Production passes time.Sleep.

The PKCE verifier is NOT generated here: the poll response carries the pair the server already bound to the code, and ccdad forwards the verifier it was given. Minting one would produce a challenge the grant was not issued against.

func (Credential) ToBlob

func (c Credential) ToBlob() cclink.Blob

ToBlob is the credential as a stored blob: one key and nothing else.

A blob rather than raw JSON because store.Add and store.SetCredentials replace the credential file WHOLESALE, so the value handed to them is the whole file. A Codex account has exactly this in it.

type DeviceStart

type DeviceStart struct {
	// DeviceAuthID and UserCode are the pair every poll carries. UserCode is
	// also what the user types on the verification page.
	DeviceAuthID string
	UserCode     string
	// Interval is how long to wait between polls, as the server asked.
	Interval time.Duration
	// ExpiresAt is when the code stops being approvable.
	ExpiresAt time.Time
}

DeviceStart is a device-code login waiting on the user.

func StartDeviceLogin

func StartDeviceLogin(ctx context.Context, client *http.Client) (DeviceStart, error)

StartDeviceLogin asks the issuer for a user code.

It is the whole of ccdad's contact with the login surface before the user acts: nothing is stored, nothing is revoked, and no browser is opened.

type Organization

type Organization struct {
	ID        string
	Title     string
	Role      string
	IsDefault bool
}

Organization is one entry of the organizations claim.

type Outcome

type Outcome struct {
	Kind       OutcomeKind
	Code       string
	Credential Credential
}

Outcome is one refresh attempt's result. Credential is the pair the caller should use: the rotated one after Rotated, the stored one after Adopted, and whatever was on disk after either failure — a caller with a live access token can still serve a request while the grant behind it is being sorted out.

It is the ZERO Credential in exactly one case: a Transient whose Code is "lock_busy" raised on the READ, where nothing could be read off disk to hand back. A "lock_busy" raised after a successful rotation carries the rotated pair, because that pair exists and is the only copy of it anywhere.

type OutcomeKind

type OutcomeKind int

OutcomeKind is what one refresh attempt learned.

Four values and not two, because "it failed" is three different facts with three different consequences: the grant is dead and only a new login helps; somebody else already rotated it and this caller should use theirs; or nothing was learned at all and the account must not be marked.

const (
	// Rotated: this call exchanged the grant and stored the new tokens.
	Rotated OutcomeKind = iota
	// Adopted: another refresher had already rotated it, so this call spent
	// nothing and returns the stored pair.
	Adopted
	// Terminal: the grant is dead. Code names why.
	Terminal
	// Transient: nothing was learned about the grant. Code names the shape.
	// This is NEVER a reason to mark an account.
	Transient
)

func Classify

func Classify(status int, body []byte, err error) (OutcomeKind, string)

Classify maps a token-endpoint answer to Terminal or Transient.

It is Codex-specific and deliberately NOT ccdad's Claude-side wire classifier. That one reports a reused refresh token as transient, which is correct for Claude Code's rotation model and exactly wrong here: a Codex grant is single-use with reuse detection, so retrying a reused token is a loop that can only ever fail, once per client retry, forever.

TERMINAL iff the endpoint answered 401, or the body's error code is one of the three, or a 400 said invalid_grant. RFC 6749 reports an unusable refresh token as a bare invalid_grant without the expired/reused/revoked subtype, so that arm is what keeps a modern answer terminal.

Everything else — transport failure, 5xx, a 429 from the token endpoint, a cancelled context — is TRANSIENT and does not count as an attempt.

func (OutcomeKind) String

func (k OutcomeKind) String() string

type Refresher

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

Refresher is the ONE thing in a ccdad process that exchanges a Codex refresh token.

It exists as a type rather than a function because the single-use grant needs a place to keep two facts: which account is being exchanged right now, and which account is cooling down. Both are per-account, both outlive one call, and neither may be a package-level global — a test would then leak state into the next one.

The lock discipline, which is the whole of its correctness:

  • a per-uuid in-process mutex is held across re-read + POST + save, so two goroutines cannot both read the same grant and both exchange it;
  • the store's cross-process flock is taken INSIDE that, twice — once for the read and once for the write — and NEVER across the POST. Holding a file lock across a network call parks every other ccdad process on the machine for as long as the endpoint takes to answer.

Waiters block on the mutex, re-read, find an access token that is no longer the one they saw, and adopt.

The cost of taking the file lock twice rather than once is that the WRITE can fail on contention after the POST has already spent the grant. That rotated pair is then the only copy there is, so it is held in refreshState.pending and landed at the top of the next call. Dropping it is not an option: the stored refresh token is burned the moment the exchange succeeds, so a discarded rotation leaves the account one refresh away from reuse detection.

func NewRefresher

func NewRefresher(cfg RefresherConfig) *Refresher

NewRefresher builds one. A process has exactly one, shared by everything that can see a 401 for a Codex account.

func (*Refresher) Refresh

func (r *Refresher) Refresh(ctx context.Context, uuid, triggeredBy string) (Outcome, error)

Refresh exchanges uuid's grant, or explains why it did not.

triggeredBy is the access token the caller SAW. If the stored one differs, another refresher has already rotated and this call adopts rather than spending a second grant. An empty triggeredBy means "the caller has no opinion" and always attempts.

The error return is for the things that are not outcomes: the store cannot be opened, the account is not there, its credential is not a Codex one. Every refusal ABOUT THE GRANT is an Outcome with a nil error — and so is store CONTENTION, which is Transient with the code "lock_busy": another ccdad process holding the file lock says nothing about the grant, and it is not even an attempt, so it earns no cooldown either.

type RefresherConfig

type RefresherConfig struct {
	Client   *http.Client
	Now      func() time.Time
	Log      func(format string, a ...any)
	Cooldown time.Duration
}

RefresherConfig builds a Refresher. Every field has a working default, so a caller that only has an *http.Client passes only that.

Jump to

Keyboard shortcuts

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