claude: Use switches Claude Code itself to a setup-token account (liukaybee on X)

liukaybee adds Claude accounts with `claude setup-token` and wants magpie
to switch only which one Claude Code itself uses, without connecting it
to magpie. Such an account has no sign-in to put in Claude Code's
keychain or .credentials.json, so Use was refused ("magpie only").

Claude Code takes CLAUDE_CODE_OAUTH_TOKEN from the env of its user
settings.json ahead of its stored sign-in. Use on a setup-token account
now writes the token there (claude_token_env.go). Claude Code's stored
sign-in stays as it is and stays Active; the token account is listed
with Uses. A switch to a signed-in account, Use on the signed-in row,
or removing the token's account takes the token out again.

- A value the user set is theirs: magpie keeps only the sha256 of what
  it wrote (claude-token-env.json), never writes over another value and
  never removes one whose hash differs, even if it once wrote it.
- An unreadable settings.json is "unknown": nothing is written, the
  record is kept, and the switch fails without moving the sign-in.
- NextLogin (Switch accounts only) leaves Claude Code on a token in use,
  as its allowance can't be read.
- magpie's own runs pass --setting-sources "" and are unaffected.
- GUI: the token row's Use and In use; the signed-in row says Signed in
  with a Use back. Every new string in zh, zh-TW, ja and de.
- app.js +864 bytes over its budget, raised with the reason in
  core_budget_test.go: one swUse helper shared by both buttons, packed;
  renderAccounts draws every account row, so no page to move it to.

Real use: real Claude Code 2.1.316 in a sandbox HOME/CLAUDE_CONFIG_DIR
(never the live ~/.claude) with a deliberately broken .credentials.json
access token. The settings.json magpie's switch writes (dumped from a
test) gave a PONG with a real account's token; the file after switching
back gave "401 OAuth access token is invalid", i.e. Claude Code was on
its stored sign-in again. Sandbox homes holding real tokens deleted.

Run (mote/mica, at f00e2059d rebased on 593517bf0, then this head):
- Rebased on effdd1beb (internal/gui and internal/provider untouched
  since, but for this): TestCoreScriptBudget and the provider TestClaude*,
  NextLogin and Forget tests rerun at the pushed head, ok.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok. gofmt -l: clean.
- go test ./... -timeout 45m on mote: 102 packages ok, internal/gui
  FAIL: TestCoreScriptBudget (fixed above, then green) and
  TestQuitKeepsTheMenuBarIconsPlace, killed at its 30s AppKit bar under
  load; passes alone in 1.1s here and on origin/main 00b2c11a6. Filed
  #6919.
