provider: an account Codex holds in another of its folders can be removed in magpie (charliepu)

charliepu on Discord (Windows), after v0.1.2385: the account that read no
allowance couldn't be removed. Remove answered "<email> is signed in to
Codex in C:\Users\charl\.codex-db-backup-20260803: sign it out there
(CODEX_HOME=... codex logout) to remove it". That folder is a backup no
Codex runs in. appdir.CodexHomes finds it by name (".codex*" holding an
auth.json), and rememberLogins read its account back at every look, so
forgetLogin refused rather than have it come back.

Now Remove forgets the account and sets that folder's sign-in aside in a
record of magpie's own (codex-homes-removed.json: the folder to a sha256
of its refresh token, or of its access token when it has none).
codexHomeLogins passes over a folder while it holds that sign-in. The
folder's files are left as they are: nothing in it is written, moved or
deleted. A sign-in made
in that folder again (Codex run there, a new token) isn't named by the
record, and is listed again with no step of the user's. With the record
unreadable, which sign-ins were removed is unknown, and no other folder's
account is read that time (accounts saved already stay listed).

Not done: treating ".codex-db-backup-*" folders as not Codex homes by
name. They are found by the same rule as ~/.codex-work, and their
sessions/ are still read for Sessions and usage as before; a name rule
would guess at what a user's folder is for. Removing is the user's own
answer, and works for any such folder.

Run at this head (origin/main 70d50254c plus this change; the doc line
added after):
- mote: go test -timeout 45m -count=1 ./internal/provider ./internal/appdir: ok (provider 142s;
  135s at the earlier base e90a635a9)
- mote: GOOS=windows and GOOS=linux go vet ./internal/provider: ok
- xiaomi-gpu (Windows 11, win-run): go test ./internal/provider -run
  'TestCodexHeldFolderAccountRemoved|TestCodexOtherHome|TestCodexHeldInOtherFolder':
  all four pass
- gofmt -l internal/provider: empty

Broken by hand, each red:
- logins.go as on main: TestCodexHeldFolderAccountRemoved fails with the
  "codex logout) to remove it" refusal, and so does
  TestCodexOtherHomeAccountReadsQuota (its last check pinned the refusal;
  it now expects the removal to go through).
- codexHomeLogins ignoring the record: "removed, then read back from the
  backup folder".
- an unreadable record read as empty: "with the record unreadable, the
  removed account came back".

docs/subsystems/providers-accounts.md's "Codex's other folders" row
said such an account couldn't be removed; it now says what Remove and
v0.1.2385's Sign in again do.

