Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

provider: a ChatGPT token the backend calls expired before its exp is refreshed once and read again (willz on Discord, #2973)

yetone3b8bcc3654d5
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 11d2ebaf0..cb7463d47 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -132,6 +132,7 @@ recorded as a prediction failure (`noPrediction`).
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
- One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<<n`, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a `holdWriter` with its reasoning let through (`thinkingShown`), kept alive past `keepHeldAfter` across the tries (one `keptAlive`), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (`codexFallsBack`; never a compaction) goes on to them (`codexFallBack`: the turn served as `codex/<model>` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. Each try is a `HandedOn` usage record and a try in the trace. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)).
- A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before.
+- A ChatGPT 401 that says the token sent has expired and asks for a refresh (`provider.SignInExpired`, #2973) while its `exp` is ahead renews the account's sign-in once (`provider.NoteExpiredSignIn` from `noteSignIn`), keyed on the token sent, so the next request goes with a fresh one; nothing is marked, and the request fails over as any 401 does ([Providers and accounts](providers-accounts.md), A token called expired).
- A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.
- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.
- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669; Volcengine Ark's "You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST.", #3251, #3276) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, or its offset as Go prints one (four digits, then the zone's name, which isn't read), followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or further off than `longestSaid` isn't read: `longestWritten` (7 days), or `longestMonthly` (35 days) when the refusal says its allowance is a month's (`monthlyWords`: Ark's, Zhipu's 1310 "Weekly/Monthly Limit Exhausted"). Such a reset is the one rest out of quota held past `longestQuota`, to `longestMonthly`; a window read full or the user's own rest is still held to 8 days (`TestMonthlyWrittenResetRestsTheMonth`). Ark's windows as its AccessKey reads them (`volcPlanQuotas`) still reach only its usage card, not routing (#3251). Zhipu's 1308 and 1310 (Z.ai and bigmodel.cn, GLM Coding Plan: "Your limit will reset at 2026-10-15 20:12:13", "您的限额将在 … 重置") write the time with no zone; it is Beijing's, and is read as UTC+8 in those words only (`zhipuResets`, `resetsZhipu`), never when a digit, colon or zone of its own follows (Player on Discord: read by nothing, the key rested `quotaRest` and the refusal said "not asked again before 17:12" while Z.ai said 20:12; `TestZhipuRestsUntilItsReset`). One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). Out of credit or quota on a model that costs credits, where the subscription serves other models free (`catalog.Model.Free`: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; `Provider.PaidBesideFree`), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, `TestOutOfCreditLeavesFreeModels`). A Credits window leaves the free models out the same way, so an account at 100% isn't ranked spent for them: the WorkBuddy plugin's lists them as `notModels` (0.1.23), and the built-in's scopes itself by the provider's last fetched list (`wbSpareFree`; with no list read, every model counts) (plugins#138, hheei: an account at 560 / 560 was still served deepseek-v4.1-flash; `TestWorkBuddyCreditsSpareFreeModels`). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. Cline's daily limit of one free model, 429 "Daily free limit reached on model deepseek/deepseek-v4-flash. Try again in 23h 59m" (the words Cline's own clients read it by, `isClineFreeModelLimitMessage`), rests that model alone (`clineFreeLimit`, `clineModelLimited`, keyed by `restID`) until the time it names (`clineBackIn`, `tryAgainIn`, held to `longestWritten`; `resets`), from a provider whose requests reach Cline's API (`ClinePinnable`: the ClinePass preset, one at cline.bot, the Cline plugin's). The key's other models, free or the plan's, are still served, and the model out of its day is answered with its refusal without asking Cline again (#1398, wuasakura: one free model's 429 sent the whole Cline account to the back; `TestClineFreeLimitRestsTheModel`, `TestClineFreeLimitLeavesOtherModels`). Another vendor's same words, and a Cline 429 that doesn't name the model's limit, rest the key as before. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (`brokeWords`), not a rate limit, on the built-in's raw body and the plugin's `insufficient_quota` alike (`TestCreditsExhaustedIsOutOfCredit`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index b611e95b7..227ed69d5 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -35,6 +35,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (`codexStore.write`: `~/.codex/auth.json`, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
| Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, the usage card's `codexUntil`, session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) |
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, or served a request (`ServedSignIn`), it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
+| A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`). The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say "<user> is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) |
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
diff --git a/internal/gateway/codex_refresh_401_test.go b/internal/gateway/codex_refresh_401_test.go
new file mode 100644
index 000000000..7bbd2b6be
--- /dev/null
+++ b/internal/gateway/codex_refresh_401_test.go
@@ -0,0 +1,193 @@
+package gateway
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// A 401 that says the token has expired and asks for a refresh (#2973) is
+// one a refresh mends, though the token's JWT exp is still ahead: the
+// sign-in is renewed where it is kept, and the next request goes out with
+// the fresh token — not recorded as a failure of other kinds and rested
+// while the account still has its allowance.
+func TestCodexExpired401RefreshesLogin(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ restingUntil.Lock()
+ restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
+ restingUntil.Unlock()
+ t.Cleanup(func() {
+ restingUntil.Lock()
+ restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
+ restingUntil.Unlock()
+ })
+
+ claims := func(m map[string]any) string {
+ b, _ := json.Marshal(m)
+ return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
+ }
+ // the token on disk expires an hour from now: good here, retired at
+ // the vendor, whose answer asks for a refresh (#2973)
+ stale := claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "v": "stale"})
+ auth, err := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
+ "id_token": claims(map[string]any{"email": "[email protected]"}),
+ "access_token": stale,
+ "refresh_token": "r-own",
+ "account_id": "acct-c"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
+ if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), auth, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ var mu sync.Mutex
+ refreshed, served := 0, []string{}
+ tokens := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]string
+ json.NewDecoder(r.Body).Decode(&body)
+ mu.Lock()
+ refreshed++
+ mu.Unlock()
+ // the rotation OpenAI's answer is: a fresh access token, and
+ // another refresh token for the spent one
+ json.NewEncoder(w).Encode(map[string]any{
+ "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "v": "fresh"}),
+ "refresh_token": body["refresh_token"] + "-2"})
+ }))
+ defer tokens.Close()
+ defer provider.CodexTokenURLForTest(tokens.URL)()
+
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.ReadAll(r.Body)
+ tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ mu.Lock()
+ served = append(served, tok)
+ mu.Unlock()
+ if tok == stale {
+ w.WriteHeader(http.StatusUnauthorized)
+ io.WriteString(w, `{"error":{"message":"Your authentication token has expired. Please try refreshing it."}}`)
+ return
+ }
+ w.Header()["Content-Type"] = nil // as the ChatGPT backend sends it
+ io.WriteString(w, sse(
+ `data: {"type":"response.created","response":{"id":"r1"}}`,
+ `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":1,"output_tokens":1}}}`))
+ }))
+ defer up.Close()
+ was := provider.CodexBase
+ provider.CodexBase = up.URL + "/backend-api/codex"
+ t.Cleanup(func() { provider.CodexBase = was })
+
+ if code, _ := post(t, "/v1/responses", `{"model":"codex/gpt-5.5","input":"ping"}`); code != 401 {
+ t.Fatalf("first request: %d, want the vendor's 401 told", code)
+ }
+ mu.Lock()
+ got, hits := append([]string(nil), served...), refreshed
+ mu.Unlock()
+ if hits != 1 {
+ t.Fatalf("the vendor said the token expired and asked for a refresh: the sign-in was renewed %d times, want once", hits)
+ }
+ if len(got) != 1 || got[0] != stale {
+ t.Fatalf("the backend was sent %q, want the stale token once", got)
+ }
+
+ // the backoff a refusal of other kinds rests the account by is over
+ noRests()
+ if code, body := post(t, "/v1/responses", `{"model":"codex/gpt-5.5","input":"ping"}`); code != 200 || !strings.Contains(body, `"status":"completed"`) {
+ t.Fatalf("after the refresh: %d %s", code, body)
+ }
+ mu.Lock()
+ got, hits = append([]string(nil), served...), refreshed
+ mu.Unlock()
+ if hits != 1 {
+ t.Fatalf("the sign-in was renewed %d times after a request was served, want the one", hits)
+ }
+ if len(got) != 2 || got[1] == stale {
+ t.Fatalf("the next request went out with %q, want the fresh token", got)
+ }
+ // the rotation is back where Codex keeps its sign-in, for Codex to find
+ b, err := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
+ if err != nil || !strings.Contains(string(b), "r-own-2") {
+ t.Fatalf("the rotated refresh token didn't reach auth.json: %q %v", b, err)
+ }
+}
+
+// A 401 that says nothing of an expired token leaves the sign-in as it is:
+// a revoked one is #1793's to mark, any other is no refresh's to mend.
+func TestCodexOther401DoesntRefresh(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ restingUntil.Lock()
+ restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
+ restingUntil.Unlock()
+ t.Cleanup(func() {
+ restingUntil.Lock()
+ restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
+ restingUntil.Unlock()
+ })
+
+ claims := func(m map[string]any) string {
+ b, _ := json.Marshal(m)
+ return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
+ }
+ auth, err := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
+ "id_token": claims(map[string]any{"email": "[email protected]"}),
+ "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
+ "refresh_token": "r-own",
+ "account_id": "acct-c"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
+ if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), auth, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ var mu sync.Mutex
+ refreshed := 0
+ tokens := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ refreshed++
+ mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()})})
+ }))
+ defer tokens.Close()
+ defer provider.CodexTokenURLForTest(tokens.URL)()
+
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.ReadAll(r.Body)
+ w.WriteHeader(http.StatusUnauthorized)
+ io.WriteString(w, `{"error":{"message":"Incorrect API key provided"}}`)
+ }))
+ defer up.Close()
+ was := provider.CodexBase
+ provider.CodexBase = up.URL + "/backend-api/codex"
+ t.Cleanup(func() { provider.CodexBase = was })
+
+ post(t, "/v1/responses", `{"model":"codex/gpt-5.5","input":"ping"}`)
+ mu.Lock()
+ hits := refreshed
+ mu.Unlock()
+ if hits != 0 {
+ t.Fatalf("a 401 that says nothing of an expired token renewed the sign-in %d times", hits)
+ }
+}
diff --git a/internal/gateway/signin_revoked.go b/internal/gateway/signin_revoked.go
index ec4115031..e2469f96d 100644
--- a/internal/gateway/signin_revoked.go
+++ b/internal/gateway/signin_revoked.go
@@ -36,7 +36,8 @@ func revokedReply(req *http.Request, why string) *http.Response {
// noteSignIn tells provider what the vendor said of the sign-in req went
// with: a 401 that says it is revoked marks it, a request served clears a
-// mark the account had. The body read is put back for the caller.
+// mark the account had, and one that says the token expired renews it.
+// The body read is put back for the caller.
func noteSignIn(ctx context.Context, a *provider.Account, req *http.Request, res *http.Response) {
if a == nil || res == nil {
return
@@ -47,8 +48,14 @@ func noteSignIn(ctx context.Context, a *provider.Account, req *http.Request, res
case res.StatusCode == http.StatusUnauthorized && res.Body != nil:
b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body}
- if err == nil && provider.SignInRevoked(res.StatusCode, b) {
+ switch {
+ case err != nil:
+ case provider.SignInRevoked(res.StatusCode, b):
provider.NoteRevokedSignIn(ctx, a, req)
+ case provider.SignInExpired(res.StatusCode, b):
+ // expired while its exp was ahead: renewed for the next
+ // request (#2973)
+ provider.NoteExpiredSignIn(ctx, a, req)
}
}
}
diff --git a/internal/provider/account.go b/internal/provider/account.go
index 56372d405..6793e07f7 100644
--- a/internal/provider/account.go
+++ b/internal/provider/account.go
@@ -69,7 +69,11 @@ type Account struct {
// go (google.go).
codeAssist string
- sign func(ctx context.Context, req *http.Request, body []byte) error
+ sign func(ctx context.Context, req *http.Request, body []byte) error
+ // renew is set on a ChatGPT account: its sign-in refreshed in place of
+ // stale, the access token the backend just called expired while it
+ // had time left (codexTokenRenewing, renewSavedLogin).
+ renew func(ctx context.Context, stale string) (tok, accountID string, err error)
body func(body []byte) []byte // request tweaks the backend insists on
models func() []catalog.Model
fetch func(ctx context.Context) ([]catalog.Model, error)
@@ -986,6 +990,9 @@ func codexAccount(home string) (Provider, bool) {
acct.User = codexLiveName(acct.User, bytes.TrimSpace(b))
}
acct.sign = codexSign(func(ctx context.Context) (string, string, error) { return codexToken(ctx, dir) })
+ acct.renew = func(ctx context.Context, stale string) (string, string, error) {
+ return codexTokenRenewing(ctx, dir, stale)
+ }
acct.body = codexBody
acct.models = catalog.Codex
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
@@ -1007,17 +1014,31 @@ func codexAccount(home string) (Provider, bool) {
// sign-in (auth.json or the keychain item, codexStore.write) for Codex to
// find.
func codexToken(ctx context.Context, dir string) (tok, accountID string, err error) {
+ return codexTokenRenewing(ctx, dir, "")
+}
+
+// codexTokenRenewing is codexToken, and with stale, the access token the
+// backend just answered 401 "token expired" for while its exp was still
+// ahead (willz on Discord, #2973: a Team account's), refreshes the
+// sign-in all the same. Unless the store holds another token by now,
+// refreshed meanwhile by Codex or another request, which is returned
+// instead: its refresh token is the one spent already.
+func codexTokenRenewing(ctx context.Context, dir, stale string) (tok, accountID string, err error) {
codexMu.Lock()
defer codexMu.Unlock()
- b, st, err := readCodexLogin(dir, false)
+ // a refresh asked for: the store's own, not a kept read
+ b, st, err := readCodexLogin(dir, stale != "")
var a codexAuth
if err == nil && json.Unmarshal(b, &a) == nil && a.Tokens.AccessToken != "" {
- if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute {
+ if stale != "" {
+ if a.Tokens.AccessToken != stale {
+ return a.Tokens.AccessToken, codexAccountID(a), nil
+ }
+ } else if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute {
return a.Tokens.AccessToken, codexAccountID(a), nil
- }
- // about to be refreshed: the store's own, not a kept read, which
- // Codex may have rotated since (its refresh token spent)
- if st.keychain {
+ } else if st.keychain {
+ // about to be refreshed: the store's own, not a kept read,
+ // which Codex may have rotated since (its refresh token spent)
b, st, err = readCodexLogin(dir, true)
a = codexAuth{}
if err == nil && json.Unmarshal(b, &a) == nil && a.Tokens.AccessToken != "" {
diff --git a/internal/provider/codex_autoreset.go b/internal/provider/codex_autoreset.go
index cccc9c6ee..fd33ea33c 100644
--- a/internal/provider/codex_autoreset.go
+++ b/internal/provider/codex_autoreset.go
@@ -186,13 +186,10 @@ func AutoUseCodexReset(ctx context.Context, user string) (ResetOutcome, error) {
}
var who string
return autoReset.use(user, func(now time.Time) (*time.Time, bool, error) {
- var tok, accountID string
+ var windows []QuotaWindow
+ var resets *ResetCredits
var err error
- who, tok, accountID, err = codexUserToken(ViaLogin(ctx, "codex", user), user)
- if err != nil {
- return nil, false, err
- }
- _, windows, resets, _, _, err := codexWindows(ViaLogin(ctx, "codex", who), tok, accountID)
+ who, windows, resets, err = codexUserWindows(ctx, user)
if err != nil {
return nil, false, err
}
diff --git a/internal/provider/codex_expired.go b/internal/provider/codex_expired.go
new file mode 100644
index 000000000..c2b516284
--- /dev/null
+++ b/internal/provider/codex_expired.go
@@ -0,0 +1,89 @@
+package provider
+
+// A ChatGPT sign-in the backend calls expired while its access token has
+// time left by its own exp (willz on Discord, #2973: two saved Team
+// accounts, /wham/usage answering 401 "Provided authentication token is
+// expired. Please try refreshing it." until each was signed in again).
+// magpie refreshes a token only as its exp nears, so it kept sending the
+// one turned away. Such an answer is mended by one refresh: forced here,
+// and the read made once more with the new token, never more.
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+)
+
+// expiredWords: a 401 that says the access token has expired and asks
+// for a refresh. Not refresh_token_expired ("_" is a word character, so
+// \b doesn't split it there), which says the sign-in itself is gone
+// (revokedWords).
+var expiredWords = regexp.MustCompile(`(?i)\btoken_expired\b|authentication token (is|has) expired|please try refreshing it`)
+
+// SignInExpired says a reply is the vendor's word that the access token
+// it was sent with has expired, for a refresh to mend.
+func SignInExpired(status int, body []byte) bool {
+ return status == http.StatusUnauthorized && expiredWords.Match(body)
+}
+
+// codexRenew refreshes a ChatGPT sign-in in place of stale, the access
+// token the backend called expired (codexTokenRenewing,
+// renewSavedLoginFrom).
+type codexRenew func(ctx context.Context, stale string) (tok, accountID string, err error)
+
+// codexExpired says err is the backend calling the token expired.
+func codexExpired(err error) bool {
+ var se *accountStatusError
+ return errors.As(err, &se) && SignInExpired(se.status, se.body)
+}
+
+// errCodexStillExpired is a usage read turned away as expired again with
+// the token refreshed just for it: nothing magpie holds will do.
+var errCodexStillExpired = errors.New("ChatGPT turned the refreshed sign-in away too; sign in to this account again")
+
+// codexWindowsRenewing is codexWindows, read once more with the sign-in
+// renewed when the backend calls token expired. A refresh refused says
+// to sign in again (codexRefresh, savedRefreshFailed).
+func codexWindowsRenewing(ctx context.Context, tok, accountID string, renew codexRenew) (plan string, out []QuotaWindow, resets *ResetCredits, credits string, held bool, err error) {
+ plan, out, resets, credits, held, err = codexWindows(ctx, tok, accountID)
+ if renew == nil || !codexExpired(err) {
+ return
+ }
+ fresh, id, rerr := renew(ctx, tok)
+ if rerr != nil {
+ return plan, out, resets, credits, held, rerr
+ }
+ if id != "" {
+ accountID = id
+ }
+ plan, out, resets, credits, held, err = codexWindows(ctx, fresh, accountID)
+ if codexExpired(err) {
+ err = errCodexStillExpired
+ }
+ return
+}
+
+// NoteExpiredSignIn renews the ChatGPT sign-in of a, whose request req the
+// backend answered 401 token expired while the token had time left by
+// its exp, so the next request goes with a new one. The request itself
+// isn't sent again here; the routing loop passes over it as an auth
+// failure. A refresh refused marks a saved account lapsed
+// (savedRefreshFailed).
+func NoteExpiredSignIn(ctx context.Context, a *Account, req *http.Request) {
+ if a == nil || a.renew == nil || a.plugin != nil || req == nil {
+ return
+ }
+ stale, ok := strings.CutPrefix(req.Header.Get("Authorization"), "Bearer ")
+ if !ok || stale == "" {
+ return
+ }
+ rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
+ defer cancel()
+ if _, _, err := a.renew(rctx, stale); err != nil {
+ log.Printf("codex: %s's token was called expired and couldn't be renewed: %v", a.User, err)
+ }
+}
diff --git a/internal/provider/codex_expired_test.go b/internal/provider/codex_expired_test.go
new file mode 100644
index 000000000..0f651b813
--- /dev/null
+++ b/internal/provider/codex_expired_test.go
@@ -0,0 +1,236 @@
+package provider
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// expiredBody is the backend's 401 for an access token it calls expired
+// while the token's own exp is an hour ahead (willz on Discord, #2973).
+const expiredBody = `{"error":{"message":"Provided authentication token is expired. Please try refreshing it.","type":null,"code":"token_expired","param":null},"status":401}`
+
+// codexExpiredFakes signs in me@ (saved) and work@ (Codex's own), both
+// with an hour left, and points usage and the token refresh at fakes.
+// usage answers each token as refused says; refresh answers each
+// refresh token with access token "fresh-<refresh token>", or as
+// refuseRefresh says. It returns the refresh tokens sent and the usage
+// reads made, by account and token.
+func codexExpiredFakes(t *testing.T, refused func(tok string) (int, string), refuseRefresh bool) (home string, refreshes func() []string, reads func() map[string]int) {
+ t.Helper()
+ home = signIn(t)
+ rememberLogins(true)
+ codexSignIn(t, home, "[email protected]", "r-work")
+ rememberLogins(true)
+ loginUsageCache.Lock()
+ loginUsageCache.m = nil
+ loginUsageCache.Unlock()
+
+ var mu sync.Mutex
+ var sent []string
+ seen := map[string]int{}
+ usage := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/backend-api/wham/usage" {
+ w.WriteHeader(404)
+ return
+ }
+ tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ mu.Lock()
+ seen[r.Header.Get("chatgpt-account-id")+" "+tok]++
+ mu.Unlock()
+ if code, body := refused(tok); code != 0 {
+ w.WriteHeader(code)
+ w.Write([]byte(body))
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"plan_type": "team", "rate_limit": map[string]any{
+ "primary_window": map[string]any{"used_percent": 12, "limit_window_seconds": 18000}}})
+ }))
+ t.Cleanup(usage.Close)
+ refresh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]string
+ json.NewDecoder(r.Body).Decode(&body)
+ mu.Lock()
+ sent = append(sent, body["refresh_token"])
+ mu.Unlock()
+ if refuseRefresh {
+ w.WriteHeader(400)
+ w.Write([]byte(`{"error":"invalid_grant"}`))
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"access_token": "fresh-" + body["refresh_token"], "refresh_token": body["refresh_token"] + "-2"})
+ }))
+ t.Cleanup(refresh.Close)
+ oldBase, oldURL := CodexBase, codexTokenURL
+ CodexBase, codexTokenURL = usage.URL+"/backend-api/codex", refresh.URL
+ t.Cleanup(func() { CodexBase, codexTokenURL = oldBase, oldURL })
+ refreshes = func() []string {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]string(nil), sent...)
+ }
+ reads = func() map[string]int {
+ mu.Lock()
+ defer mu.Unlock()
+ out := map[string]int{}
+ for k, v := range seen {
+ out[k] = v
+ }
+ return out
+ }
+ return home, refreshes, reads
+}
+
+// staleExpired answers every token magpie didn't refresh as expired.
+func staleExpired(tok string) (int, string) {
+ if strings.HasPrefix(tok, "fresh-") {
+ return 0, ""
+ }
+ return http.StatusUnauthorized, expiredBody
+}
+
+func TestCodexUsageRenewsTokenCalledExpired(t *testing.T) {
+ home, refreshes, reads := codexExpiredFakes(t, staleExpired, false)
+
+ u := LoginUsage(context.Background(), "codex")
+ for _, user := range []string{"[email protected]", "[email protected]"} {
+ q := u[user]
+ if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Used != 12 {
+ t.Fatalf("%s: %+v", user, q)
+ }
+ }
+ got := refreshes()
+ if len(got) != 2 || !(got[0] == "r" && got[1] == "r-work" || got[0] == "r-work" && got[1] == "r") {
+ t.Fatalf("refreshed with %q, want r and r-work once each", got)
+ }
+ if n := reads(); n["acct-1 fresh-r"] != 1 || n["[email protected] fresh-r-work"] != 1 {
+ t.Fatalf("reads %v", n)
+ }
+ // each renewed where it is kept: the saved one in logins.json, Codex's
+ // own in its auth.json, every other field as it was
+ var live codexAuth
+ readJSON(filepath.Join(home, ".codex", "auth.json"), &live)
+ if live.Tokens.AccessToken != "fresh-r-work" || live.Tokens.RefreshToken != "r-work-2" || live.Tokens.AccountID != "[email protected]" {
+ t.Fatalf("Codex's own sign-in: %+v", live.Tokens)
+ }
+ for _, l := range readLogins() {
+ if l.User == "[email protected]" && !strings.Contains(string(l.Auth), `"fresh-r"`) {
+ t.Fatalf("the saved account's refresh wasn't kept: %s", l.Auth)
+ }
+ }
+
+ // read again: the new tokens go out, with no refresh
+ loginUsageCache.Lock()
+ loginUsageCache.m = nil
+ loginUsageCache.Unlock()
+ u = LoginUsage(context.Background(), "codex")
+ if u["[email protected]"].Error != "" || u["[email protected]"].Error != "" || len(refreshes()) != 2 {
+ t.Fatalf("again: %+v, refreshes %q", u, refreshes())
+ }
+}
+
+// A refresh refused says to sign in again, once; a token still called
+// expired after its refresh is read no third time.
+func TestCodexUsageExpiredOnce(t *testing.T) {
+ t.Run("refresh refused", func(t *testing.T) {
+ _, refreshes, reads := codexExpiredFakes(t, staleExpired, true)
+ u := LoginUsage(context.Background(), "codex")
+ if e := u["[email protected]"].Error; !strings.Contains(e, "add the account again") {
+ t.Fatalf("saved account: %q", e)
+ }
+ if e := u["[email protected]"].Error; !strings.Contains(e, "codex login") {
+ t.Fatalf("Codex's own account: %q", e)
+ }
+ if n := len(refreshes()); n != 2 {
+ t.Fatalf("%d refreshes, want one each", n)
+ }
+ for k, n := range reads() {
+ if n != 1 {
+ t.Fatalf("%s read %d times", k, n)
+ }
+ }
+ })
+ t.Run("still expired", func(t *testing.T) {
+ always := func(string) (int, string) { return http.StatusUnauthorized, expiredBody }
+ _, refreshes, reads := codexExpiredFakes(t, always, false)
+ u := LoginUsage(context.Background(), "codex")
+ for _, user := range []string{"[email protected]", "[email protected]"} {
+ if e := u[user].Error; e != errCodexStillExpired.Error() {
+ t.Fatalf("%s: %q", user, e)
+ }
+ }
+ if n := len(refreshes()); n != 2 {
+ t.Fatalf("%d refreshes, want one each", n)
+ }
+ if n := reads(); n["acct-1 fresh-r"] != 1 || n["[email protected] fresh-r-work"] != 1 {
+ t.Fatalf("reads %v", n)
+ }
+ })
+}
+
+// Any other 401 isn't the token's age: nothing is refreshed for it.
+func TestCodexUsageOther401NotRenewed(t *testing.T) {
+ other := func(string) (int, string) {
+ return http.StatusUnauthorized, `{"error":{"message":"Unauthorized","code":"unauthorized"}}`
+ }
+ _, refreshes, _ := codexExpiredFakes(t, other, false)
+ u := LoginUsage(context.Background(), "codex")
+ if u["[email protected]"].Error != "Unauthorized" || len(refreshes()) != 0 {
+ t.Fatalf("%+v, refreshes %q", u, refreshes())
+ }
+}
+
+func TestSignInExpiredWords(t *testing.T) {
+ for body, want := range map[string]bool{
+ expiredBody: true,
+ `{"detail":"Your authentication token has expired. Please try signing in again."}`: true,
+ `{"error":{"code":"refresh_token_expired"}}`: false,
+ `{"error":{"code":"token_revoked"}}`: false,
+ `Unauthorized`: false,
+ } {
+ if got := SignInExpired(http.StatusUnauthorized, []byte(body)); got != want {
+ t.Errorf("%s: %v", body, got)
+ }
+ }
+ if SignInExpired(http.StatusForbidden, []byte(expiredBody)) {
+ t.Error("a 403")
+ }
+}
+
+// The gateway's 401 token expired renews the account the request went
+// with: the saved one in logins.json, and only while the token sent is
+// the one still saved.
+func TestNoteExpiredSignIn(t *testing.T) {
+ _, refreshes, _ := codexExpiredFakes(t, staleExpired, false)
+ if err := SetLoginOn("codex", "[email protected]", true); err != nil {
+ t.Fatal(err)
+ }
+ p, err := Find("codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ also := p.AlsoOn()
+ if len(also) != 1 || also[0].Account.User != "[email protected]" {
+ t.Fatalf("also on: %+v", also)
+ }
+ a := also[0].Account
+ req, _ := http.NewRequest("POST", "http://x", nil)
+ if err := a.sign(context.Background(), req, nil); err != nil {
+ t.Fatal(err)
+ }
+ stale := req.Header.Get("Authorization")
+ NoteExpiredSignIn(context.Background(), a, req)
+ NoteExpiredSignIn(context.Background(), a, req) // a second reply for the same token
+ if got := refreshes(); len(got) != 1 || got[0] != "r" {
+ t.Fatalf("refreshed with %q", got)
+ }
+ req, _ = http.NewRequest("POST", "http://x", nil)
+ if err := a.sign(context.Background(), req, nil); err != nil || req.Header.Get("Authorization") != "Bearer fresh-r" || stale == "Bearer fresh-r" {
+ t.Fatalf("next request signed %q (was %q), %v", req.Header.Get("Authorization"), stale, err)
+ }
+}
diff --git a/internal/provider/codex_expiring.go b/internal/provider/codex_expiring.go
index 5e7f24be5..2ab6f84f1 100644
--- a/internal/provider/codex_expiring.go
+++ b/internal/provider/codex_expiring.go
@@ -193,13 +193,10 @@ func SpendExpiringCodexResets(ctx context.Context) {
}
var who string
out, err := expiring.check(user, time.Now(), func() ([]QuotaWindow, *ResetCredits, error) {
- var tok, accountID string
+ var windows []QuotaWindow
+ var resets *ResetCredits
var err error
- who, tok, accountID, err = codexUserToken(ViaLogin(ctx, "codex", user), user)
- if err != nil {
- return nil, nil, err
- }
- _, windows, resets, _, _, err := codexWindows(ViaLogin(ctx, "codex", who), tok, accountID)
+ who, windows, resets, err = codexUserWindows(ctx, user)
return windows, resets, err
}, func() (ResetOutcome, error) {
// one spend at a time, with the week's used-up one too
@@ -225,11 +222,7 @@ func SpendExpiringCodexResets(ctx context.Context) {
// stillExpiring reads who's windows and resets again and says whether
// check would still spend one now; a var so tests can stand in for it.
var stillExpiring = func(ctx context.Context, who string) bool {
- who, tok, accountID, err := codexUserToken(ViaLogin(ctx, "codex", who), who)
- if err != nil {
- return false
- }
- _, windows, resets, _, _, err := codexWindows(ViaLogin(ctx, "codex", who), tok, accountID)
+ _, windows, resets, err := codexUserWindows(ctx, who)
return err == nil && spendExpiringNow(windows, resets, time.Now())
}
diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go
index 660d2f972..a6095ea44 100644
--- a/internal/provider/codex_resets.go
+++ b/internal/provider/codex_resets.go
@@ -246,19 +246,43 @@ func useCodexReset(ctx context.Context, user, why string) (ResetOutcome, error)
// codexUserToken signs in as the Codex account user: the one Codex itself
// is signed in to, or one magpie keeps — and says which it was.
func codexUserToken(ctx context.Context, user string) (who, tok, accountID string, err error) {
+ who, tok, accountID, _, err = codexUserSign(ctx, user)
+ return who, tok, accountID, err
+}
+
+// codexUserSign is codexUserToken, with how to renew that sign-in.
+func codexUserSign(ctx context.Context, user string) (who, tok, accountID string, renew codexRenew, err error) {
// the one signed in now, read from Codex's own file: the list of those
// kept may not have caught up with it yet
if live, ok := liveLogin("codex"); user == "" || ok && strings.EqualFold(live.User, user) {
tok, accountID, err = codexToken(ctx, codexHome())
- return live.User, tok, accountID, err
+ renew = func(ctx context.Context, stale string) (string, string, error) {
+ return codexTokenRenewing(ctx, codexHome(), stale)
+ }
+ return live.User, tok, accountID, renew, err
}
for _, l := range Logins("codex") {
if strings.EqualFold(l.User, user) {
- tok, accountID, err = savedLoginToken(ctx, "codex", l.User)
- return l.User, tok, accountID, err
+ who := l.User
+ tok, accountID, err = savedLoginToken(ctx, "codex", who)
+ renew = func(ctx context.Context, stale string) (string, string, error) {
+ return renewSavedLoginFrom(ctx, "codex", who, stale)
+ }
+ return who, tok, accountID, renew, err
}
}
- return "", "", "", fmt.Errorf("no Codex account %q", user)
+ return "", "", "", nil, fmt.Errorf("no Codex account %q", user)
+}
+
+// codexUserWindows reads the windows and resets of the Codex account user
+// (codexUserSign), renewing a sign-in the backend calls expired once.
+func codexUserWindows(ctx context.Context, user string) (who string, windows []QuotaWindow, resets *ResetCredits, err error) {
+ who, tok, accountID, renew, err := codexUserSign(ViaLogin(ctx, "codex", user), user)
+ if err != nil {
+ return who, nil, nil, err
+ }
+ _, windows, resets, _, _, err = codexWindowsRenewing(ViaLogin(ctx, "codex", who), tok, accountID, renew)
+ return who, windows, resets, err
}
// consumeCodexReset spends the reset credit; id makes a retry of the same
diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go
index 2bd9690a8..085f0c54c 100644
--- a/internal/provider/login_usage.go
+++ b/internal/provider/login_usage.go
@@ -337,12 +337,20 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
}
var tok, accountID string
var err error
+ var renew codexRenew
switch {
case l.Agent == "claude": // Claude Code reads its own (claudeWindows)
case l.Active:
tok, accountID, err = codexToken(ctx, codexHome())
+ renew = func(ctx context.Context, stale string) (string, string, error) {
+ return codexTokenRenewing(ctx, codexHome(), stale)
+ }
default:
tok, accountID, err = savedLoginToken(ctx, l.Agent, l.User)
+ agent, user := l.Agent, l.User
+ renew = func(ctx context.Context, stale string) (string, string, error) {
+ return renewSavedLoginFrom(ctx, agent, user, stale)
+ }
}
if err == nil {
if l.Agent == "claude" {
@@ -351,7 +359,7 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
}
} else {
var plan string
- if plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindows(ctx, tok, accountID); plan != "" {
+ if plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindowsRenewing(ctx, tok, accountID, renew); plan != "" {
q.Plan = plan
}
q.Until = codexUntil(codexLoginAuth(l), time.Now())
diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go
index 5c5092bf7..b52ed5476 100644
--- a/internal/provider/logins_on.go
+++ b/internal/provider/logins_on.go
@@ -163,6 +163,9 @@ func (p Provider) alsoOn() []Provider {
}
if agent == "codex" {
a.sign = codexSign(func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, agent, user) })
+ a.renew = func(ctx context.Context, stale string) (string, string, error) {
+ return renewSavedLoginFrom(ctx, agent, user, stale)
+ }
}
q := p
q.Account = &a
@@ -203,6 +206,18 @@ func savedLoginToken(ctx context.Context, agent, user string) (tok, accountID st
// refuses is kept on the account as lapsed, until one goes through or it is
// signed in again.
func renewSavedLogin(ctx context.Context, agent, user string, force bool) (tok, accountID string, err error) {
+ return renewSaved(ctx, agent, user, force, "")
+}
+
+// renewSavedLoginFrom refreshes the saved sign-in whose access token stale
+// the backend just called expired while it had time left (#2973), unless
+// it was renewed since: the token saved by now is returned then, its
+// refresh token being the one spent already.
+func renewSavedLoginFrom(ctx context.Context, agent, user, stale string) (tok, accountID string, err error) {
+ return renewSaved(ctx, agent, user, false, stale)
+}
+
+func renewSaved(ctx context.Context, agent, user string, force bool, stale string) (tok, accountID string, err error) {
ctx = ViaLogin(ctx, agent, user) // refreshed through the account's own proxy
savedTokenMu.Lock()
defer savedTokenMu.Unlock()
@@ -230,7 +245,11 @@ func renewSavedLogin(ctx context.Context, agent, user string, force bool) (tok,
if accountID == "" {
accountID = claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_account_id")
}
- if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); !force && (exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute) {
+ if stale != "" {
+ if a.Tokens.AccessToken != stale {
+ return a.Tokens.AccessToken, accountID, nil
+ }
+ } else if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); !force && (exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute) {
return a.Tokens.AccessToken, accountID, nil
}
if tok, err = codexRefresh(ctx, raw); err != nil {
diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go
index af6bbfd0e..987756110 100644
--- a/internal/provider/subscription_usage.go
+++ b/internal/provider/subscription_usage.go
@@ -555,7 +555,7 @@ func accountJSON(ctx context.Context, url, token string, headers map[string]stri
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if res.StatusCode < 200 || res.StatusCode >= 300 {
- e := &accountStatusError{status: res.StatusCode}
+ e := &accountStatusError{status: res.StatusCode, body: b[:min(len(b), 4<<10)]}
if secs, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && secs > 0 {
e.retryAfter = time.Duration(secs) * time.Second
}
@@ -567,6 +567,7 @@ func accountJSON(ctx context.Context, url, token string, headers map[string]stri
type accountStatusError struct {
status int
retryAfter time.Duration // what the vendor asked to wait, when it said
+ body []byte // the start of what it answered (accountJSON)
}
func (e *accountStatusError) Error() string { return http.StatusText(e.status) }
@@ -897,7 +898,10 @@ func codexSubscriptionUsage(ctx context.Context, dir string) SubscriptionQuota {
q.Error = err.Error()
return q
}
- q.Plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindows(ctx, token, accountID)
+ renew := func(ctx context.Context, stale string) (string, string, error) {
+ return codexTokenRenewing(ctx, dir, stale)
+ }
+ q.Plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindowsRenewing(ctx, token, accountID, renew)
if b, _, rerr := readCodexLogin(dir, false); rerr == nil {
q.Until = codexUntil(b, time.Now())
}