- GUI, both engines, every language, on mica: the 45 account, Claude,
  switch, sign-in and i18n files (1275 tests, 68 red). The same 9 red
  files on origin/main effdd1beb give 67 of the same reds (#5925, #6660,
  #6179, #6424, #6010, #5998, #5814, #6877). The one red only at this
  head, accounts-own-signin webkit zh (access-control on /api/autobackup)
  is #6038 and passes 20/20 alone. claude-setup-token: green in all 10
  engine x language runs.

Broken by hand, each red, then restored: the own-value check
(TestClaudeOwnEnvTokenLeftAlone), clearing on an OAuth switch
(TestClaudeCodeSwitchedToSetupToken, ...UnreadableSettings), clearing
on Use back (Switched, InUseNotMovedOff), clearing on remove
(TestClaudeSetupTokenRemovedLeavesSettings), the NextLogin guard
(InUseNotMovedOff), unreadable settings read as empty
(TestClaudeEnvTokenUnreadableSettings).

Not tried: the whole GUI suite (both machines were running other
sessions' full suites for hours); a magpie GUI build clicking Use
against the real binary (the switch's file was checked instead);
Windows and Linux Claude Code.
This commit is contained in:
yetone
2026-11-17 11:42:27 +08:00
parent effdd1beb9
commit 2f25728ddf
12 changed files with 662 additions and 37 deletions
File diff suppressed because one or more lines are too long
+15 -3
View File
@@ -13566,9 +13566,13 @@ function renderAccounts(a, p) {
const quota = loginUsageOf(a.agent);
// signed out while spent, back once it has room (#408)
const back = ls.find((l) => l.returns && !l.active);
// the setup-token Claude Code itself uses over its sign-in
const tokenUsed = ls.find((l) => l.uses);
for (const l of ls) {
const on = isOn(l);
const row = el("div", "acc" + (on ? " in-use" : " off") + (l.user === justAdded ? " new" : ""));
// Use that switches Claude Code itself
const swUse = (title, b = el("button", "text", t("Use"))) => (b.title = title, b.onclick = () => (b.classList.add("busy"), accountAction("login/switch", { agent: a.agent, user: l.user }, t("{agent} now uses {user}", { agent: a.agentName, user: l.user }))), b);
// its Remove, titled as given; true: the own account's, else the plain one
const forgetOf = (title) => {
const f = el("button", "text quiet", t("Remove"));
@@ -13661,6 +13665,11 @@ function renderAccounts(a, p) {
signed.title = t("{agent} is kept signed in to this account; requests through magpie go to the accounts in their order", { agent: a.agentName });
line.append(signed);
if (on) line.append(makeFirst(l));
} else if (l.active && tokenUsed) {
// its sign-in still, under the setup-token Claude Code uses over it
const signed = el("span", "using", l.paused ? t("Paused") : t("Signed in"));
signed.title = t("{agent} is signed in to this account, but uses {user}'s setup-token over it", { agent: a.agentName, user: tokenUsed.user });
line.append(signed, swUse(t("Switch {agent} itself back to this account", { agent: a.agentName })));
} else if (l.active) {
const using = el("span", "using", l.paused ? t("Paused") : back ? t("First for now") : several ? t("First") : t("In use"));
if (back && !l.paused) using.title = t("{user} was nearly used up, so magpie signed {agent} in to this one; it goes back to {user} once that has room again", { user: back.user, agent: a.agentName });
@@ -13689,10 +13698,13 @@ function renderAccounts(a, p) {
line.append(forget);
if (l.user === firstUser) line.append(el("span", "using", t("First")));
else if (on) line.append(makeFirst(l));
} else if (l.token && l.uses) {
const using = el("span", "using", t("In use"));
using.title = t("{agent} itself uses this setup-token, set in its settings.json", { agent: a.agentName });
line.append(forget, using);
} else if (l.token) {
const only = el("span", "using", t("magpie only"));
only.title = t("Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it");
line.append(forget, only);
// Claude Code itself switched to it in its settings.json (liukaybee on X)
line.append(forget, swUse(t("Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays", { agent: a.agentName })));
} else if (l.accessOnly) {
const only = el("span", "using", t("magpie only"));
only.title = t("Kept access token only: requests through magpie use it until it expires; Codex itself isn't signed in to it, as Codex would renew it");
+20 -4
View File
@@ -2487,7 +2487,11 @@ const I18N = {
"Add an account by setup-token…": "用 setup-token 添加账号…",
"Sign in on another computer…": "在另一台电脑上登录…",
"magpie only": "仅 magpie",
"Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 添加:经 magpie 的请求会使用它;Claude Code 本身无法登录到这个账号",
"{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} 登录的是这个账号,但优先使用 {user} 的 setup-token",
"Switch {agent} itself back to this account": "把 {agent} 本身切回这个账号",
"{agent} now uses {user}": "{agent} 现在使用 {user}",
"{agent} itself uses this setup-token, set in its settings.json": "{agent} 本身正在使用这个 setup-token,写在它的 settings.json 里",
"Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "把 {agent} 本身切换到这个 setup-token(写入它的 settings.json);它原有的登录保持不变",
"Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "导入从 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 导出的账号",
"Import accounts from a file…": "从文件导入账号…",
"Import {name} accounts": "导入 {name} 账号",
@@ -7842,7 +7846,11 @@ const I18N = {
"Add an account by setup-token…": "用 setup-token 新增帳號…",
"Sign in on another computer…": "在另一台電腦上登入…",
"magpie only": "僅 magpie",
"Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 新增:經 magpie 的請求會使用它;Claude Code 本身無法登入到這個帳號",
"{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} 登入的是這個帳號,但優先使用 {user} 的 setup-token",
"Switch {agent} itself back to this account": "把 {agent} 本身切回這個帳號",
"{agent} now uses {user}": "{agent} 現在使用 {user}",
"{agent} itself uses this setup-token, set in its settings.json": "{agent} 本身正在使用這個 setup-token,寫在它的 settings.json 裡",
"Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "把 {agent} 本身切換到這個 setup-token(寫入它的 settings.json);它原有的登入保持不變",
"Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "匯入從 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 匯出的帳號",
"Import accounts from a file…": "從檔案匯入帳號…",
"Import {name} accounts": "匯入 {name} 帳號",
@@ -13172,7 +13180,11 @@ const I18N = {
"Add an account by setup-token…": "setup-token でアカウントを追加…",
"Sign in on another computer…": "別のコンピュータでサインイン…",
"magpie only": "magpie のみ",
"Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "setup-token で追加:magpie 経由のリクエストはこれを使いますが、Claude Code 自体をこのアカウントにサインインさせることはできません",
"{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} はこのアカウントにサインインしていますが、{user} の setup-token を優先して使っています",
"Switch {agent} itself back to this account": "{agent} 自体をこのアカウントに戻します",
"{agent} now uses {user}": "{agent} は {user} を使うようになりました",
"{agent} itself uses this setup-token, set in its settings.json": "{agent} 自体がこの setup-token を使っています(settings.json に設定)",
"Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "{agent} 自体をこの setup-token に切り替えます(settings.json に設定)。元のサインインはそのままです",
"Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Antigravity Cockpit、Antigravity Manager、CLIProxyAPI からエクスポートしたアカウントを取り込みます",
"Import accounts from a file…": "ファイルからアカウントをインポート…",
"Import {name} accounts": "{name} アカウントをインポート",
@@ -18533,7 +18545,11 @@ const I18N = {
"Add an account by setup-token…": "Konto per setup-token hinzufügen…",
"Sign in on another computer…": "Auf einem anderen Computer anmelden…",
"magpie only": "Nur magpie",
"Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "Per setup-token hinzugefügt: Anfragen über magpie nutzen es; Claude Code selbst kann sich damit nicht anmelden",
"{agent} is signed in to this account, but uses {user}'s setup-token over it": "{agent} ist bei diesem Konto angemeldet, nutzt aber vorrangig das Setup-Token von {user}",
"Switch {agent} itself back to this account": "{agent} selbst wieder auf dieses Konto umstellen",
"{agent} now uses {user}": "{agent} nutzt jetzt {user}",
"{agent} itself uses this setup-token, set in its settings.json": "{agent} selbst nutzt dieses Setup-Token, eingetragen in seiner settings.json",
"Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays": "{agent} selbst auf dieses Setup-Token umstellen, in seiner settings.json; seine eigene Anmeldung bleibt",
"Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Konten übernehmen, die aus Antigravity Cockpit, Antigravity Manager oder CLIProxyAPI exportiert wurden",
"Import accounts from a file…": "Konten aus Datei importieren…",
"Import {name} accounts": "{name}-Konten importieren",
File diff suppressed because one or more lines are too long
+38 -12
View File
@@ -3,8 +3,9 @@
// "Use a setup-token instead…", which ends the browser sign-in and asks for
// the token `claude setup-token` printed, said whole in the page's
// language. A refused token says why and stays to be fixed; one taken is
// added. The account it makes is magpie's only: Remove and "magpie only",
// no Use or Make first.
// added. Its row's Use switches Claude Code itself to it (in its
// settings.json, liukaybee on X); in use, the signed-in account's Use
// switches back.
// Chromium and WebKit, English, Chinese (both), Japanese and German, at
// 420px; no backend, the API is faked here.
const assert = require("node:assert/strict");
@@ -107,19 +108,44 @@ for (const engine of engines) for (const lang of ["en", "zh", "zh-TW", "ja", "de
assert.deepEqual(await page.evaluate(() => window.signedInWith), [{ agent: "claude", user: "Claude setup-token 3204d0", token: true }]);
assert.equal(await box.innerText().then((s) => s.includes(TOKEN)), false);
// its row is magpie's only
const row = await page.evaluate(() => {
const ls = [{ user: "pro@x.com", active: true, plan: "max" }, { user: "Claude setup-token 3204d0", on: true, token: true }];
// its row's Use switches Claude Code itself to it (liukaybee on X)
const rowsOf = (uses) => page.evaluate((uses) => {
document.getElementById("accts-under-test")?.remove();
const ls = [{ user: "pro@x.com", active: true, plan: "max" }, { user: "Claude setup-token 3204d0", on: true, token: true, uses }];
const a = { agent: "claude", agentName: "Claude Code", logins: ls };
const list = renderAccounts(a, { id: "claude", account: { agent: "claude", user: "pro@x.com" } });
list.id = "accts-under-test";
document.body.append(list);
const rows = [...list.querySelectorAll("*")].filter((e) => e.textContent.includes("Claude setup-token 3204d0") && !e.textContent.includes("pro@x.com") && e.querySelector("button"));
const r = rows[0];
return r ? { text: r.innerText, buttons: [...r.querySelectorAll("button")].map((b) => b.textContent) } : null;
}).catch((e) => ({ error: e.message }));
assert.ok(row && !row.error, JSON.stringify(row));
assert.ok(row.text.includes(await translated("magpie only")), row.text);
assert.ok(!row.buttons.includes(await said("Make first")) && !row.buttons.includes(await said("Use")), row.buttons.join(","));
const of = (u) => {
const r = list.querySelector(`[data-account-id="${u}"] .acc-line`);
return { text: r.innerText, buttons: [...r.querySelectorAll("button.text")].map((b) => ({ text: b.textContent, title: b.title })), spans: [...r.querySelectorAll(".using")].map((x) => ({ text: x.textContent, title: x.title })) };
};
return { pro: of("pro@x.com"), tok: of("Claude setup-token 3204d0") };
}, uses);
const use = await said("Use");
let rows = await rowsOf(false);
const tokUse = rows.tok.buttons.find((b) => b.text === use);
assert.ok(tokUse, JSON.stringify(rows.tok));
assert.equal(tokUse.title, await translated("Switch {agent} itself to this setup-token, in its settings.json; its own sign-in stays", { agent: "Claude Code" }));
assert.ok(!rows.tok.text.includes(await said("magpie only")), rows.tok.text);
assert.ok(!rows.pro.buttons.some((b) => b.text === use), JSON.stringify(rows.pro));
const posted = page.waitForRequest((r) => new URL(r.url()).pathname === "/api/login/switch");
await page.locator('#accts-under-test [data-account-id="Claude setup-token 3204d0"] button.text', { hasText: use }).click();
assert.deepEqual((await posted).postDataJSON(), { agent: "claude", user: "Claude setup-token 3204d0" });
// in use: said on it, and the signed-in account's Use switches back
rows = await rowsOf(true);
assert.deepEqual(rows.tok.spans.map((x) => x.text), [await said("In use")]);
assert.equal(rows.tok.spans[0].title, await translated("{agent} itself uses this setup-token, set in its settings.json", { agent: "Claude Code" }));
assert.ok(!rows.tok.buttons.some((b) => b.text === use), JSON.stringify(rows.tok));
assert.deepEqual(rows.pro.spans.map((x) => x.text), [await said("Signed in")]);
assert.equal(rows.pro.spans[0].title, await translated("{agent} is signed in to this account, but uses {user}'s setup-token over it", { agent: "Claude Code", user: "Claude setup-token 3204d0" }));
const back = rows.pro.buttons.find((b) => b.text === use);
assert.ok(back, JSON.stringify(rows.pro));
assert.equal(back.title, await translated("Switch {agent} itself back to this account", { agent: "Claude Code" }));
await translated("{agent} now uses {user}", { agent: "Claude Code", user: "pro@x.com" });
const w2 = await page.evaluate(() => Math.max(...[...document.querySelectorAll("#accts-under-test *")].map((e) => e.getBoundingClientRect().right)));
assert.ok(w2 <= 420, `accounts reach ${w2}px`);
assert.deepEqual(errors, []);
});
}
+2 -1
View File
@@ -240,7 +240,8 @@ func syncClaudeProxyEnvNow() {
}
user := ""
for _, l := range Logins("claude") {
if l.Active {
if l.Active && user == "" || l.Uses {
// the setup-token it uses over its sign-in, if any
user = l.User
}
}
+8 -5
View File
@@ -11,8 +11,9 @@ package provider
// "oauth_token" and no more), and its /usage shows the API cost view, not
// the subscription's windows. The account is named by the token's own
// short hash, and its allowance is unknown (errClaudeSetupToken) until a
// reply's rate-limit headers tell it. Claude Code itself can't be signed in
// to it: there is nothing to put in its keychain or .credentials.json.
// reply's rate-limit headers tell it. There is nothing to put in Claude
// Code's keychain or .credentials.json for it: Claude Code itself is
// switched to it through its settings.json (claude_token_env.go).
import (
"crypto/sha256"
@@ -65,9 +66,11 @@ func claudeTokenName(token string) string {
// zero. Its words must not read as a refusal (claudeUsageDenied).
var errClaudeSetupToken = errors.New("unknown: a setup-token can't read the allowance (Claude Code's /usage needs a full sign-in); it shows once a reply tells it")
// errClaudeTokenSwitch is the answer to signing Claude Code in to a
// setup-token account.
const errClaudeTokenSwitch = "%s was added by a setup-token: magpie's requests use it, but Claude Code itself can't be signed in to it"
// errClaudeTokenSwitch is the answer to keeping Claude Code signed in to a
// setup-token account (SetKeepLoginAs), or to putting one in its sign-in
// store: Claude Code is switched to it in its settings.json alone
// (claude_token_env.go), when the user picks it.
const errClaudeTokenSwitch = "%s was added by a setup-token: Use switches Claude Code itself to it, but magpie can't keep Claude Code on it, as it can't read its allowance"
// checkClaudeSetupToken is token trimmed, or why it isn't a setup-token.
func checkClaudeSetupToken(token string) (string, error) {
+3 -2
View File
@@ -87,8 +87,9 @@ func TestClaudeSetupTokenAccount(t *testing.T) {
t.Fatal("Claude Code's own run was given the token")
}
// Claude Code can't be signed in to it
if err := SwitchLogin("claude", user); err == nil || !strings.Contains(err.Error(), "setup-token") {
// Claude Code's own sign-in isn't written with it: a switch to it
// goes in settings.json (claude_token_env_test.go)
if err := SwitchLogin("claude", user); err != nil {
t.Fatalf("switch onto a setup-token account: %v", err)
}
if after, _ := os.ReadFile(cred); string(after) != string(before) {
+228
View File
@@ -0,0 +1,228 @@
package provider
// Claude Code itself on an account added by a setup-token (liukaybee on X).
// There is no sign-in to put in Claude Code's keychain or
// .credentials.json for such an account, but Claude Code takes the token
// in CLAUDE_CODE_OAUTH_TOKEN, and reads that from the env of its user
// settings.json too, ahead of its stored sign-in (its docs' authentication
// order; tried with Claude Code 2.1.316: a token there is used over a
// valid stored sign-in, and with it taken out the stored sign-in is used
// again). So a switch to such an account writes the token there, and a
// switch to a signed-in account takes it out again.
//
// Claude Code's stored sign-in is left as it is meanwhile: it is still
// the account magpie's own runs of Claude Code are on, since those read
// no settings of the user's (--setting-sources ""), and the account
// Logins calls Active. A setup-token in use is said beside it (Login.Uses).
//
// A token the user set there is theirs: magpie writes none over it and
// never takes it out. magpie keeps the hash of the token it wrote
// (claude-token-env.json), and the value counts as its own only while it
// still has that hash. Claude Code reads its env as it starts, so it is
// the sessions started after a switch that are on the new account.
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/edit"
)
const claudeTokenEnvKey = "CLAUDE_CODE_OAUTH_TOKEN"
var claudeTokenEnvMu sync.Mutex
func claudeTokenRecordPath() string {
return filepath.Join(filepath.Dir(Path()), "claude-token-env.json")
}
// claudeTokenRecord is what magpie last wrote to Claude Code's env: the
// token's hash, never the token.
type claudeTokenRecord struct {
Hash string `json:"hash"`
}
func claudeTokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// readClaudeTokenRecord is the hash magpie wrote, "" for none. One that
// can't be read is an error, never "nothing written": that would make
// magpie's own token look like the user's for good.
func readClaudeTokenRecord() (string, error) {
b, err := os.ReadFile(claudeTokenRecordPath())
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", err
}
var r claudeTokenRecord
if err := json.Unmarshal(b, &r); err != nil {
return "", fmt.Errorf("%s: %w", claudeTokenRecordPath(), err)
}
return r.Hash, nil
}
func writeClaudeTokenRecord(hash string) error {
if hash == "" {
if err := os.Remove(claudeTokenRecordPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
b, err := json.MarshalIndent(claudeTokenRecord{Hash: hash}, "", " ")
if err != nil {
return err
}
return writePrivate(claudeTokenRecordPath(), append(b, '\n'))
}
// claudeEnvToken is CLAUDE_CODE_OAUTH_TOKEN in the env of Claude Code's
// settings.json, and whether it is set there. A file that can't be read
// is an error: what it holds is unknown.
func claudeEnvToken() (string, bool, error) {
path := claudeSettingsFile()
raw, err := edit.Read(path)
if err != nil {
return "", false, err
}
if len(bytes.TrimSpace(raw)) == 0 {
return "", false, nil
}
stripped := jsonc.ToJSON(raw)
if !json.Valid(stripped) {
return "", false, fmt.Errorf("%s can't be read", path)
}
v := gjson.GetBytes(stripped, "env."+claudeTokenEnvKey)
return v.String(), v.Exists(), nil
}
// claudeTokenInUse is the setup-token magpie has Claude Code use, ""
// when there is none of magpie's in its settings.json (none, the user's
// own, or one that can't be read).
func claudeTokenInUse() string {
claudeTokenEnvMu.Lock()
defer claudeTokenEnvMu.Unlock()
return claudeTokenOursLocked()
}
func claudeTokenOursLocked() string {
hash, err := readClaudeTokenRecord()
if err != nil || hash == "" {
return ""
}
v, ok, err := claudeEnvToken()
if err != nil || !ok || v == "" || claudeTokenHash(v) != hash {
return ""
}
return v
}
// ClaudeTokenUser is the saved setup-token account Claude Code itself
// uses now (magpie's token in its settings.json), "" for none.
func ClaudeTokenUser() string {
tok := claudeTokenInUse()
if tok == "" {
return ""
}
loginsMu.Lock()
defer loginsMu.Unlock()
return claudeTokenUserIn(readLogins(), tok)
}
func claudeTokenUserIn(ls []savedLogin, tok string) string {
if tok == "" {
return ""
}
for _, l := range ls {
if l.Agent == "claude" && claudeSetupToken(l.Auth) == tok {
return l.User
}
}
return ""
}
// errClaudeOwnToken: the user set CLAUDE_CODE_OAUTH_TOKEN in Claude
// Code's settings.json themselves.
const errClaudeOwnToken = "Claude Code's %s sets CLAUDE_CODE_OAUTH_TOKEN of your own, which Claude Code uses over any account magpie switches it to; magpie leaves it as it is. Take it out there to switch Claude Code here."
// setClaudeEnvToken has Claude Code use token (setClaudeEnvToken("")
// takes magpie's out again), leaving a value the user set alone: putting
// one in over it is an error, taking magpie's out leaves it.
func setClaudeEnvToken(token string) error {
claudeTokenEnvMu.Lock()
defer claudeTokenEnvMu.Unlock()
return setClaudeEnvTokenLocked(token)
}
func setClaudeEnvTokenLocked(token string) error {
hash, err := readClaudeTokenRecord()
if err != nil {
return err
}
if token == "" && hash == "" {
return nil // nothing of magpie's there, nor to be
}
path := claudeSettingsFile()
cur, has, err := claudeEnvToken()
if err != nil {
if token == "" {
// what it holds is unknown: magpie's token may be there yet,
// and the record is kept to take it out once it can be read
return err
}
return fmt.Errorf("%w; Claude Code is left on the account it is on", err)
}
ours := has && hash != "" && claudeTokenHash(cur) == hash
if token == "" {
if ours {
if err := edit.DelJSON(path, "env."+claudeTokenEnvKey); err != nil {
return err
}
}
return writeClaudeTokenRecord("")
}
if has && !ours && cur != "" {
return fmt.Errorf(errClaudeOwnToken, path)
}
// what is about to be written is kept first: a crash between the two
// then leaves a record of a value that isn't there, never a value of
// magpie's that looks like the user's
if err := writeClaudeTokenRecord(claudeTokenHash(token)); err != nil {
return err
}
if has && cur == token {
return nil
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
return edit.SetJSON(path, edit.KV{Path: "env." + claudeTokenEnvKey, Value: token})
}
// claudeTokenGone takes magpie's token for the removed account l out of
// Claude Code's settings.json, so Claude Code goes back to its own
// sign-in; another account's, or the user's own, stays.
func claudeTokenGone(l savedLogin) error {
tok := claudeSetupToken(l.Auth)
if tok == "" || l.Agent != "claude" {
return nil
}
claudeTokenEnvMu.Lock()
defer claudeTokenEnvMu.Unlock()
if claudeTokenOursLocked() != tok {
return nil
}
return setClaudeEnvTokenLocked("")
}
+270
View File
@@ -0,0 +1,270 @@
package provider
import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/tidwall/gjson"
)
// envTokenOf is CLAUDE_CODE_OAUTH_TOKEN in Claude Code's settings.json.
func envTokenOf(t *testing.T) (string, bool) {
t.Helper()
b, err := os.ReadFile(claudeSettingsFile())
if os.IsNotExist(err) {
return "", false
}
if err != nil {
t.Fatal(err)
}
v := gjson.GetBytes(b, "env."+claudeTokenEnvKey)
return v.String(), v.Exists()
}
func claudeLoginOf(t *testing.T, user string) Login {
t.Helper()
for _, l := range Logins("claude") {
if l.User == user {
return l
}
}
t.Fatalf("%q isn't listed: %+v", user, Logins("claude"))
return Login{}
}
// liukaybee on X: accounts added by `claude setup-token`, and Claude Code
// itself switched among them, never connected to magpie. Use on such an
// account puts its token in Claude Code's settings.json env, which Claude
// Code takes over its stored sign-in; that sign-in is left as it is, and a
// switch to a signed-in account takes the token out again.
func TestClaudeCodeSwitchedToSetupToken(t *testing.T) {
claudeThree(t) // Claude Code on the Pro, the Team and Max saved
pro, team := "pro@x.com", "team@x.com · Acme"
cred := claudeSettingsFile()
cred = filepath.Join(filepath.Dir(cred), ".credentials.json")
before, err := os.ReadFile(cred)
if err != nil {
t.Fatal(err)
}
// the user's own env stays beside magpie's token
writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{"FOO": "bar"}, "model": "opus"})
tok, err := AddClaudeSetupToken(testSetupToken)
if err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
if v, _ := envTokenOf(t); v != testSetupToken {
t.Fatalf("settings.json's %s = %q, want the setup-token", claudeTokenEnvKey, v)
}
if after, _ := os.ReadFile(cred); string(after) != string(before) {
t.Fatal("a switch to a setup-token wrote Claude Code's stored sign-in")
}
b, _ := os.ReadFile(claudeSettingsFile())
if gjson.GetBytes(b, "env.FOO").String() != "bar" || gjson.GetBytes(b, "model").String() != "opus" {
t.Fatalf("the user's settings were lost: %s", b)
}
if b, _ := os.ReadFile(claudeTokenRecordPath()); strings.Contains(string(b), testSetupToken) {
t.Fatal("the record keeps the token, not its hash")
}
if l := claudeLoginOf(t, tok); !l.Uses || l.Active {
t.Fatalf("setup-token listed as %+v, want Uses and not Active", l)
}
if l := claudeLoginOf(t, pro); !l.Active || l.Uses {
t.Fatalf("Claude Code's sign-in listed as %+v, want Active", l)
}
if err := SwitchLogin("claude", tok); err != nil { // again: nothing to do
t.Fatal(err)
}
// back to the account it is signed in to: the token goes
if err := SwitchLogin("claude", pro); err != nil {
t.Fatal(err)
}
if _, has := envTokenOf(t); has {
t.Fatal("a switch back to the sign-in left the setup-token in settings.json")
}
if _, err := os.Stat(claudeTokenRecordPath()); !os.IsNotExist(err) {
t.Fatalf("the record stayed: %v", err)
}
if b, _ := os.ReadFile(claudeSettingsFile()); gjson.GetBytes(b, "env.FOO").String() != "bar" {
t.Fatalf("the user's env was lost: %s", b)
}
if l := claudeLoginOf(t, tok); l.Uses {
t.Fatal("still listed as used")
}
// to another signed-in account: that one's sign-in, and the token goes
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", team); err != nil {
t.Fatal(err)
}
if _, has := envTokenOf(t); has {
t.Fatal("a switch to another account left the setup-token in settings.json")
}
if l := claudeLoginOf(t, team); !l.Active {
t.Fatalf("%s listed as %+v, want Active", team, l)
}
}
// A CLAUDE_CODE_OAUTH_TOKEN the user set in settings.json themselves is
// theirs: magpie writes none over it, and takes it out on no switch.
func TestClaudeOwnEnvTokenLeftAlone(t *testing.T) {
claudeThree(t)
team := "team@x.com · Acme"
writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: "sk-ant-oat01-users-own"}})
tok, err := AddClaudeSetupToken(testSetupToken)
if err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", tok); err == nil || !strings.Contains(err.Error(), "of your own") {
t.Fatalf("switch over the user's own token: %v", err)
}
if err := SwitchLogin("claude", team); err != nil {
t.Fatal(err)
}
if v, _ := envTokenOf(t); v != "sk-ant-oat01-users-own" {
t.Fatalf("the user's own token became %q", v)
}
if claudeLoginOf(t, tok).Uses {
t.Fatal("the user's own token was taken for magpie's")
}
// magpie's, then changed by the user: theirs from then on
writeFile(t, claudeSettingsFile(), map[string]any{})
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: "sk-ant-oat01-users-later"}})
if err := SwitchLogin("claude", "max@x.com"); err != nil {
t.Fatal(err)
}
if v, _ := envTokenOf(t); v != "sk-ant-oat01-users-later" {
t.Fatalf("the user's later token became %q", v)
}
}
// A settings.json that can't be read holds what it holds: no token is
// written into it, and the record of magpie's stays until it can be read.
func TestClaudeEnvTokenUnreadableSettings(t *testing.T) {
claudeThree(t)
tok, err := AddClaudeSetupToken(testSetupToken)
if err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
broken := []byte(`{"env": {"` + claudeTokenEnvKey + `": "` + testSetupToken + `",`)
if err := os.WriteFile(claudeSettingsFile(), broken, 0o600); err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", "team@x.com · Acme"); err == nil {
t.Fatal("a switch past an unreadable settings.json said it took the token out")
}
if b, _ := os.ReadFile(claudeSettingsFile()); string(b) != string(broken) {
t.Fatalf("an unreadable settings.json was written: %s", b)
}
if claudeLoginOf(t, "team@x.com · Acme").Active {
t.Fatal("Claude Code's sign-in was switched under a token that couldn't be taken out")
}
if _, err := os.Stat(claudeTokenRecordPath()); err != nil {
t.Fatalf("the record went with the token still there: %v", err)
}
// readable again: the token goes on the next switch
writeFile(t, claudeSettingsFile(), map[string]any{"env": map[string]any{claudeTokenEnvKey: testSetupToken}})
if err := SwitchLogin("claude", "team@x.com · Acme"); err != nil {
t.Fatal(err)
}
if _, has := envTokenOf(t); has {
t.Fatal("the token stayed")
}
}
// Removing the setup-token Claude Code uses takes it out of settings.json:
// Claude Code is on its own sign-in again.
func TestClaudeSetupTokenRemovedLeavesSettings(t *testing.T) {
claudeThree(t)
tok, err := AddClaudeSetupToken(testSetupToken)
if err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
if err := ForgetLogin("claude", tok); err != nil {
t.Fatal(err)
}
if _, has := envTokenOf(t); has {
t.Fatal("a removed account's token stayed in settings.json")
}
if _, err := os.Stat(claudeTokenRecordPath()); !os.IsNotExist(err) {
t.Fatalf("the record stayed: %v", err)
}
}
// Claude Code on a setup-token the user picked is left there by magpie's
// own switching (Switch accounts only), whose allowance it can't read:
// the spent sign-in under it is no reason to move.
func TestClaudeSetupTokenInUseNotMovedOff(t *testing.T) {
claudeThree(t) // pro@x.com signed in; team and max saved
var text atomic.Value
text.Store("Current session: 100% used")
fakeClaudeUsage(t, &text, nil)
forget := func() {
lastQuotas.Lock()
lastQuotas.m, lastQuotas.loaded = nil, false
lastQuotas.Unlock()
loginUsageCache.Lock()
loginUsageCache.m = nil
loginUsageCache.Unlock()
}
forget()
t.Cleanup(forget)
if err := SetSwitchOnly("claude", true); err != nil {
t.Fatal(err)
}
for _, l := range Logins("claude") {
if !l.Active {
if err := SetLoginOn("claude", l.User, true); err != nil {
t.Fatal(err)
}
}
}
UsageClaudeVia(func(_ context.Context, dir string) (string, error) {
if dir == "" {
return "Current session: 100% used", nil
}
return "Current session: 10% used", nil
})
tok, err := AddClaudeSetupToken(testSetupToken)
if err != nil {
t.Fatal(err)
}
if err := SwitchLogin("claude", tok); err != nil {
t.Fatal(err)
}
forget()
if _, to, _, ok := NextLogin(context.Background(), "claude"); ok || to != "" {
t.Fatalf("NextLogin moved Claude Code off the setup-token to %q", to)
}
if v, _ := envTokenOf(t); v != testSetupToken {
t.Fatalf("settings.json's token became %q", v)
}
// back on its sign-in, magpie moves it as before
if err := SwitchLogin("claude", "pro@x.com"); err != nil {
t.Fatal(err)
}
forget()
if _, to, _, ok := NextLogin(context.Background(), "claude"); !ok || to == "" {
t.Fatalf("NextLogin no longer moves the spent sign-in: %q ok=%v", to, ok)
}
}
+5
View File
@@ -285,6 +285,11 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
if leftAlone(agent) {
return "", "", false, false // magpie has no say in its sign-in, or was told to leave it be
}
if agent == "claude" && claudeTokenInUse() != "" {
// on a setup-token the user switched it to, whose allowance can't
// be read: it stays there till they switch it again
return "", "", false, false
}
var spares []Login
var first *Login
ls := Logins(agent)
+70 -7
View File
@@ -64,8 +64,13 @@ type Login struct {
// spent, and signs it back in to once it has room again (#408).
Returns bool `json:"returns,omitempty"`
// Token is a Claude account added by a setup-token: magpie's
// requests use it, Claude Code itself can't be signed in to it.
// requests use it, and Claude Code itself only through its
// settings.json (Uses).
Token bool `json:"token,omitempty"`
// Uses is the setup-token account Claude Code itself uses now, its
// token put in its settings.json by magpie (claude_token_env.go). The
// account Claude Code's stored sign-in is (Active) stays as it is.
Uses bool `json:"uses,omitempty"`
// AccessOnly is a ChatGPT account kept access token only
// (codex_access_only.go): magpie never renews its sign-in, nor signs
// Codex in to it.
@@ -1242,6 +1247,10 @@ func loginsNow(agent string) []Login {
active["claude"] = u
}
}
tokenUser := ""
if agent == "" || agent == "claude" {
tokenUser = claudeTokenUserIn(ls, claudeTokenInUse())
}
standIn := ""
if _, ok := active["claude"]; !ok {
// the one the provider is listed on (claudeStandInAccount), a
@@ -1283,6 +1292,7 @@ func loginsNow(agent string) []Login {
if l.Agent == "claude" {
lg.Lapsed = claudeSignedOut(l)
lg.Token = claudeSetupToken(l.Auth) != ""
lg.Uses = lg.Token && strings.EqualFold(tokenUser, l.User)
} else {
// the one in use too, its sign-in revoked (#1793)
lg.Lapsed = revokedLapse(l)
@@ -1508,8 +1518,34 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
// whichever refreshed first would sign the other out
return "", fmt.Errorf("%s is signed in to Codex in %s: run Codex there (CODEX_HOME=%s codex) to use it, or turn it on for magpie's requests", target.User, home, home)
}
if agent == "claude" && claudeSetupToken(target.Auth) != "" {
return "", fmt.Errorf(errClaudeTokenSwitch, target.User)
// the setup-token account Claude Code itself uses now, if magpie has
// it use one (claude_token_env.go): its stored sign-in is then not
// the one it is on
tokenFrom := ""
if agent == "claude" {
tokenFrom = claudeTokenUserIn(ls, claudeTokenInUse())
}
if tok := claudeSetupToken(target.Auth); agent == "claude" && tok != "" {
// no sign-in to put in its store: Claude Code is given the token
// in its settings.json's env, over its stored sign-in, which stays
if why := claudeSignedOut(*target); why != "" {
return "", fmt.Errorf("%s: %s", target.User, why)
}
if strings.EqualFold(tokenFrom, target.User) {
return "", nil
}
from = tokenFrom
if from == "" {
if live, ok := liveLogin(agent); ok {
from = live.User
}
}
if err := setClaudeEnvToken(tok); err != nil {
return "", err
}
loginsSeenAt.Store(0)
forgetAccountCaches()
return from, nil
}
if agent == "codex" && target.AccessOnly {
return "", fmt.Errorf(errCodexAccessOnlySwitch, target.User)
@@ -1551,7 +1587,17 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
}
if live, ok := liveLogin(agent); ok {
if strings.EqualFold(live.User, want.User) {
return "", nil
if tokenFrom == "" {
return "", nil
}
// signed in to it still: the setup-token goes, and Claude
// Code is on its sign-in again
if err := setClaudeEnvToken(""); err != nil {
return "", err
}
loginsSeenAt.Store(0)
forgetAccountCaches()
return tokenFrom, nil
}
from = live.User
// the credentials being replaced, as fresh as the agent has them;
@@ -1574,6 +1620,15 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
// there that couldn't be read
err = saveCodexLogin(codexHome(), want.Auth)
case "claude":
// magpie's setup-token out of its settings.json first, or Claude
// Code would stay on that over the sign-in; one that can't be
// taken out (settings.json unreadable) leaves it where it is
if err = setClaudeEnvToken(""); err != nil {
break
}
if tokenFrom != "" {
from = tokenFrom
}
if err = putClaudeLogin(want); err == nil {
// Claude Code's own now: its only holder
forgetClaudeDir(want.User)
@@ -1726,8 +1781,10 @@ func nextOnForget(agent, user string) string {
return ""
}
// switchable is an account an agent can be signed in to: not a Claude
// setup-token one (errClaudeTokenSwitch), nor a ChatGPT account Codex
// switchable is an account magpie signs an agent in to by itself: not a
// Claude setup-token one, which Claude Code is switched to by the user
// alone (claude_token_env.go: its allowance can't be read, so magpie
// can't tell when to move off or back), nor a ChatGPT account Codex
// keeps in another folder (codexHeldIn).
func switchable(l Login) bool { return !l.Token && !l.AccessOnly && l.home == "" }
@@ -1780,9 +1837,10 @@ func forgetLogin(agent, user string) (signedOut bool, err error) {
}
out := ls[:0]
found := false
var gone savedLogin
for _, l := range ls {
if l.Agent == agent && strings.EqualFold(l.User, user) {
found = true
found, gone = true, l
continue
}
out = append(out, l)
@@ -1794,6 +1852,11 @@ func forgetLogin(agent, user string) (signedOut bool, err error) {
return false, fmt.Errorf("no saved %s account %q", agent, user)
}
if agent == "claude" {
// a setup-token Claude Code uses: taken out of its settings.json,
// and Claude Code is on its own sign-in again
if err := claudeTokenGone(gone); err != nil {
return false, fmt.Errorf("removing %s, which Claude Code uses: %w", user, err)
}
forgetClaudeDir(user)
}
return signedOut, writeLogins(out)