Not tried: the real app on Windows with a real backup folder (the test
runs on Windows with a sandbox HOME); a real account. No GUI change: the
row's Remove posts login/forget as before, which now goes through.
This commit is contained in:
yetone
2026-10-31 19:42:52 +08:00
parent 70d50254cb
commit e484b1e936
5 changed files with 191 additions and 5 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
| 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) |
| Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/<name>.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares) nor removed (`forgetLogin`): each error names the folder and the `CODEX_HOME=… codex` command. phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_test.go) |
| Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/<name>.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares): the error names the folder and the `CODEX_HOME=… codex` command. A refresh OpenAI refuses there marks the account signed out (`codexHeldRefusal`, `codexSignInRead`), so its row has Sign in again, and magpie's sign-in writes the new tokens back to that folder (`codexHeldFolder` in `addLogin`), never to `~/.codex` (`TestCodexHeldInOtherFolderSignedOutThenSignedInAgain`). Remove forgets it and sets that folder's sign-in aside in `codex-homes-removed.json` (the folder to a SHA-256 of its refresh token, `setCodexAside`), the folder's files left as they are; `codexHomeLogins` passes over the folder while it holds that sign-in, and a sign-in made there again is listed again. An unreadable record reads no other folder's account that look (charliepu on Discord: a `.codex-db-backup-…` folder no Codex runs in, refused with "codex logout"; `TestCodexHeldFolderAccountRemoved`). phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_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. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, 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 is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. 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) |
+95
View File
@@ -0,0 +1,95 @@
package provider
// An account Codex is signed in to in another of its folders (codexHomeLogins)
// was read again from there at every look, so Remove refused it and said to
// run `CODEX_HOME=… codex logout` (charliepu on Discord, Windows: the
// folder was C:\Users\…\.codex-db-backup-20260803, a backup no Codex runs
// in). Removed now, the folder's sign-in is set aside here, magpie's own
// record: that folder is listed no more while it holds that sign-in. Its
// files are left as they are. A sign-in made there again is another token,
// which nothing here names: it is listed again with no step of the user's.
import (
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"sync"
"github.com/yetone/magpie/internal/lastgood"
)
// codexAsideMu guards the record's file.
var codexAsideMu sync.Mutex
// codexAsidePath is the record: a Codex folder to the hash of the sign-in
// in it that the user removed from magpie (codexAsideKey).
func codexAsidePath() string {
return filepath.Join(filepath.Dir(Path()), "codex-homes-removed.json")
}
// codexAsideKey names the sign-in auth holds without keeping it: its
// refresh token, or its access token when it has none. "" for none.
func codexAsideKey(auth []byte) string {
var a codexAuth
if json.Unmarshal(auth, &a) != nil {
return ""
}
if a.Tokens.RefreshToken != "" {
return codexGoneHash(a.Tokens.RefreshToken)
}
if a.Tokens.AccessToken != "" {
return codexGoneHash(a.Tokens.AccessToken)
}
return ""
}
// readCodexAside reads the record. None yet is empty; one that can't be
// read or doesn't parse is an error: what it sets aside is unknown.
func readCodexAside() (map[string]string, error) {
m := map[string]string{}
b, err := os.ReadFile(codexAsidePath())
if errors.Is(err, fs.ErrNotExist) {
return m, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
return m, nil
}
// setCodexAside records that the sign-in auth in the Codex folder dir was
// removed from magpie.
func setCodexAside(dir string, auth []byte) error {
key := codexAsideKey(auth)
if key == "" {
return nil
}
codexAsideMu.Lock()
defer codexAsideMu.Unlock()
m, err := readCodexAside()
if err != nil {
// a record that doesn't parse is kept aside, then begun again
m = map[string]string{}
}
m[filepath.Clean(dir)] = key
out, err := json.MarshalIndent(m, "", " ")
if err == nil {
err = lastgood.KeepUnparsed(codexAsidePath(), lastgood.Into[map[string]string])
}
if err == nil {
err = writePrivate(codexAsidePath(), append(out, '\n'))
}
return err
}
// codexSetAside says whether l, read from its folder l.Home, is the sign-in
// the user removed from magpie there, by the record m (readCodexAside).
func codexSetAside(l savedLogin, m map[string]string) bool {
key := codexAsideKey(l.Auth)
return key != "" && m[filepath.Clean(l.Home)] == key
}
@@ -0,0 +1,74 @@
package provider
import (
"os"
"path/filepath"
"testing"
)
// charliepu on Discord (Windows, 10-31): an account Codex was signed in to
// in C:\Users\charl\.codex-db-backup-20260803, a backup no Codex runs in,
// couldn't be removed: "sign it out there (CODEX_HOME=… codex logout) to
// remove it". Now Remove takes it out of magpie, the folder's files left
// as they are, and it isn't read back from there at the next look. A
// sign-in made in that folder again is listed again.
func TestCodexHeldFolderAccountRemoved(t *testing.T) {
home := signIn(t)
t.Setenv("CODEX_HOME", "")
backup := filepath.Join(home, ".codex-db-backup-20260803")
auth := func(refresh string) map[string]any {
idTok := fakeJWT(map[string]any{"email": "pro@example.com",
"https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "pro", "chatgpt_account_id": "acct-pro"}})
return map[string]any{"auth_mode": "chatgpt", "OPENAI_API_KEY": nil, "last_refresh": "2026-08-03T00:00:00Z",
"tokens": map[string]any{"id_token": idTok, "access_token": fakeJWT(map[string]any{"exp": 1.0}),
"refresh_token": refresh, "account_id": "acct-pro"}}
}
writeFile(t, filepath.Join(backup, "auth.json"), auth("r-old"))
before, _ := os.ReadFile(filepath.Join(backup, "auth.json"))
listed := func() bool {
ForgetAccounts()
rememberLogins(true)
for _, l := range Logins("codex") {
if l.User == "pro@example.com" {
return true
}
}
return false
}
if !listed() {
t.Fatalf("the backup folder's account isn't listed: %+v", Logins("codex"))
}
if err := ForgetLogin("codex", "pro@example.com"); err != nil {
t.Fatalf("remove the account held in the backup folder: %v", err)
}
if after, _ := os.ReadFile(filepath.Join(backup, "auth.json")); string(after) != string(before) {
t.Errorf("the backup folder's auth.json was changed: %s", after)
}
if listed() {
t.Fatalf("removed, then read back from the backup folder: %+v", Logins("codex"))
}
for _, l := range Logins("codex") {
if l.User != "me@example.com" {
t.Errorf("left after the removal: %+v", l)
}
}
// unreadable, the record says nothing: the removed account isn't
// listed again on a guess
if err := os.WriteFile(codexAsidePath(), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if listed() {
t.Fatalf("with the record unreadable, the removed account came back")
}
if err := setCodexAside(backup, before); err != nil {
t.Fatal(err)
}
// Codex signed in in that folder again: another sign-in, listed
writeFile(t, filepath.Join(backup, "auth.json"), auth("r-new"))
if !listed() {
t.Fatalf("a new sign-in in the folder isn't listed: %+v", Logins("codex"))
}
}
+3 -1
View File
@@ -108,7 +108,9 @@ func TestCodexOtherHomeAccountReadsQuota(t *testing.T) {
if now, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json")); string(now) != string(mainAuth) {
t.Errorf("~/.codex/auth.json was rewritten: %s", now)
}
if err := ForgetLogin("codex", "work@example.com"); err == nil || !strings.Contains(err.Error(), "codex logout") {
// removed from magpie, ~/.codex-work left as it is
// (TestCodexHeldFolderAccountRemoved)
if err := ForgetLogin("codex", "work@example.com"); err != nil {
t.Errorf("remove the other folder's account: %v", err)
}
}
+18 -3
View File
@@ -755,8 +755,14 @@ func codexOtherHomes() []string { return appdir.CodexHomes()[1:] }
// other Codex folders, each with its folder as Home: one Codex keeps
// signed in itself, as it does the one in ~/.codex. The one ~/.codex is
// signed in to is that one's, wherever else it is too, and an account in
// two other folders is the first's.
// two other folders is the first's. A folder's sign-in the user removed
// from magpie is passed over (codexSetAside); with that record unreadable,
// which ones were removed is unknown, and none is read this time.
func codexHomeLogins(live savedLogin, haveLive bool) []savedLogin {
aside, err := readCodexAside()
if err != nil {
return nil
}
var out []savedLogin
for _, home := range codexOtherHomes() {
l, ok := codexLoginIn(home)
@@ -764,6 +770,9 @@ func codexHomeLogins(live savedLogin, haveLive bool) []savedLogin {
continue
}
l.Home = home
if codexSetAside(l, aside) {
continue
}
out = append(out, l)
}
return out
@@ -1443,8 +1452,14 @@ func forgetLogin(agent, user string) (signedOut bool, err error) {
for _, l := range ls {
if l.Agent == agent && strings.EqualFold(l.User, user) {
if home := codexHeldIn(l); home != "" {
// it would be read again from there at the next look
return false, fmt.Errorf("%s is signed in to Codex in %s: sign it out there (CODEX_HOME=%s codex logout) to remove it", l.User, home, home)
// it would be read again from there at the next look: that
// folder's sign-in is set aside instead, its files left as
// they are (charliepu's .codex-db-backup-…, which no Codex
// runs in, refused with "codex logout")
in, _ := codexLoginIn(home)
if err := setCodexAside(home, in.Auth); err != nil {
return false, fmt.Errorf("removing %s, signed in to Codex in %s: %w", l.User, home, err)
}
}
}
}