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.
174 lines
6.2 KiB
Go
174 lines
6.2 KiB
Go
package provider
|
|
|
|
// A Claude account added by a setup-token: the long-lived token `claude
|
|
// setup-token` prints, which Claude Code takes in CLAUDE_CODE_OAUTH_TOKEN.
|
|
// magpie keeps it in logins.json as it keeps a sign-in, and hands it to the
|
|
// real Claude Code, in that variable, for runs in the account's own config
|
|
// directory only (ClaudeDirToken); it never asks Anthropic anything with it.
|
|
//
|
|
// What such a token can't do: it has the inference scope only, so Claude
|
|
// Code tells no email, plan or organization for it (`auth status` says
|
|
// "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. 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"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// claudeTokenAuth is a setup-token as savedLogin.Auth keeps it.
|
|
type claudeTokenAuth struct {
|
|
SetupToken string `json:"setupToken"`
|
|
}
|
|
|
|
// claudeSetupToken is the setup-token a saved Claude login's Auth holds, ""
|
|
// for a sign-in.
|
|
func claudeSetupToken(auth []byte) string {
|
|
if len(auth) == 0 {
|
|
return ""
|
|
}
|
|
var a claudeTokenAuth
|
|
if json.Unmarshal(auth, &a) != nil {
|
|
return ""
|
|
}
|
|
return a.SetupToken
|
|
}
|
|
|
|
// claudeTokenVersion is the credential version of a setup-token
|
|
// (claudeLoginVersion): its hash, never the token.
|
|
func claudeTokenVersion(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return "setup-token:" + hex.EncodeToString(sum[:])[:16]
|
|
}
|
|
|
|
// claudeTokenName is the name a setup-token account gets: Claude tells no
|
|
// email for it, so a short hash of the token tells two apart without
|
|
// showing any of it.
|
|
func claudeTokenName(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return "Claude setup-token " + hex.EncodeToString(sum[:])[:6]
|
|
}
|
|
|
|
// errClaudeSetupToken is a setup-token account's allowance: unknown, never
|
|
// 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 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) {
|
|
token = strings.TrimSpace(token)
|
|
token = strings.TrimPrefix(token, "CLAUDE_CODE_OAUTH_TOKEN=")
|
|
token = strings.Trim(token, `"'`)
|
|
switch {
|
|
case token == "":
|
|
return "", errors.New("paste the token `claude setup-token` printed")
|
|
case strings.HasPrefix(token, "sk-ant-api"):
|
|
return "", errors.New("this is an Anthropic API key, not a setup-token: add it as an API key provider instead")
|
|
case !strings.HasPrefix(token, "sk-ant-oat"):
|
|
return "", errors.New("this isn't a setup-token: `claude setup-token` prints one that starts with sk-ant-oat")
|
|
case len(token) > 512 || strings.IndexFunc(token, func(r rune) bool { return unicode.IsSpace(r) || r > unicode.MaxASCII }) >= 0:
|
|
return "", errors.New("this isn't a setup-token: it has spaces or other characters a token doesn't")
|
|
}
|
|
return token, nil
|
|
}
|
|
|
|
// AddClaudeSetupToken adds a Claude account from a setup-token, served by
|
|
// Claude Code with the token in CLAUDE_CODE_OAUTH_TOKEN. Claude Code's own
|
|
// sign-in is left as it is. It answers the account's name; a token already
|
|
// saved answers the account that has it.
|
|
func AddClaudeSetupToken(token string) (string, error) {
|
|
if settings.AccountDiscoveryOff() {
|
|
return "", errAccountDiscoveryOff
|
|
}
|
|
token, err := checkClaudeSetupToken(token)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
loginsMu.Lock()
|
|
for _, l := range readLogins() {
|
|
if l.Agent == "claude" && claudeSetupToken(l.Auth) == token {
|
|
loginsMu.Unlock()
|
|
return l.User, nil
|
|
}
|
|
}
|
|
loginsMu.Unlock()
|
|
auth, err := json.Marshal(claudeTokenAuth{SetupToken: token})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
l := savedLogin{Agent: "claude", User: claudeTokenName(token), Auth: auth}
|
|
if _, err := addLogin(l); err != nil {
|
|
return "", err
|
|
}
|
|
return l.User, nil
|
|
}
|
|
|
|
// ClaudeDirToken is the setup-token of the saved Claude account whose
|
|
// config directory is dir (claudeAccountDir), "" when it has a sign-in of
|
|
// its own or is no saved account's. A run there is given it, and no other.
|
|
func ClaudeDirToken(dir string) string {
|
|
if dir == "" {
|
|
return ""
|
|
}
|
|
dir = filepath.Clean(dir)
|
|
loginsMu.Lock()
|
|
defer loginsMu.Unlock()
|
|
for _, l := range readLogins() {
|
|
if l.Agent != "claude" {
|
|
continue
|
|
}
|
|
if tok := claudeSetupToken(l.Auth); tok != "" && filepath.Clean(claudeAccountDir(l.User)) == dir {
|
|
return tok
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// claudeTokenAccount says the saved Claude account user was added by a
|
|
// setup-token.
|
|
func claudeTokenAccount(user string) bool {
|
|
loginsMu.Lock()
|
|
defer loginsMu.Unlock()
|
|
for _, l := range readLogins() {
|
|
if l.Agent == "claude" && strings.EqualFold(l.User, user) {
|
|
return claudeSetupToken(l.Auth) != ""
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// claudeTokenDir makes the config directory a setup-token account runs
|
|
// in: no sign-in in it (on a refused token Claude Code would otherwise
|
|
// take one it found there; addLogin cleared the directory's keychain item
|
|
// with it, forgetClaudeDir), only the onboarding Claude Code asks for
|
|
// before its first run.
|
|
func claudeTokenDir(user string) (string, error) {
|
|
dir := claudeAccountDir(user)
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
if err := os.Remove(filepath.Join(dir, ".credentials.json")); err != nil && !os.IsNotExist(err) {
|
|
return "", fmt.Errorf("a sign-in left in %s: %w", dir, err)
|
|
}
|
|
claudeOnboarded(dir, nil)
|
|
return dir, nil
|
|
}
|