provider: ChatGPT account calls go with Codex's headers, and saved accounts are listed once a day
Two follow-ups of 6e55914b6's audit of what magpie sends OpenAI for
idle saved Codex accounts (owl, Discord #general: three ChatGPT accounts
deactivated). Product call made by the session the owner delegated
product calls to; mimicking the official client is allowed for every
vendor but Claude Code. Identity, base_instructions and prompts are not
touched.
- Headers. GET /backend-api/wham/usage, /wham/rate-limit-reset-credits,
POST .../consume and POST auth.openai.com/oauth/token (live and saved
sign-ins, and the sign-in's code exchange) went with Go's
"Go-http-client/1.1" and no originator. They now carry Codex's
originator and User-Agent through codexClientHeaders, the part of
codexSign that /codex/models and /responses already used. No version
header on them: codex-rs sends it with model requests only
(login/src/auth/default_client.rs default_headers is originator +
User-Agent; backend-client/src/client.rs adds auth headers).
- Refresh body. codex-rs (main f32b6cfd and rust-v0.165.0,
login/src/oauth/client.rs refresh, auth/manager.rs
request_chatgpt_token_refresh) sends JSON client_id, grant_type,
refresh_token and refresh_reason, and no scope. magpie sent
scope "openid profile email" and no reason. It now sends codex-rs's
fields: proactive_expiry near expiry, unauthorized_recovery after a
401 (stale token), scheduled from the 8-day keep-alive, forced for an
import or a revoked-sign-in check. The code exchange's form already
matched exchange_code; only its headers changed.
- Model lists. The active Codex account's /codex/models fetch (hourly
KeepAccountsListed, FetchNew, Refresh) also fetched every switched-on
saved account's list each time. codexFetchSaved now asks one with no
list at once, and the others once a day, one per call, oldest asked
first; a failed ask is remembered so a deactivated account doesn't go
first every hour. The active account's list is unchanged.
Docs: providers-accounts.md says both.
Tests (codex_quiet_test.go), each red on the old behaviour (broken by
hand: wham/refresh/exchange headers removed, scope back, the age check
and the one-a-look cap removed, the keep-alive's reason dropped, and
separately the failed-ask memory skipped):
- TestCodexAccountCallsGoAsCodex counts the requests to a fake (usage 1,
credits 1, consume 1, token 2) and checks User-Agent/originator on
each and the refresh body's keys. Old: Go-http-client/1.1, "" and
scope in the body.
- TestCodexRefreshSaysWhy: scheduled, forced, unauthorized_recovery.
Old: no reason.
- TestSavedCodexListsOnceADay: 2 asks on the first look, 0 an hour on,
1 then 1 a day on, 0 again, and 0 within the day while failing. Old:
2 on every look; without the memory, a failing one asked again.
Run (mote-run, at origin/main 9b4d0bda8 plus this change, the tree
pushed unless the rebase below names a newer base):
- gofmt -l internal/provider: clean
- go vet ./internal/{provider,agent,cli,gateway} on darwin, GOOS=linux
-tags nogui and GOOS=windows: ok
- go test -count=1 -timeout 45m ./internal/provider ./internal/agent
./internal/cli ./internal/gateway: all ok (118s, 199s, 44s, 562s)
Not tried: a real ChatGPT account (none touched, per the session's
rules), so OpenAI's answer to the new headers and the scope-less
refresh is known only from codex-rs doing the same. The Sign in with
ChatGPT API path (auth.openai.com/api/accounts/oauth/token, chatgpt_api.go)
is another client and is left as it was. Refresh in the GUI also lists
saved accounts by the once-a-day rule now.
This commit is contained in:
@@ -143,7 +143,7 @@ no decision model was discovered (`Test` in
|
||||
|
||||
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. So does a public plugin, one whose every way in is keyless (`publicPlugin` in [`plugin_accounts.go`](../../internal/provider/plugin_accounts.go), OpenCode Zen Free): it holds no account of the user's, so it stays listed and served, and its sign-in goes through (lileo0668: it signed in, then was listed nowhere). Any other plugin's key is refused in `PluginAPIKey`, as its browser sign-in is, rather than saved and listed nowhere. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
|
||||
|
||||
A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it.
|
||||
A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it. The saved ChatGPT accounts behind the one Codex is signed in to are listed with that fetch (`codexFetchSaved`), but not each time: one with no list yet is asked at once, the others once a day (`codexSavedListAge`) and one a look (`codexSavedAtOnce`), the one asked longest ago first, and one that failed waits its day too (`codexSavedAsked`). Asking every switched-on saved account each hour was a burst of `/codex/models` calls from one address for accounts no Codex used (`TestSavedCodexListsOnceADay`). Every call magpie makes about a ChatGPT account, not only `/codex/models` and `/responses` (`codexSign`), carries Codex's `originator` and User-Agent (`codexClientHeaders`, codex-rs `default_headers`): `/wham/usage`, the reset credits and their use (`codexAccountHeaders`), and the token endpoint's refresh and sign-in exchange. The refresh's body is codex-rs's: `client_id`, `grant_type`, `refresh_token` and a `refresh_reason` (`proactive_expiry`, `scheduled` from the keep-alive, `unauthorized_recovery` after a 401, `forced`), with no `scope` (`TestCodexAccountCallsGoAsCodex`, `TestCodexRefreshSaysWhy`).
|
||||
|
||||
## Runtime path
|
||||
|
||||
|
||||
@@ -1127,7 +1127,11 @@ func codexTokenRenewing(ctx context.Context, dir, stale string) (tok, accountID
|
||||
return "", "", errors.New("Codex is signed out; run codex login")
|
||||
}
|
||||
accountID = codexAccountID(a)
|
||||
tok, err = codexRefresh(ctx, raw)
|
||||
reason := codexRefreshExpiry
|
||||
if stale != "" {
|
||||
reason = codexRefreshRecovery
|
||||
}
|
||||
tok, err = codexRefresh(ctx, raw, reason)
|
||||
if err != nil {
|
||||
// OpenAI refused this sign-in for good: Codex is signed out to
|
||||
// magpie's wiring until it is signed in again (#4308)
|
||||
@@ -1164,9 +1168,39 @@ func codexAccountID(a codexAuth) string {
|
||||
return claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_account_id")
|
||||
}
|
||||
|
||||
// Why a ChatGPT sign-in is refreshed, in the words codex-rs sends with
|
||||
// its own refresh (refresh_reason, login/src/oauth/client.rs).
|
||||
const (
|
||||
codexRefreshExpiry = "proactive_expiry" // its access token is about to run out
|
||||
codexRefreshScheduled = "scheduled" // not refreshed for keepAliveEvery
|
||||
codexRefreshRecovery = "unauthorized_recovery" // the backend called its token expired
|
||||
codexRefreshForced = "forced" // asked for: an import, a check
|
||||
)
|
||||
|
||||
type refreshReasonKey struct{}
|
||||
|
||||
// refreshingFor has a forced refresh made under ctx say why it is made,
|
||||
// when it is more than "forced" (the keep-alive's "scheduled").
|
||||
func refreshingFor(ctx context.Context, reason string) context.Context {
|
||||
return context.WithValue(ctx, refreshReasonKey{}, reason)
|
||||
}
|
||||
|
||||
// forcedReason is why ctx forces a refresh: what refreshingFor said, else
|
||||
// "forced".
|
||||
func forcedReason(ctx context.Context) string {
|
||||
if r, _ := ctx.Value(refreshReasonKey{}).(string); r != "" {
|
||||
return r
|
||||
}
|
||||
return codexRefreshForced
|
||||
}
|
||||
|
||||
// codexRefresh renews the tokens of an auth.json-shaped sign-in in place,
|
||||
// every other field left as it was, and returns the new access token.
|
||||
func codexRefresh(ctx context.Context, raw map[string]any) (string, error) {
|
||||
// It is asked as codex-rs asks it (request_chatgpt_token_refresh): a JSON
|
||||
// body of client_id, grant_type, refresh_token and refresh_reason, with
|
||||
// no scope (a refresh keeps the scopes granted), and Codex's originator
|
||||
// and User-Agent.
|
||||
func codexRefresh(ctx context.Context, raw map[string]any, reason string) (string, error) {
|
||||
toks, _ := raw["tokens"].(map[string]any)
|
||||
if toks == nil {
|
||||
toks = map[string]any{}
|
||||
@@ -1185,12 +1219,13 @@ func codexRefresh(ctx context.Context, raw map[string]any) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
body, _ := json.Marshal(map[string]string{"client_id": codexClientID, "grant_type": "refresh_token",
|
||||
"refresh_token": refresh, "scope": "openid profile email"})
|
||||
"refresh_token": refresh, "refresh_reason": reason})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, codexTokenURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
codexClientHeaders(req.Header, codexVersion())
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", errors.New("Codex token refresh: " + err.Error())
|
||||
|
||||
@@ -103,6 +103,10 @@ func isolate(t testing.TB) {
|
||||
// a minute, and CachedCards hands them on whatever their age
|
||||
forgetPlanQuotas()
|
||||
ForgetBalances()
|
||||
// nor when another test asked a saved account's list
|
||||
codexSavedAsked.Lock()
|
||||
codexSavedAsked.m = map[string]time.Time{}
|
||||
codexSavedAsked.Unlock()
|
||||
t.Cleanup(func() {
|
||||
claudeKeychain, claudeBase, claudeExecutable = oldKeychain, oldBase, oldExe
|
||||
DevinExecutable = oldDevin
|
||||
|
||||
@@ -422,16 +422,70 @@ func levelRank(e string) int {
|
||||
return len(Levels)
|
||||
}
|
||||
|
||||
// codexFetchSaved asks for the models of each saved ChatGPT account that
|
||||
// stands behind the one Codex is signed in to, with that account's own
|
||||
// sign-in, so the gateway doesn't send one a model its plan lacks. One that
|
||||
// can't be asked now keeps what it listed last.
|
||||
// codexSavedListAge is how old a saved account's list is before it is
|
||||
// asked for again, and codexSavedAtOnce how many of those one fetch of the
|
||||
// active account's list asks. The active account's list is asked every
|
||||
// accountListAge (KeepAccountsListed) as Codex asks its own; asking every
|
||||
// switched-on saved account's beside it each hour was a burst of N
|
||||
// /codex/models calls from one address for accounts no Codex was using
|
||||
// (the audit after owl's deactivated accounts, 10-30). A plan's models
|
||||
// change seldom: once a day, one account a look, so they drift apart.
|
||||
const (
|
||||
codexSavedListAge = 24 * time.Hour
|
||||
codexSavedAtOnce = 1
|
||||
)
|
||||
|
||||
// codexSavedAsked is when each saved account's list was last asked for,
|
||||
// fetched or not, so one that keeps failing (a deactivated account) waits
|
||||
// its day like the others instead of being first every look.
|
||||
var codexSavedAsked = struct {
|
||||
sync.Mutex
|
||||
m map[string]time.Time
|
||||
}{m: map[string]time.Time{}}
|
||||
|
||||
// codexSavedNow is codexFetchSaved's clock; a var so tests can move it.
|
||||
var codexSavedNow = time.Now
|
||||
|
||||
// codexFetchSaved asks for the models of the saved ChatGPT accounts that
|
||||
// stand behind the one Codex is signed in to, with each account's own
|
||||
// sign-in, so the gateway doesn't send one a model its plan lacks. An
|
||||
// account with no list yet is asked at once; of the rest, the one asked
|
||||
// longest ago, once codexSavedListAge has passed, and no more than
|
||||
// codexSavedAtOnce of them. One that can't be asked now keeps what it
|
||||
// listed last.
|
||||
func codexFetchSaved(ctx context.Context) {
|
||||
for _, l := range Logins("codex") {
|
||||
now := codexSavedNow()
|
||||
type due struct {
|
||||
user string
|
||||
at time.Time
|
||||
}
|
||||
var fresh, stale []due
|
||||
ls := Logins("codex")
|
||||
codexSavedAsked.Lock()
|
||||
for _, l := range ls {
|
||||
if l.Active || !l.On {
|
||||
continue
|
||||
}
|
||||
user := l.User
|
||||
_, at, ok := catalog.Live(accountModels("codex", l.User))
|
||||
if !ok {
|
||||
fresh = append(fresh, due{l.User, at})
|
||||
continue
|
||||
}
|
||||
if a := codexSavedAsked.m[strings.ToLower(l.User)]; a.After(at) {
|
||||
at = a
|
||||
}
|
||||
if now.Sub(at) >= codexSavedListAge {
|
||||
stale = append(stale, due{l.User, at})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(stale, func(i, j int) bool { return stale[i].at.Before(stale[j].at) })
|
||||
ask := append(fresh, stale[:min(len(stale), codexSavedAtOnce)]...)
|
||||
for _, d := range ask {
|
||||
codexSavedAsked.m[strings.ToLower(d.user)] = now
|
||||
}
|
||||
codexSavedAsked.Unlock()
|
||||
for _, d := range ask {
|
||||
user := d.user
|
||||
sign := codexSign(func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, "codex", user) })
|
||||
// through the account's own proxy, if it has one
|
||||
if ms, err := codexModels(ViaLogin(ctx, "codex", user), sign); err == nil {
|
||||
|
||||
@@ -3,10 +3,13 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -128,3 +131,234 @@ func TestKeepAliveRenewsOneALook(t *testing.T) {
|
||||
t.Fatalf("one look renewed %d of %+v, refreshed %v", renewed, rs, got)
|
||||
}
|
||||
}
|
||||
|
||||
// Every call magpie makes about a ChatGPT account goes as Codex makes it:
|
||||
// its originator and User-Agent on /wham/usage, the reset credits and the
|
||||
// token endpoint, as on /codex/models and /responses already. They went
|
||||
// with Go's "Go-http-client/1.1" and no originator, unlike any request the
|
||||
// official client sends. The refresh's body is codex-rs's too: a
|
||||
// refresh_reason, and no scope.
|
||||
func TestCodexAccountCallsGoAsCodex(t *testing.T) {
|
||||
signIn(t)
|
||||
type call struct {
|
||||
ua, originator, ctype string
|
||||
body []byte
|
||||
}
|
||||
var mu sync.Mutex
|
||||
calls := map[string][]call{}
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
calls[r.Method+" "+r.URL.Path] = append(calls[r.Method+" "+r.URL.Path], call{r.UserAgent(), r.Header.Get("originator"), r.Header.Get("Content-Type"), b})
|
||||
mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/backend-api/wham/usage":
|
||||
json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus",
|
||||
"rate_limit": map[string]any{"primary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 18000}},
|
||||
"rate_limit_reset_credits": map[string]any{"available_count": 1}})
|
||||
case "/backend-api/wham/rate-limit-reset-credits":
|
||||
json.NewEncoder(w).Encode(map[string]any{"available_count": 1, "credits": []any{map[string]any{"id": "c1", "reset_type": "all", "status": "available"}}})
|
||||
case "/backend-api/wham/rate-limit-reset-credits/consume":
|
||||
json.NewEncoder(w).Encode(map[string]any{"code": "ok", "windows_reset": 1})
|
||||
case "/oauth/token":
|
||||
json.NewEncoder(w).Encode(map[string]any{"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}),
|
||||
"refresh_token": "r-2", "id_token": fakeJWT(map[string]any{"email": "new@example.com"})})
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer fake.Close()
|
||||
codexListedAt(t, fake.URL) // CodexBase, and the machine's own Codex CLI out of the version
|
||||
old := codexTokenURL
|
||||
codexTokenURL = fake.URL + "/oauth/token"
|
||||
t.Cleanup(func() { codexTokenURL = old })
|
||||
|
||||
ctx := context.Background()
|
||||
if _, _, resets, _, _, err := codexWindows(ctx, "tok", "acct-1"); err != nil || resets == nil {
|
||||
t.Fatalf("usage: resets %+v, %v", resets, err)
|
||||
}
|
||||
if _, err := consumeCodexReset(ctx, fake.URL+"/backend-api", "tok", "acct-1", "c1", newRedeemID()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := codexRefresh(ctx, map[string]any{"tokens": map[string]any{"refresh_token": "r-1"}}, codexRefreshScheduled); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
codexExchange(ctx, "code", "verifier", "http://localhost:1455/auth/callback") // the request is what is checked
|
||||
|
||||
want := map[string]int{"GET /backend-api/wham/usage": 1, "GET /backend-api/wham/rate-limit-reset-credits": 1,
|
||||
"POST /backend-api/wham/rate-limit-reset-credits/consume": 1, "POST /oauth/token": 2}
|
||||
ua := codexUserAgent(codexVersion())
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for k, n := range want {
|
||||
if len(calls[k]) != n {
|
||||
t.Errorf("%s asked %d times, want %d (%v)", k, len(calls[k]), n, calls)
|
||||
}
|
||||
for _, c := range calls[k] {
|
||||
if c.ua != ua || c.originator != "codex_cli_rs" {
|
||||
t.Errorf("%s sent User-Agent %q, originator %q; Codex sends %q, codex_cli_rs", k, c.ua, c.originator, ua)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(calls) != len(want) {
|
||||
t.Errorf("asked %v", calls)
|
||||
}
|
||||
if tok := calls["POST /oauth/token"]; len(tok) == 2 {
|
||||
var refresh map[string]any
|
||||
if tok[0].ctype != "application/json" || json.Unmarshal(tok[0].body, &refresh) != nil {
|
||||
t.Fatalf("refresh sent as %q: %s", tok[0].ctype, tok[0].body)
|
||||
}
|
||||
keys := []string{}
|
||||
for k := range refresh {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
if strings.Join(keys, ",") != "client_id,grant_type,refresh_reason,refresh_token" ||
|
||||
refresh["refresh_reason"] != "scheduled" || refresh["grant_type"] != "refresh_token" || refresh["client_id"] != codexClientID {
|
||||
t.Errorf("refresh body %s; codex-rs sends client_id, grant_type, refresh_token and refresh_reason", tok[0].body)
|
||||
}
|
||||
if tok[1].ctype != "application/x-www-form-urlencoded" || !strings.Contains(string(tok[1].body), "grant_type=authorization_code") {
|
||||
t.Errorf("sign-in exchange sent as %q: %s", tok[1].ctype, tok[1].body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh says why it is made, in codex-rs's words: the keep-alive's is
|
||||
// "scheduled", one after the backend called the token expired
|
||||
// "unauthorized_recovery", one asked for otherwise "forced", and one for
|
||||
// a token about to run out "proactive_expiry".
|
||||
func TestCodexRefreshSaysWhy(t *testing.T) {
|
||||
home := signIn(t)
|
||||
rememberLogins(true) // me@ saved
|
||||
codexSignIn(t, home, "work@example.com", "r-work")
|
||||
rememberLogins(true) // Codex on work@
|
||||
var mu sync.Mutex
|
||||
var why []string
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
mu.Lock()
|
||||
why = append(why, body["refresh_reason"])
|
||||
mu.Unlock()
|
||||
json.NewEncoder(w).Encode(map[string]any{"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix()), "n": len(why)}),
|
||||
"refresh_token": body["refresh_token"] + "-2"})
|
||||
}))
|
||||
defer fake.Close()
|
||||
old := codexTokenURL
|
||||
codexTokenURL = fake.URL
|
||||
t.Cleanup(func() { codexTokenURL = old })
|
||||
|
||||
ctx := context.Background()
|
||||
// me@ was last seen nine days ago: the keep-alive renews it, as due
|
||||
loginsMu.Lock()
|
||||
ls := readLogins()
|
||||
for i := range ls {
|
||||
if ls[i].User == "me@example.com" {
|
||||
ls[i].Seen = time.Now().Add(-9 * 24 * time.Hour)
|
||||
}
|
||||
}
|
||||
err := writeLogins(ls)
|
||||
loginsMu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rs := renewLogins(ctx, keepAliveEvery, keepAliveAtOnce); len(rs) != 1 || !rs[0].Renewed {
|
||||
t.Fatalf("keep-alive: %+v", rs)
|
||||
}
|
||||
tok, _, err := renewSavedLogin(ctx, "codex", "me@example.com", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := renewSavedLoginFrom(ctx, "codex", "me@example.com", tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if strings.Join(why, ",") != "scheduled,forced,unauthorized_recovery" {
|
||||
t.Fatalf("refreshes said %v", why)
|
||||
}
|
||||
}
|
||||
|
||||
// A saved ChatGPT account's model list is asked for once a day, one
|
||||
// account a look; the hourly relist asked every switched-on saved
|
||||
// account's beside the active one's, a burst of /codex/models calls from
|
||||
// one address for accounts no Codex was using. An account with no list
|
||||
// yet is asked at once, and one that fails waits its day like the rest.
|
||||
func TestSavedCodexListsOnceADay(t *testing.T) {
|
||||
home := signIn(t) // me@example.com, acct-1
|
||||
rememberLogins(true)
|
||||
codexSignIn(t, home, "spare@example.com", "r-spare")
|
||||
rememberLogins(true)
|
||||
codexSignIn(t, home, "work@example.com", "r-work")
|
||||
rememberLogins(true) // Codex on work@
|
||||
for _, u := range []string{"me@example.com", "spare@example.com"} {
|
||||
if err := SetLoginOn("codex", u, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var mu sync.Mutex
|
||||
hits := map[string]int{}
|
||||
var down atomic.Bool
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/backend-api/codex/models" {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
hits[r.Header.Get("chatgpt-account-id")]++
|
||||
mu.Unlock()
|
||||
if down.Load() {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
w.Write(codexListOf("gpt-6.1-sol"))
|
||||
}))
|
||||
defer fake.Close()
|
||||
codexListedAt(t, fake.URL)
|
||||
now := time.Now()
|
||||
oldNow := codexSavedNow
|
||||
codexSavedNow = func() time.Time { return now }
|
||||
t.Cleanup(func() { codexSavedNow = oldNow })
|
||||
look := func(at time.Duration) map[string]int {
|
||||
t.Helper()
|
||||
now = time.Now().Add(at)
|
||||
mu.Lock()
|
||||
hits = map[string]int{}
|
||||
mu.Unlock()
|
||||
codexFetchSaved(context.Background())
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
got := map[string]int{}
|
||||
for k, v := range hits {
|
||||
got[k] = v
|
||||
}
|
||||
return got
|
||||
}
|
||||
// no list yet: both saved accounts are asked, never the active one here
|
||||
if got := look(0); len(got) != 2 || got["acct-1"] != 1 || got["acct-spare@example.com"] != 1 {
|
||||
t.Fatalf("first look: %v", got)
|
||||
}
|
||||
// within the day: none
|
||||
if got := look(time.Hour); len(got) != 0 {
|
||||
t.Fatalf("an hour on: %v", got)
|
||||
}
|
||||
if codexSavedListAge < 24*time.Hour || codexSavedAtOnce != 1 {
|
||||
t.Fatalf("saved lists asked every %v, %d a look", codexSavedListAge, codexSavedAtOnce)
|
||||
}
|
||||
// a day on: one a look, then the other, then none till the next day
|
||||
first := look(25 * time.Hour)
|
||||
second := look(26 * time.Hour)
|
||||
if len(first) != 1 || len(second) != 1 || first["acct-1"]+second["acct-1"] != 1 {
|
||||
t.Fatalf("a day on: %v, then %v", first, second)
|
||||
}
|
||||
if got := look(27 * time.Hour); len(got) != 0 {
|
||||
t.Fatalf("both asked today, asked again: %v", got)
|
||||
}
|
||||
// failing: still once a day each, not first in every look
|
||||
down.Store(true)
|
||||
look(50 * time.Hour)
|
||||
look(51 * time.Hour)
|
||||
if got := look(52 * time.Hour); len(got) != 0 {
|
||||
t.Fatalf("failing accounts asked again within the day: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,12 +39,11 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
|
||||
req.Header.Set("chatgpt-account-id", accountID)
|
||||
}
|
||||
req.Header.Set("OpenAI-Beta", "responses=experimental")
|
||||
req.Header.Set("originator", "codex_cli_rs")
|
||||
// the version and the User-Agent name one Codex, never older than
|
||||
// the client whose request this is (its version header, relayed)
|
||||
ver := newerVersion(codexVersion(), req.Header.Get("version"))
|
||||
req.Header.Set("version", ver)
|
||||
req.Header.Set("User-Agent", codexUserAgent(ver))
|
||||
codexClientHeaders(req.Header, ver)
|
||||
if body == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -54,6 +53,31 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
|
||||
}
|
||||
}
|
||||
|
||||
// codexClientHeaders are what every request Codex CLI makes carries,
|
||||
// whatever it is for: its originator and its User-Agent, naming Codex of
|
||||
// version ver (codex-rs login/src/auth/default_client.rs default_headers,
|
||||
// which its token refresh, its /wham reads and its model requests are all
|
||||
// sent with). The ChatGPT account's own calls that aren't a model's
|
||||
// (/wham/usage, the reset credits, the token refresh) went with Go's
|
||||
// User-Agent and no originator, unlike any request Codex makes.
|
||||
func codexClientHeaders(h http.Header, ver string) {
|
||||
h.Set("originator", "codex_cli_rs")
|
||||
h.Set("User-Agent", codexUserAgent(ver))
|
||||
}
|
||||
|
||||
// codexAccountHeaders are the headers of a call Codex makes about the
|
||||
// ChatGPT account (its /wham reads): the account it is about and
|
||||
// codexClientHeaders. Codex sends no version header with them.
|
||||
func codexAccountHeaders(accountID string) map[string]string {
|
||||
h := http.Header{}
|
||||
codexClientHeaders(h, codexVersion())
|
||||
m := map[string]string{"chatgpt-account-id": accountID}
|
||||
for k := range h {
|
||||
m[k] = h.Get(k)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// sessionHeaders names the conversation body belongs to (its
|
||||
// prompt_cache_key) in the headers Codex CLI 0.162 sends it in, session-id
|
||||
// and thread-id. The ChatGPT backend finds a conversation's cached prompt
|
||||
|
||||
@@ -159,7 +159,7 @@ func codexResets(ctx context.Context, base, token, accountID string, count int)
|
||||
ctx, cancel := context.WithTimeout(ctx, codexResetDetailsTimeout)
|
||||
defer cancel()
|
||||
var w codexResetCreditsWire
|
||||
if accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, map[string]string{"chatgpt-account-id": accountID}, &w) == nil {
|
||||
if accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, codexAccountHeaders(accountID), &w) == nil {
|
||||
out.Until = w.soonest()
|
||||
// listed only when they are the ones counted: a list that says
|
||||
// otherwise isn't put on the card as if it were
|
||||
@@ -218,7 +218,7 @@ func useCodexReset(ctx context.Context, user, why string) (ResetOutcome, error)
|
||||
// which of them to spend is named, as Codex itself does: left to the
|
||||
// vendor, it may be one that lasts longer
|
||||
var w codexResetCreditsWire
|
||||
if err := accountJSON(ctx, base+"/wham/rate-limit-reset-credits", tok, map[string]string{"chatgpt-account-id": accountID}, &w); err != nil {
|
||||
if err := accountJSON(ctx, base+"/wham/rate-limit-reset-credits", tok, codexAccountHeaders(accountID), &w); err != nil {
|
||||
return ResetOutcome{}, fmt.Errorf("couldn't read which reset runs out first, so none was used: %w", err)
|
||||
}
|
||||
credit, _ := w.first()
|
||||
@@ -297,8 +297,10 @@ func consumeCodexReset(ctx context.Context, base, token, accountID, credit, id s
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if accountID != "" {
|
||||
req.Header.Set("chatgpt-account-id", accountID)
|
||||
for k, v := range codexAccountHeaders(accountID) {
|
||||
if v != "" {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
|
||||
@@ -82,7 +82,11 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal
|
||||
continue
|
||||
}
|
||||
tried++
|
||||
if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
|
||||
why := ctx
|
||||
if every > 0 {
|
||||
why = refreshingFor(ctx, codexRefreshScheduled)
|
||||
}
|
||||
if _, _, err := renewSavedLogin(why, l.Agent, l.User, true); err != nil {
|
||||
r.Err = err.Error()
|
||||
var refused refreshRefused
|
||||
r.Lapsed = errors.As(err, &refused)
|
||||
|
||||
@@ -378,7 +378,7 @@ func importLogin(ctx context.Context, agent string, e loginImport, name string,
|
||||
switch agent {
|
||||
case "codex":
|
||||
raw := map[string]any{"tokens": map[string]any{"refresh_token": e.refreshToken}}
|
||||
if _, err := codexRefresh(ctx, raw); err != nil {
|
||||
if _, err := codexRefresh(ctx, raw, codexRefreshForced); err != nil {
|
||||
return refused("ChatGPT", err)
|
||||
}
|
||||
t := raw["tokens"].(map[string]any)
|
||||
|
||||
@@ -275,7 +275,13 @@ func renewSaved(ctx context.Context, agent, user string, force bool, stale strin
|
||||
} 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 {
|
||||
reason := codexRefreshExpiry
|
||||
if stale != "" {
|
||||
reason = codexRefreshRecovery
|
||||
} else if force {
|
||||
reason = forcedReason(ctx)
|
||||
}
|
||||
if tok, err = codexRefresh(ctx, raw, reason); err != nil {
|
||||
return "", "", savedRefreshFailed(agent, user, err)
|
||||
}
|
||||
if auth, err = json.MarshalIndent(raw, "", " "); err != nil {
|
||||
|
||||
@@ -753,10 +753,19 @@ func postToken(ctx context.Context, tokenURL, ctype string, body []byte, out any
|
||||
// postTokenAs is postToken asked with bearer, a token already had, when it
|
||||
// isn't "" (Google's IAM Credentials, which trades one for another).
|
||||
func postTokenAs(ctx context.Context, tokenURL, ctype, bearer string, body []byte, out any) error {
|
||||
return postTokenWith(ctx, tokenURL, ctype, bearer, nil, body, out)
|
||||
}
|
||||
|
||||
// postTokenWith is postTokenAs sent with the headers in h too (Codex's
|
||||
// own, codexClientHeaders).
|
||||
func postTokenWith(ctx context.Context, tokenURL, ctype, bearer string, h http.Header, body []byte, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, v := range h {
|
||||
req.Header[k] = v
|
||||
}
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if bearer != "" {
|
||||
@@ -830,7 +839,10 @@ func codexExchange(ctx context.Context, code, verifier, redirect string) (savedL
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
if err := postToken(ctx, codexTokenURL, "application/x-www-form-urlencoded", []byte(form.Encode()), &tok); err != nil {
|
||||
// sent as Codex sends it (codex-rs OAuthClient::exchange_code)
|
||||
h := http.Header{}
|
||||
codexClientHeaders(h, codexVersion())
|
||||
if err := postTokenWith(ctx, codexTokenURL, "application/x-www-form-urlencoded", "", h, []byte(form.Encode()), &tok); err != nil {
|
||||
return savedLogin{}, err
|
||||
}
|
||||
if tok.AccessToken == "" || tok.RefreshToken == "" || tok.IDToken == "" {
|
||||
|
||||
@@ -965,7 +965,7 @@ func codexWindows(ctx context.Context, token, accountID string) (plan string, ou
|
||||
var data codexUsage
|
||||
base := strings.TrimSuffix(CodexBase, "/codex")
|
||||
out = []QuotaWindow{}
|
||||
if err = accountJSON(ctx, base+"/wham/usage", token, map[string]string{"chatgpt-account-id": accountID}, &data); err != nil {
|
||||
if err = accountJSON(ctx, base+"/wham/usage", token, codexAccountHeaders(accountID), &data); err != nil {
|
||||
return "", out, nil, "", false, err
|
||||
}
|
||||
if c := data.Credits; c != nil && c.Has && !c.Unlimited {
|
||||
|
||||
Reference in New Issue
Block a user