claude: add an account from a setup-token (CLAUDE_CODE_OAUTH_TOKEN)
sfss5362 on X asked "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". It didn't work
before: cleanClaudeEnv strips the variable everywhere, and the import
flow needs a refresh token and an email.
A Claude account can now be added from the token `claude setup-token`
prints. In the window: the sign-in's "Use a setup-token instead…" and
the accounts list's "Add an account by setup-token…", which post to
POST /api/signin/claude-token.
The token is kept in logins.json as {"setupToken":…}. The real Claude
Code gets it in CLAUDE_CODE_OAUTH_TOKEN, and only for runs in that
account's own config directory (inClaudeDir via
provider.ClaudeDirToken). It never goes on the command line or into a
log. magpie never asks Anthropic anything with it. The bridge, the
sdk-cli entrypoint and the weighting are unchanged.
What such a token can't do: it has the inference scope only.
- Claude Code's `auth status` gives no email or plan. The account is
named "Claude setup-token <6 hex of its hash>".
- Its /usage prints the API cost view. /usage is never run for it, so
its allowance is unknown (errClaudeSetupToken, which `passing` keeps
as saying nothing about the account), not zero. Windows heard on
real replies still fill it in.
- Its config directory holds no .credentials.json, so Claude Code has
no sign-in to fall back to if the token is refused.
- Claude Code itself is never signed in to it. addLogin, switchLogin,
putClaudeLogin, SetKeepLoginAs, NextLogin and signInToFirst all pass
it over. Its row shows Remove and "magpie only", and the switch menu
leaves it out.
New strings are in zh, zh-TW, ja and de. Docs: providers-accounts.md
and claude-subscription-bridge.md.
Run:
- mote: gofmt -l (clean); go vet ./internal/...; GOOS=linux go vet
-tags nogui and GOOS=windows go vet of provider, gateway and gui; go
build ./...
- mote: go test of provider and gateway, -run on SetupToken, Claude
usage, warm-up, saved, account, logins, switch and keep-login: ok.
- New tests, with a fake claude binary in a sandbox HOME:
- TestClaudeSetupTokenAccount, TestClaudeSetupTokenSignsClaudeCodeInToNothing,
TestClaudeSetupTokenAllowanceUnknown and TestCheckClaudeSetupToken
in provider;
- TestClaudeSetupTokenReachesItsOwnRunsOnly in gateway: the token
reaches only its account's run, not "" or another dir, even with
the shell's CLAUDE_CODE_OAUTH_TOKEN=leaked, and never in args;
- claude-setup-token.test.cjs: Chromium on mote and WebKit on
xiaomi-gpu, each in en, zh, zh-TW, ja and de.
- GUI files the change reaches (signin-link, signin-web-blocked,
signin-closes-sheet, revoked-signin-account, account-eye,
account-row-line, i18n-keys and the new one): 73/73 on xiaomi-gpu
Chromium.
- On mote, 33 account, sign-in and i18n files had 96 reds. mote was
overloaded by another session's full GUI suite. Six of those files
fail 58 of 64 the same way at origin/main dafe4af82 there, and pass
on xiaomi-gpu. WebKit on mote timed out on the untouched
copilot-ghe.test.cjs too.
Size: app.js was 2,885 bytes over its budget after the rebase. The
new comments were cut, and the budgets were raised to the measured sizes
(app.js 1,317,705, core 1,539,423) with no room added, as
core_budget_test.go says. After the rebase onto origin/main 969868ccd,
these were run on mote at this head: TestCoreScriptBudget and the
SetupToken tests ok, and claude-setup-token plus i18n-keys in Chromium
9/9.
Broken by hand (each went red):
- without the token line in inClaudeDir, the gateway test;
- with addLogin allowed to sign Claude Code in, two provider tests;
- with /usage run for a token account, AllowanceUnknown ("told no
allowance").
- With switchLogin's guard removed, the tests stay green, because
putClaudeLogin still refuses.
Not tried: a real setup-token against Anthropic. The full Go and GUI
suites will be run after the push.
This commit is contained in:
@@ -53,6 +53,8 @@ to use an http:// proxy. The `settings.json` env that magpie writes for the
|
||||
user's own Claude Code sessions leaves a SOCKS proxy out (see
|
||||
[Providers and accounts](providers-accounts.md)).
|
||||
|
||||
A saved account added by a setup-token (see [Providers and accounts](providers-accounts.md)) has no sign-in in its config directory. `inClaudeDir`, which builds the env of every run in a saved account's directory (a turn's run, the warm-up, `askClaude`, `/usage`), drops any `CLAUDE_CODE_OAUTH_TOKEN` it was given and sets it to `provider.ClaudeDirToken(configDir)` when that directory is a token account's: the token reaches the real Claude Code there and nowhere else, never on its command line, never in a log, and never to Claude Code's own account. magpie asks Anthropic nothing with it; the entrypoint and everything else about the run are as for any account.
|
||||
|
||||
The helper offers each of the client's tools under `bridgeToolName`
|
||||
(`bridgeTools`), which Claude Code calls `mcp__magpie__<name>`. Claude Code
|
||||
keeps only `[A-Za-z0-9_-]` of an MCP tool's name, so a name it would change
|
||||
|
||||
@@ -47,6 +47,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say "<user> is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) |
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
|
||||
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
|
||||
| Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) |
|
||||
| Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. Not in the tray panel (it reads no provider list), not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) |
|
||||
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
|
||||
| Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) |
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
const gwSetupToken = "sk-ant-oat01-gatewaysetuptoken-0123456789abcdefghijklmnop"
|
||||
|
||||
// A Claude account added by a setup-token (sfss5362 on X) is served by the
|
||||
// real Claude Code, given the token in CLAUDE_CODE_OAUTH_TOKEN for runs in
|
||||
// that account's own config directory and no other: never on the command
|
||||
// line, never to Claude Code's own account or another saved one, and never
|
||||
// the token the shell happens to hold.
|
||||
func TestClaudeSetupTokenReachesItsOwnRunsOnly(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for Claude Code")
|
||||
}
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||
provider.ForgetAccounts()
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
|
||||
user, err := provider.AddClaudeSetupToken(gwSetupToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.ForgetAccounts()
|
||||
// the directory the gateway is handed for the account, as a turn is
|
||||
var dir string
|
||||
for _, p := range provider.All() {
|
||||
if p.Account != nil && p.Account.Agent == "claude" && p.Account.User == user {
|
||||
d, _, err := p.Account.Token(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir = d
|
||||
}
|
||||
}
|
||||
if dir == "" {
|
||||
t.Fatalf("no provider serves %q", user)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".credentials.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("a sign-in sits in the token account's directory: %v", err)
|
||||
}
|
||||
|
||||
bin := t.TempDir()
|
||||
log := filepath.Join(bin, "log")
|
||||
text := "Current session: 13% used · resets Oct 1 at 3:30pm (UTC)\n"
|
||||
b, _ := json.Marshal(map[string]any{"type": "result", "is_error": false, "num_turns": 0, "result": text})
|
||||
os.WriteFile(filepath.Join(bin, "out"), b, 0o644)
|
||||
script := "#!/bin/sh\n" +
|
||||
"{ printf 'args:'; for a in \"$@\"; do printf '[%s]' \"$a\"; done; echo; echo \"dir:$CLAUDE_CONFIG_DIR\"; echo \"token:$CLAUDE_CODE_OAUTH_TOKEN\"; } >> " + log + "\n" +
|
||||
"cat " + filepath.Join(bin, "out") + "\n"
|
||||
testenv.Program(t, filepath.Join(bin, "claude"), script)
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "leaked")
|
||||
|
||||
run := func(configDir string) string {
|
||||
t.Helper()
|
||||
os.Remove(log)
|
||||
if _, err := claudeUsage(context.Background(), configDir); err != nil {
|
||||
t.Fatalf("%q: %v", configDir, err)
|
||||
}
|
||||
got, _ := os.ReadFile(log)
|
||||
return string(got)
|
||||
}
|
||||
if got := run(dir); !strings.Contains(got, "token:"+gwSetupToken+"\n") || !strings.Contains(got, "dir:"+dir+"\n") {
|
||||
t.Fatalf("the token account's run wasn't given its token:\n%s", got)
|
||||
} else if args, _, _ := strings.Cut(got, "\n"); strings.Contains(args, gwSetupToken) {
|
||||
t.Fatalf("the token went on the command line: %s", args)
|
||||
}
|
||||
for _, other := range []string{"", filepath.Join(filepath.Dir(dir), "0123456789abcdef")} {
|
||||
if got := run(other); !strings.Contains(got, "token:\n") {
|
||||
t.Fatalf("a run in %q was given a token:\n%s", other, got)
|
||||
}
|
||||
}
|
||||
|
||||
// the bridge's env is built the same way
|
||||
env := inClaudeDir([]string{"CLAUDE_CODE_OAUTH_TOKEN=leaked", "PATH=/bin"}, dir)
|
||||
n := 0
|
||||
for _, e := range env {
|
||||
if strings.HasPrefix(e, "CLAUDE_CODE_OAUTH_TOKEN=") {
|
||||
n++
|
||||
if e != "CLAUDE_CODE_OAUTH_TOKEN="+gwSetupToken {
|
||||
t.Fatalf("bridge env %q", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("%d tokens in the bridge's env: %q", n, env)
|
||||
}
|
||||
}
|
||||
@@ -593,6 +593,9 @@ func (c claudeCLI) env(env []string, configDir string) []string {
|
||||
if configDir != "" {
|
||||
names = append(slices.Clone(names), "CLAUDE_CONFIG_DIR/p")
|
||||
}
|
||||
if slices.ContainsFunc(env, func(e string) bool { return strings.HasPrefix(e, "CLAUDE_CODE_OAUTH_TOKEN=") }) {
|
||||
names = append(slices.Clone(names), "CLAUDE_CODE_OAUTH_TOKEN")
|
||||
}
|
||||
if c.wsl.Root {
|
||||
// asRoot's, for a distro whose user is root
|
||||
names = append(slices.Clone(names), "IS_SANDBOX")
|
||||
@@ -2060,15 +2063,22 @@ func inClaudeDir(env []string, configDir string) []string {
|
||||
if configDir == "" {
|
||||
return env
|
||||
}
|
||||
out := make([]string, 0, len(env)+1)
|
||||
out := make([]string, 0, len(env)+2)
|
||||
for _, e := range env {
|
||||
switch k, _, _ := strings.Cut(e, "="); k {
|
||||
case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR":
|
||||
case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", "CLAUDE_CODE_OAUTH_TOKEN":
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return append(out, "CLAUDE_CONFIG_DIR="+configDir)
|
||||
out = append(out, "CLAUDE_CONFIG_DIR="+configDir)
|
||||
// an account added by a setup-token: Claude Code takes the token as
|
||||
// `claude setup-token` says to, in its environment, for this account's
|
||||
// directory alone; never on the command line, nor logged
|
||||
if tok := provider.ClaudeDirToken(configDir); tok != "" {
|
||||
out = append(out, "CLAUDE_CODE_OAUTH_TOKEN="+tok)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cleanClaudeEnv(env []string) []string {
|
||||
|
||||
@@ -1614,7 +1614,7 @@ function switchEntry(a) {
|
||||
setTimeout(() => b.classList.remove("done"), 5000 - ago);
|
||||
}
|
||||
b.append(svg(CHEV, 10, 1.6));
|
||||
const opts = ls.map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: l.lapsed ? "Sign-in required" : accountPlan({ agent: a.id, plan: l.plan }) }));
|
||||
const opts = ls.filter((l) => !l.token).map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: l.lapsed ? "Sign-in required" : accountPlan({ agent: a.id, plan: l.plan }) }));
|
||||
const on = cx ? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag) : t("magpie serves no requests on these accounts");
|
||||
// the Only switch setting, where the accounts page offers it
|
||||
if (!cx || ls.filter((l) => !l.lapsed && (l.active || l.on)).length > 1) opts.push({ v: "only", name: t("Only switch {agent}'s sign-in", ag), literalName: true, ticked: !!p.switchOnly, note: on });
|
||||
@@ -12444,6 +12444,7 @@ async function signedIn(st) {
|
||||
if (!p) status(t("{user} signed in, but magpie can't list it — please report this", { user: who }), "err");
|
||||
// an account listed already is said to be, not added (#413)
|
||||
else if (st.again) status(t("{user} is already listed — its sign-in was renewed", { user: who }), "ok");
|
||||
else if (st.token) status(t("{user} added; requests through magpie use it beside your other accounts", { user: who }), "ok");
|
||||
else status(st.using ? t("Signed in as {user}", { user: who }) : t("{user} added — switch to it any time", { user: who }), "ok");
|
||||
state = await api("state");
|
||||
renderAgents();
|
||||
@@ -12819,6 +12820,57 @@ function renderCopilotGHE(sub) {
|
||||
return box;
|
||||
}
|
||||
|
||||
// a Claude account from a setup-token (claude_setup_token.go)
|
||||
function startClaudeToken() {
|
||||
stopSignIn();
|
||||
signing = { agent: "claude", state: "token", token: "" };
|
||||
renderProviders();
|
||||
}
|
||||
|
||||
function renderClaudeToken(sub) {
|
||||
const box = el("div", "signing claude-token");
|
||||
const tt = el("span", "tt");
|
||||
box.append(tt);
|
||||
const flow = signing;
|
||||
const label = t("Add a Claude account by setup-token");
|
||||
tt.append(el("span", "n", label),
|
||||
el("span", "s", t("Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.", { cmd: "claude setup-token" })),
|
||||
el("span", "s", t("A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.")));
|
||||
const form = el("form", "callback-form");
|
||||
const inp = input(flow.token || "", "sk-ant-oat01-…", "password");
|
||||
inp.setAttribute("aria-label", label);
|
||||
const go = el("button", "text primary", t("Add"));
|
||||
go.type = "submit";
|
||||
go.disabled = !inp.value.trim() || !!flow.busy;
|
||||
const why = el("span", "s why", flow.error || "");
|
||||
inp.oninput = () => { flow.token = inp.value; go.disabled = !inp.value.trim(); why.textContent = ""; };
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
if (signing !== flow || flow.busy || !inp.value.trim()) return;
|
||||
flow.busy = true;
|
||||
go.disabled = true;
|
||||
try {
|
||||
const r = await api("signin/claude-token", { token: inp.value });
|
||||
if (signing !== flow) return;
|
||||
await signedIn({ agent: "claude", user: r.user, token: true });
|
||||
} catch (err) {
|
||||
if (signing !== flow) return;
|
||||
flow.busy = false;
|
||||
flow.error = err.message;
|
||||
renderProviders();
|
||||
}
|
||||
};
|
||||
form.onsubmit = submit;
|
||||
go.onclick = submit;
|
||||
form.append(inp, go);
|
||||
tt.append(form, why);
|
||||
const close = el("button", "text", t("Cancel"));
|
||||
close.onclick = cancelSignIn;
|
||||
box.append(close);
|
||||
setTimeout(() => { if (inp.isConnected) inp.focus({ preventScroll: true }); });
|
||||
return box;
|
||||
}
|
||||
|
||||
// dropSigningIn: the editor of provider id closing (Cancel, Save, Remove)
|
||||
// leaves no sign-in of its account waiting behind it, to come back with the
|
||||
// editor (#526: 无论我点击底部的移除、取消、保存都没办法); an import being
|
||||
@@ -12894,6 +12946,7 @@ function renderSigning(sub) {
|
||||
return box;
|
||||
}
|
||||
if (signing.state === "ghe") return renderCopilotGHE(sub);
|
||||
if (signing.state === "token") return renderClaudeToken(sub);
|
||||
if (signing.state === "import" || signing.state === "importing" || signing.state === "imported") return renderLoginImport(sub);
|
||||
if (signing.state === "method" || signing.state === "prompt" || signing.state === "key") return renderPluginAsk(sub);
|
||||
if (signing.state === "failed") {
|
||||
@@ -13067,6 +13120,12 @@ function renderSigning(sub) {
|
||||
const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts"));
|
||||
acts.append(imp);
|
||||
}
|
||||
if (sub.agent === "claude") {
|
||||
const tok = el("button", "link", t("Use a setup-token instead…"));
|
||||
tok.onclick = () => startClaudeToken();
|
||||
const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts"));
|
||||
acts.append(tok);
|
||||
}
|
||||
// the one way to put it away (#526): a Close beside Open again did what
|
||||
// this does, two buttons for one thing
|
||||
const x = el("button", "text", t("Cancel"));
|
||||
@@ -13273,7 +13332,7 @@ function renderAccounts(a, p) {
|
||||
row.classList.add("signed-out");
|
||||
line.append(el("span", "using", t("Sign-in required")));
|
||||
const again = el("button", "text", t("Sign in again"));
|
||||
again.onclick = () => startSignIn(a.agent, false, undefined, { user: l.user });
|
||||
again.onclick = () => l.token ? startClaudeToken() : startSignIn(a.agent, false, undefined, { user: l.user });
|
||||
line.append(again);
|
||||
// the one Claude Code is signed in to can't be forgotten (ForgetLogin)
|
||||
if (!l.active) {
|
||||
@@ -13322,6 +13381,10 @@ 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) {
|
||||
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);
|
||||
} else {
|
||||
const use = el("button", "text", on ? t("Make first") : t("Use"));
|
||||
use.title = sub?.own ? t("The gateway uses this account first") : t("Sign {agent} in to this account", { agent: a.agentName });
|
||||
@@ -13426,6 +13489,7 @@ function renderAccounts(a, p) {
|
||||
imp.title = importSay(a.agent).from;
|
||||
list.append(imp);
|
||||
}
|
||||
if (a.agent === "claude") list.append(addRow(t("Add an account by setup-token…"), startClaudeToken));
|
||||
}
|
||||
arrangeAccountRows(list, p);
|
||||
return list;
|
||||
|
||||
@@ -1881,6 +1881,14 @@ const I18N = {
|
||||
"Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "逐个查询 Key 所属的账号,与 Droid 处理 FACTORY_API_KEY 时相同。",
|
||||
"Use an API key instead…": "改用 API Key…",
|
||||
"Add an account by API key…": "用 API Key 添加账号…",
|
||||
"Use a setup-token instead…": "改用 setup-token…",
|
||||
"Add a Claude account by setup-token": "用 setup-token 添加 Claude 账号",
|
||||
"Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "粘贴 {cmd} 输出的 token。magpie 只在这个账号的请求里把它交给 Claude Code;Claude Code 本身的登录保持不变。",
|
||||
"A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token 读不到邮箱和用量:账号以 token 命名,用量要等某次回复带回后才显示。",
|
||||
"{user} added; requests through magpie use it beside your other accounts": "已添加 {user};经 magpie 的请求会和你的其他账号一起使用它",
|
||||
"Add an account by setup-token…": "用 setup-token 添加账号…",
|
||||
"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 本身无法登录到这个账号",
|
||||
"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} 账号",
|
||||
@@ -6032,6 +6040,14 @@ const I18N = {
|
||||
"Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "逐個查詢 Key 所屬的帳號,與 Droid 處理 FACTORY_API_KEY 時相同。",
|
||||
"Use an API key instead…": "改用 API Key…",
|
||||
"Add an account by API key…": "用 API Key 新增帳號…",
|
||||
"Use a setup-token instead…": "改用 setup-token…",
|
||||
"Add a Claude account by setup-token": "用 setup-token 新增 Claude 帳號",
|
||||
"Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "貼上 {cmd} 輸出的 token。magpie 只在這個帳號的請求裡把它交給 Claude Code;Claude Code 本身的登入保持不變。",
|
||||
"A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token 讀不到電子郵件和用量:帳號以 token 命名,用量要等某次回覆帶回後才顯示。",
|
||||
"{user} added; requests through magpie use it beside your other accounts": "已新增 {user};經 magpie 的請求會和你的其他帳號一起使用它",
|
||||
"Add an account by setup-token…": "用 setup-token 新增帳號…",
|
||||
"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 本身無法登入到這個帳號",
|
||||
"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} 帳號",
|
||||
@@ -10160,6 +10176,14 @@ const I18N = {
|
||||
"Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "Droid が FACTORY_API_KEY で行うように、各キーの所有アカウントを問い合わせます。",
|
||||
"Use an API key instead…": "代わりに APIキーを使う…",
|
||||
"Add an account by API key…": "APIキーでアカウントを追加…",
|
||||
"Use a setup-token instead…": "代わりに setup-token を使う…",
|
||||
"Add a Claude account by setup-token": "setup-token で Claude アカウントを追加",
|
||||
"Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "{cmd} が表示したトークンを貼り付けてください。magpie はこのアカウントのリクエストに限って Claude Code に渡します。Claude Code 自体のサインインはそのままです。",
|
||||
"A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token ではメールアドレスと使用量を読めません。アカウントはトークンから名付けられ、使用量は応答で伝えられてから表示されます。",
|
||||
"{user} added; requests through magpie use it beside your other accounts": "{user} を追加しました。magpie 経由のリクエストはほかのアカウントと並べてこれを使います",
|
||||
"Add an account by setup-token…": "setup-token でアカウントを追加…",
|
||||
"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 自体をこのアカウントにサインインさせることはできません",
|
||||
"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} アカウントをインポート",
|
||||
@@ -14318,6 +14342,14 @@ const I18N = {
|
||||
"Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "Für jeden Schlüssel wird abgefragt, zu welchem Konto er gehört, so wie Droid es mit FACTORY_API_KEY macht.",
|
||||
"Use an API key instead…": "Stattdessen API-Schlüssel verwenden…",
|
||||
"Add an account by API key…": "Konto per API-Schlüssel hinzufügen…",
|
||||
"Use a setup-token instead…": "Stattdessen ein setup-token verwenden…",
|
||||
"Add a Claude account by setup-token": "Claude-Konto per setup-token hinzufügen",
|
||||
"Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "Füge das Token ein, das {cmd} ausgegeben hat. magpie gibt es Claude Code nur für die Anfragen dieses Kontos; Claude Code selbst bleibt angemeldet, wie es ist.",
|
||||
"A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "Ein setup-token verrät weder E-Mail noch Kontingent: Das Konto wird nach dem Token benannt, und sein Kontingent erscheint, sobald eine Antwort es nennt.",
|
||||
"{user} added; requests through magpie use it beside your other accounts": "{user} hinzugefügt; Anfragen über magpie nutzen es neben deinen anderen Konten",
|
||||
"Add an account by setup-token…": "Konto per setup-token hinzufügen…",
|
||||
"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",
|
||||
"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
@@ -2319,6 +2319,22 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
// A Claude account from a setup-token (`claude setup-token`), which
|
||||
// Claude Code takes in CLAUDE_CODE_OAUTH_TOKEN: nothing is asked of
|
||||
// Anthropic, and the token is never echoed back.
|
||||
mux.HandleFunc("POST /api/signin/claude-token", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Token string }
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 16<<10)).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
user, err := provider.AddClaudeSetupToken(in.Token)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]string{"user": user})
|
||||
})
|
||||
// Accounts brought in from another tool's export (Antigravity's, from
|
||||
// Antigravity Cockpit, Antigravity Manager, CLIProxyAPI; ChatGPT's and
|
||||
// Claude's from CLIProxyAPI or the agents' own files), each file's
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// sfss5362 on X: "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". Claude's sign-in offers
|
||||
// "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.
|
||||
// Chromium and WebKit, English, Chinese (both), Japanese and German, at
|
||||
// 420px; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const playwright = require("playwright");
|
||||
|
||||
const engines = (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]);
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const TOKEN = "sk-ant-oat01-guitoken-0123456789";
|
||||
|
||||
for (const engine of engines) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
test(`claude setup-token account (${engine}, ${lang})`, async (t) => {
|
||||
const browser = await playwright[engine].launch();
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width: 420, height: 720 } });
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const tokens = [];
|
||||
const canceled = [];
|
||||
await page.route("**/*", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data, status) => route.fulfill({ json: data, status: status || 200 });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"dark",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "dark" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/signin/claude-token") {
|
||||
const body = route.request().postDataJSON();
|
||||
tokens.push(body.token);
|
||||
if (body.token.startsWith("sk-ant-api")) return json({ error: "this is an Anthropic API key, not a setup-token: add it as an API key provider instead" }, 400);
|
||||
return json({ user: "Claude setup-token 3204d0" });
|
||||
}
|
||||
if (url.pathname === "/api/signin") return json({ id: "c1", agent: "claude", state: "waiting", url: "https://claude.ai/oauth/authorize?x=1" });
|
||||
if (/^\/api\/signin\/c\d+\/cancel$/.test(url.pathname)) { canceled.push(url.pathname.split("/")[3]); return json({}); }
|
||||
if (/^\/api\/signin\/c\d+$/.test(url.pathname)) return new Promise(() => {}); // stays waiting
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
return route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
});
|
||||
await page.context().route((url) => url.hostname !== "magpie.test", (route) => route.fulfill({ contentType: "text/html", body: "" }));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.waitForFunction((l) => state.settings.lang === l, lang);
|
||||
await page.evaluate(() => {
|
||||
providers = providers || { providers: [], presets: [], plugins: [] };
|
||||
window.signedInWith = [];
|
||||
window.signedIn = async (st) => { window.signedInWith.push(st); signing = null; };
|
||||
window.renderProviders = () => {
|
||||
const host = document.getElementById("csign") || Object.assign(document.createElement("div"), { id: "csign" });
|
||||
host.style.cssText = "position:fixed;inset:0 auto auto 0;width:100%;z-index:1000;";
|
||||
host.replaceChildren(signing ? renderSigning(subOf("claude") || { agent: "claude" }) : "");
|
||||
document.body.append(host);
|
||||
};
|
||||
startSignIn("claude", true);
|
||||
});
|
||||
const box = page.locator("#csign");
|
||||
const said = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]);
|
||||
const translated = async (s, v) => {
|
||||
const got = await said(s, v);
|
||||
if (lang !== "en") assert.notEqual(got, s.replace("{cmd}", "claude setup-token"), `${s} isn't in ${lang}`);
|
||||
return got;
|
||||
};
|
||||
|
||||
// the browser sign-in offers the token
|
||||
await page.waitForFunction(() => signing?.state === "waiting");
|
||||
const offer = box.getByRole("button", { name: await translated("Use a setup-token instead…") });
|
||||
await offer.click();
|
||||
await page.waitForFunction(() => signing?.state === "token");
|
||||
assert.deepEqual(canceled, ["c1"]);
|
||||
const text = await box.innerText();
|
||||
assert.ok(text.includes(await translated("Add a Claude account by setup-token")), text);
|
||||
assert.ok(text.includes(await translated("Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.", { cmd: "claude setup-token" })), text);
|
||||
assert.ok(text.includes(await translated("A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.")), text);
|
||||
const field = box.locator(".claude-token input");
|
||||
const add = box.locator('.claude-token button[type="submit"]');
|
||||
assert.equal(await field.getAttribute("type"), "password");
|
||||
assert.equal(await add.isDisabled(), true);
|
||||
assert.equal(await box.locator("select").count(), 0);
|
||||
// inside the sheet at 420px
|
||||
const w = await box.evaluate((root) => Math.max(...[...root.querySelectorAll("*")].map((e) => e.getBoundingClientRect().right)));
|
||||
assert.ok(w <= 420, `sheet reaches ${w}px`);
|
||||
|
||||
// a refused token says why and stays
|
||||
await field.fill("sk-ant-api03-key");
|
||||
await add.click();
|
||||
await page.waitForFunction(() => document.querySelector("#csign .claude-token .why")?.textContent);
|
||||
assert.match(await box.locator(".why").textContent(), /API key/);
|
||||
assert.equal(await page.evaluate(() => signing?.state), "token");
|
||||
|
||||
// a setup-token is added
|
||||
await box.locator(".claude-token input").fill(TOKEN);
|
||||
await box.locator('.claude-token button[type="submit"]').click();
|
||||
await page.waitForFunction(() => window.signedInWith.length === 1);
|
||||
assert.deepEqual(tokens, ["sk-ant-api03-key", TOKEN]);
|
||||
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 }];
|
||||
const a = { agent: "claude", agentName: "Claude Code", logins: ls };
|
||||
const list = renderAccounts(a, { id: "claude", account: { agent: "claude", user: "pro@x.com" } });
|
||||
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(","));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
@@ -59,6 +59,9 @@ func claudeLoginVersion(l savedLogin) string {
|
||||
if c, ok := parseClaudeCredentials(l.Auth); ok {
|
||||
return c.version()
|
||||
}
|
||||
if tok := claudeSetupToken(l.Auth); tok != "" {
|
||||
return claudeTokenVersion(tok)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -155,6 +155,9 @@ func syncSavedClaude(user string) {
|
||||
ls := readLogins()
|
||||
for i := range ls {
|
||||
if ls[i].Agent == "claude" && strings.EqualFold(ls[i].User, user) {
|
||||
if claudeSetupToken(ls[i].Auth) != "" {
|
||||
return // Claude Code keeps no sign-in of its own there
|
||||
}
|
||||
if _, changed, err := syncClaudeDir(&ls[i]); err == nil && changed {
|
||||
_ = writeLogins(ls)
|
||||
}
|
||||
@@ -168,6 +171,11 @@ func syncSavedClaude(user string) {
|
||||
// the account's own proxy. Claude Code's own sign-in isn't touched.
|
||||
func readSavedClaudeUsage(ctx context.Context, user string) ([]QuotaWindow, error) {
|
||||
ws := []QuotaWindow{}
|
||||
if claudeTokenAccount(user) {
|
||||
// its /usage shows the API cost view, which would read as no
|
||||
// allowance at all: unknown, not run
|
||||
return ws, errClaudeSetupToken
|
||||
}
|
||||
err := inSavedClaudeDir(user, func(dir string) error {
|
||||
var err error
|
||||
ws, err = readClaudeUsage(ViaLogin(ctx, "claude", user), dir)
|
||||
@@ -195,6 +203,14 @@ func claudeSavedDir(user string) (string, error) {
|
||||
if i < 0 {
|
||||
return "", fmt.Errorf("no saved claude account %q", user)
|
||||
}
|
||||
if claudeSetupToken(ls[i].Auth) != "" {
|
||||
// no sign-in to put there: the token goes in Claude Code's
|
||||
// environment (ClaudeDirToken)
|
||||
if why := claudeSignedOut(ls[i]); why != "" {
|
||||
return "", errors.New(why)
|
||||
}
|
||||
return claudeTokenDir(user)
|
||||
}
|
||||
dir := claudeAccountDir(user)
|
||||
has, changed, err := syncClaudeDir(&ls[i])
|
||||
if err != nil {
|
||||
@@ -373,7 +389,7 @@ func claudeSignedOut(l savedLogin) string {
|
||||
}
|
||||
return l.Lapsed
|
||||
}
|
||||
if _, ok := parseClaudeCredentials(l.Auth); ok {
|
||||
if _, ok := parseClaudeCredentials(l.Auth); ok || claudeSetupToken(l.Auth) != "" {
|
||||
return ""
|
||||
}
|
||||
return claudeGoneLapse
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
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. Claude Code itself can't be signed in
|
||||
// to it: there is nothing to put in its keychain or .credentials.json.
|
||||
|
||||
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 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"
|
||||
|
||||
// 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)
|
||||
}
|
||||
profile := filepath.Join(dir, ".claude.json")
|
||||
if _, err := os.Stat(profile); os.IsNotExist(err) {
|
||||
_ = writePrivate(profile, []byte("{\n \"hasCompletedOnboarding\": true\n}\n"))
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testSetupToken = "sk-ant-oat01-setuptoken-abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
|
||||
// sfss5362 on X: "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". A token `claude
|
||||
// setup-token` printed is added as an account of magpie's own: kept in
|
||||
// logins.json, named without an email, given to Claude Code for its own
|
||||
// config directory only, and Claude Code's own sign-in left as it was.
|
||||
func TestClaudeSetupTokenAccount(t *testing.T) {
|
||||
home := claudeHome(t)
|
||||
cred := claudeSignIn(t, home, time.Now().Add(time.Hour))
|
||||
writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "pro@x.com",
|
||||
"organizationUuid": "org-pro", "organizationName": "pro@x.com's Organization"}})
|
||||
forgetAccountCaches()
|
||||
rememberLogins(true)
|
||||
before, err := os.ReadFile(cred)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
user, err := AddClaudeSetupToken(" CLAUDE_CODE_OAUTH_TOKEN=" + testSetupToken + "\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user == "" || strings.Contains(user, "sk-ant") || strings.Contains(user, testSetupToken[len(testSetupToken)-6:]) {
|
||||
t.Fatalf("named %q: no name, or a name showing the token", user)
|
||||
}
|
||||
if after, _ := os.ReadFile(cred); string(after) != string(before) {
|
||||
t.Fatal("adding a setup-token wrote Claude Code's own sign-in")
|
||||
}
|
||||
// kept as a credential is, in logins.json
|
||||
if b, _ := os.ReadFile(loginsPath()); !strings.Contains(string(b), testSetupToken) {
|
||||
t.Fatal("the token isn't kept in logins.json")
|
||||
}
|
||||
var got *Login
|
||||
for _, l := range Logins("claude") {
|
||||
if l.User == user {
|
||||
got = &l
|
||||
}
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("%q isn't listed: %+v", user, Logins("claude"))
|
||||
}
|
||||
if got.Active || !got.On || !got.Token || got.Lapsed != "" {
|
||||
t.Fatalf("setup-token account listed as %+v, want on beside Claude Code's own, not active", *got)
|
||||
}
|
||||
// the same token again is the same account
|
||||
if again, err := AddClaudeSetupToken(testSetupToken); err != nil || again != user {
|
||||
t.Fatalf("the same token again: %q, %v", again, err)
|
||||
}
|
||||
if n := len(Logins("claude")); n != 2 {
|
||||
t.Fatalf("%d Claude accounts, want 2", n)
|
||||
}
|
||||
|
||||
// its directory holds no sign-in, and its token is given there alone
|
||||
dir, err := claudeSavedDir(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir != claudeAccountDir(user) {
|
||||
t.Fatalf("dir %q, want %q", dir, claudeAccountDir(user))
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".credentials.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("a sign-in was put in the setup-token account's directory: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(dir, ".claude.json")); !strings.Contains(string(b), "hasCompletedOnboarding") {
|
||||
t.Fatalf("no onboarding in its .claude.json: %s", b)
|
||||
}
|
||||
if tok := ClaudeDirToken(dir); tok != testSetupToken {
|
||||
t.Fatalf("ClaudeDirToken(own dir) = %q", tok)
|
||||
}
|
||||
if tok := ClaudeDirToken(claudeAccountDir("pro@x.com · pro@x.com's Organization")); tok != "" {
|
||||
t.Fatal("another account's directory was given the token")
|
||||
}
|
||||
if tok := ClaudeDirToken(""); tok != "" {
|
||||
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") {
|
||||
t.Fatalf("switch onto a setup-token account: %v", err)
|
||||
}
|
||||
if after, _ := os.ReadFile(cred); string(after) != string(before) {
|
||||
t.Fatal("a switch wrote the token into Claude Code's own sign-in")
|
||||
}
|
||||
// its version is the token's hash, never the token
|
||||
if v := ClaudeLoginVersion(user); v == "" || strings.Contains(v, testSetupToken) {
|
||||
t.Fatalf("version %q", v)
|
||||
}
|
||||
}
|
||||
|
||||
// With Claude Code signed out, the first account added is signed in to in
|
||||
// Claude Code; a setup-token never is.
|
||||
func TestClaudeSetupTokenSignsClaudeCodeInToNothing(t *testing.T) {
|
||||
home := claudeHome(t)
|
||||
user, err := AddClaudeSetupToken(testSetupToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(home, ".claude", ".credentials.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("Claude Code was signed in to a setup-token: %v", err)
|
||||
}
|
||||
ls := Logins("claude")
|
||||
if len(ls) != 1 || ls[0].User != user || ls[0].Active || !ls[0].On || ls[0].Lapsed != "" {
|
||||
t.Fatalf("listed as %+v", ls)
|
||||
}
|
||||
}
|
||||
|
||||
// A setup-token has the inference scope only: Claude Code's /usage shows
|
||||
// the API cost view for it. Its allowance is unknown, never none, and
|
||||
// /usage isn't run for it.
|
||||
func TestClaudeSetupTokenAllowanceUnknown(t *testing.T) {
|
||||
claudeHome(t)
|
||||
var text atomic.Value
|
||||
text.Store("Total cost: $0.0000\nTotal duration (API): 0s")
|
||||
runs := fakeClaudeUsage(t, &text, nil)
|
||||
user, err := AddClaudeSetupToken(testSetupToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
ws, err := readSavedClaudeUsage(ctx, user)
|
||||
if !errors.Is(err, errClaudeSetupToken) || len(ws) != 0 {
|
||||
t.Fatalf("read %+v, %v; want unknown", ws, err)
|
||||
}
|
||||
if runs.Load() != 0 {
|
||||
t.Fatal("/usage was run for a setup-token")
|
||||
}
|
||||
if claudeUsageDenied.MatchString(err.Error()) {
|
||||
t.Fatalf("%q reads as a refusal", err)
|
||||
}
|
||||
if !passing.MatchString(err.Error()) {
|
||||
t.Fatalf("%q isn't kept as saying nothing about the account", err)
|
||||
}
|
||||
RefreshUsage(ctx, "claude", user)
|
||||
q := LoginUsage(ctx, "claude")[user]
|
||||
if q.Error != errClaudeSetupToken.Error() || len(q.Windows) != 0 || runs.Load() != 0 {
|
||||
t.Fatalf("card %+v after %d runs; want unknown", q, runs.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckClaudeSetupToken(t *testing.T) {
|
||||
for in, ok := range map[string]bool{
|
||||
testSetupToken: true,
|
||||
"'" + testSetupToken + "'": true,
|
||||
"": false,
|
||||
"sk-ant-api03-abc": false,
|
||||
"sk-ant-ort01-refresh": false,
|
||||
"sk-ant-oat01-a b": false,
|
||||
`{"claudeAiOauth":{"accessToken":1}}`: false,
|
||||
} {
|
||||
tok, err := checkClaudeSetupToken(in)
|
||||
if (err == nil) != ok {
|
||||
t.Errorf("%q: %q %v", in, tok, err)
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), in) && in != "" {
|
||||
t.Errorf("%q: the error repeats the token: %v", in, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,9 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo
|
||||
first = &ls[i]
|
||||
}
|
||||
// never one Codex keeps signed in in another folder (switchSavedLogin)
|
||||
if !l.Active && l.On && l.Lapsed == "" && l.home == "" {
|
||||
// nor one added by a setup-token, which Claude Code can't be
|
||||
// signed in to
|
||||
if !l.Active && l.On && l.Lapsed == "" && l.home == "" && !l.Token {
|
||||
spares = append(spares, l)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,9 @@ func SetKeepLoginAs(id, user string) error {
|
||||
if to.Lapsed != "" {
|
||||
return fmt.Errorf("%s has to be signed in to again first", to.User)
|
||||
}
|
||||
if to.Token {
|
||||
return fmt.Errorf(errClaudeTokenSwitch, to.User)
|
||||
}
|
||||
if !p.KeepLogin || p.KeepLoginAs == "" {
|
||||
// the order the gateway goes by now — the one signed in to
|
||||
// first — is kept as the accounts' own, before the sign-in moves
|
||||
@@ -146,7 +149,7 @@ func rankLogins(agent string, order []string) error {
|
||||
// choosing, the one signed in to is the first again.
|
||||
func signInToFirst(agent string) error {
|
||||
for _, l := range Logins(agent) {
|
||||
if (l.Active || l.On) && !l.Paused && l.Lapsed == "" {
|
||||
if (l.Active || l.On) && !l.Paused && l.Lapsed == "" && !l.Token {
|
||||
if l.Active {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -58,6 +58,9 @@ type Login struct {
|
||||
// Returns is the account magpie signed the agent out of when it was
|
||||
// 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.
|
||||
Token bool `json:"token,omitempty"`
|
||||
|
||||
// first is the saved Claude account served in the place of Claude
|
||||
// Code's own while it is signed out (claudeStandIn).
|
||||
@@ -1010,6 +1013,7 @@ func Logins(agent string) []Login {
|
||||
}
|
||||
if l.Agent == "claude" {
|
||||
lg.Lapsed = claudeSignedOut(l)
|
||||
lg.Token = claudeSetupToken(l.Auth) != ""
|
||||
} else {
|
||||
// the one in use too, its sign-in revoked (#1793)
|
||||
lg.Lapsed = revokedLapse(l)
|
||||
@@ -1211,6 +1215,9 @@ 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)
|
||||
}
|
||||
if agent == "claude" {
|
||||
// as Claude Code keeps it, if it has run on the account beside the
|
||||
// one it is signed in to; never one that can't be used, which
|
||||
@@ -1279,6 +1286,9 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
|
||||
}
|
||||
|
||||
func putClaudeLogin(l savedLogin) error {
|
||||
if claudeSetupToken(l.Auth) != "" {
|
||||
return fmt.Errorf(errClaudeTokenSwitch, l.User)
|
||||
}
|
||||
c, ok := parseClaudeCredentials(l.Auth)
|
||||
if !ok {
|
||||
return errors.New("the saved Claude Code sign-in is unreadable")
|
||||
@@ -1503,10 +1513,14 @@ func claudeHolders(ls []savedLogin, l savedLogin) (same bool, others []savedLogi
|
||||
return false, nil
|
||||
}
|
||||
c, ok := parseClaudeCredentials(l.Auth)
|
||||
if !ok {
|
||||
tok := claudeSetupToken(l.Auth)
|
||||
if !ok && tok == "" {
|
||||
return false, nil
|
||||
}
|
||||
holds := func(x savedLogin) bool {
|
||||
if tok != "" {
|
||||
return claudeSetupToken(x.Auth) == tok
|
||||
}
|
||||
o, ok := parseClaudeCredentials(x.Auth)
|
||||
return ok && (c.OAuth.AccessToken != "" && o.OAuth.AccessToken == c.OAuth.AccessToken ||
|
||||
c.OAuth.RefreshToken != "" && o.OAuth.RefreshToken == c.OAuth.RefreshToken)
|
||||
|
||||
@@ -42,9 +42,10 @@ func lastQuotasPath() string { return filepath.Join(filepath.Dir(Path()), "quota
|
||||
|
||||
// passing is an error that says nothing about the account: the vendor
|
||||
// rate limiting, failing or out of reach, or a Claude account's usage not
|
||||
// read this time (errClaudeNotAsked, errClaudeSaved). A sign-in gone bad
|
||||
// read this time (errClaudeNotAsked, errClaudeSaved), or one a setup-token
|
||||
// can't read at all (errClaudeSetupToken). A sign-in gone bad
|
||||
// is not one.
|
||||
var passing = regexp.MustCompile(`(?i)not read yet|doesn't read a saved account|rate.?limit|too many requests|429|internal server error|bad gateway|service unavailable|gateway timeout|deadline exceeded|timeout|timed out|connection (refused|reset)|no such host|network is unreachable|EOF|asks again|fetch failed|unable to connect|ECONN[A-Z]+|ENOTFOUND|EAI_AGAIN|socket hang up|HTTP 5\d\d`)
|
||||
var passing = regexp.MustCompile(`(?i)not read yet|a setup-token can't read|doesn't read a saved account|rate.?limit|too many requests|429|internal server error|bad gateway|service unavailable|gateway timeout|deadline exceeded|timeout|timed out|connection (refused|reset)|no such host|network is unreachable|EOF|asks again|fetch failed|unable to connect|ECONN[A-Z]+|ENOTFOUND|EAI_AGAIN|socket hang up|HTTP 5\d\d`)
|
||||
|
||||
// keyTag names a key's card among the last readings, by what it is (a
|
||||
// plan's windows, a balance) and a digest of the key, never the key: a
|
||||
|
||||
@@ -893,6 +893,11 @@ func addLogin(l savedLogin) (using bool, err error) {
|
||||
ls := readLogins()
|
||||
l.User = codexName(ls, l)
|
||||
using = !signedIn || sameLogin(live, l)
|
||||
if l.Agent == "claude" && claudeSetupToken(l.Auth) != "" {
|
||||
// Claude Code itself can't be signed in to a setup-token: the
|
||||
// account is magpie's alone, its own sign-in left as it is
|
||||
using = false
|
||||
}
|
||||
if first := claudeStandIn(ls); !signedIn && l.Agent == "claude" && first != "" {
|
||||
// logged out of Claude Code with accounts in magpie: it stays so,
|
||||
// as the user left it (a claude.ai sign-in beside magpie's token
|
||||
|
||||
@@ -827,6 +827,9 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow
|
||||
return e.windows(now), nil
|
||||
case active:
|
||||
return []QuotaWindow{}, errClaudeNotAsked
|
||||
case claudeTokenAccount(user):
|
||||
// a refresh wouldn't read it either (readSavedClaudeUsage)
|
||||
return []QuotaWindow{}, errClaudeSetupToken
|
||||
default:
|
||||
return []QuotaWindow{}, errClaudeSaved
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user