From 3d2567915417e144d0fd01debce690400fa8a0aa Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 15:54:15 +0800 Subject: [PATCH] accounts: a setup-token pasted into the Claude import is added as one, not taken for a refresh token liukaybee on X asked whether the token `claude setup-token` prints can be pasted into Providers > Claude > Import accounts. It couldn't: the paste box read every bare line as a refresh token, and a Claude one with no email failed with "the file doesn't say which Claude account this is". parseLoginImport now reads each bare line (and a JSON string) through bareImport. A line that is a setup-token (sk-ant-oat..., bare, as CLAUDE_CODE_OAUTH_TOKEN=... or export CLAUDE_CODE_OAUTH_TOKEN="...") is checked by checkClaudeSetupToken and added by AddClaudeSetupToken, the same path as "Add an account by setup-token...": kept in logins.json, named by its hash, nothing asked of Anthropic. One magpie already has is "exists", twice in one paste is "in the files twice", an sk-ant-api key pasted there is refused as an API key. In the ChatGPT import a setup-token is refused as Claude's and never sent to ChatGPT's token endpoint. Refresh-token lines and JSON files in the same import work as before. No result row carries the token; nothing here logs. Run (mica, mica-run): - TestImportClaudeSetupToken red on origin/main's login_import.go (#2..#5 failed, setup-token lines "doesn't say which Claude account"), green with the fix. - go test ./internal/provider -run 'Import|SetupToken|Login': ok - go vet ./internal/provider: ok - go test -timeout 45m ./internal/provider ./internal/cli: ok, ok - gofmt -l internal/provider: clean Not tried: a real setup-token pasted in the real app (the add path it calls is the existing one, itself not tried with a real token). --- docs/subsystems/providers-accounts.md | 2 +- internal/provider/login_import.go | 60 +++++++++++++++++++++++++- internal/provider/login_import_test.go | 54 +++++++++++++++++++++++ 3 files changed, 113 insertions(+), 3 deletions(-) diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index ba25b77f1..a9c890383 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -57,7 +57,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) | | Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. A `Held` account never gets a config directory of magpie's either (`claudeSavedDir` refuses it, `errClaudeHeld`): a second Claude Code there would spend the refresh token Claude Code holds and sign it out. A sign-in that can't be read whole is no sign-out: Claude Code on Windows rewrites `.credentials.json` and `.claude.json` in place while magpie has the file open (its rename gets EPERM), so a read can find either empty or cut short. Until such a read has lasted `claudeUnsureGrace` (2 minutes), the `Held` account stays active and is not marked lapsed (`claudeSignInUnsure` in `rememberLogins`, `Logins` and `renewLogins`); it is marked lapsed only when the file is gone, Claude Code emptied it, `claude auth status` says it is logged out, or no account is named (xbpb6 on X: the account said Sign-in required over and over on Windows; `TestClaudeHalfWrittenSignInIsNoLogout`). The Mac's keychain item is read whole or not at all, and there nothing changes. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say " 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). ChatGPT also signs in by device code, as `codex login --device-auth` does (`CodexDeviceSite`, `startCodexDeviceSignIn` in `codex_device_signin.go`): magpie asks `auth.openai.com/api/accounts/deviceauth/usercode` for a code, the box shows it with ChatGPT's device page, and magpie polls `deviceauth/token` (403 or 404 is not entered yet, up to 15 minutes), then trades the code at the token endpoint with the verifier it got and the `/deviceauth/callback` redirect. Nothing listens on this machine. The window starts this way when `magpie web` is opened from another computer (`remotePage` in `app.js`: a host other than localhost or loopback; curtinp118 on Discord, magpie on a VPS), and the box offers the other way as a link either way; a device code ChatGPT turns away (404) fails with a link to the browser's way. 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. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened, with a Settings › link to the row, and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. 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), [`codex_device_signin.go`](../../internal/provider/codex_device_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. Claude also reads claude-swap's `cswap export` (format 1, claude-swap 0.29; `cswapEntry`, #4532): each account's `credentials.claudeAiOauth` and `config.oauthAccount`, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (`importNames`). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; `testdata/cswap_0.29.0_export.json` is claude-swap's own output. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's `expiresAt` is later than the one magpie has (the account's own config directory counted, `claudeNewerKept`); otherwise it is `exists` with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, `TestImportCswapKeepsNewerSignIn`). A file that gives no `expiresAt` never replaces one. A sign-in itself imported and never run since is kept with `expiresAt` 1, so any dated file is taken over it. 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) | +| 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. Claude also reads claude-swap's `cswap export` (format 1, claude-swap 0.29; `cswapEntry`, #4532): each account's `credentials.claudeAiOauth` and `config.oauthAccount`, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (`importNames`). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; `testdata/cswap_0.29.0_export.json` is claude-swap's own output. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's `expiresAt` is later than the one magpie has (the account's own config directory counted, `claudeNewerKept`); otherwise it is `exists` with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, `TestImportCswapKeepsNewerSignIn`). A file that gives no `expiresAt` never replaces one. A sign-in itself imported and never run since is kept with `expiresAt` 1, so any dated file is taken over it. An entry with an access token and no refresh token is refused (`accessOnly`). A line (or a JSON string) holding a setup-token (`sk-ant-oat…`, as `claude setup-token` prints it, bare, as `CLAUDE_CODE_OAUTH_TOKEN=…` or `export …`) is added as one by `AddClaudeSetupToken`, never taken for a refresh token (`bareImport`, `importSetupToken`, liukaybee on X); one magpie has is `exists`, an API key pasted there is refused, and in the ChatGPT import it is refused as Claude's, nothing sent (`TestImportClaudeSetupToken`). 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) | | Antigravity to agy | The withdrawn Antigravity plugin (`antigravity`) signed in with Antigravity's own Google OAuth client, the one `agy` signs in with, so its accounts move to Antigravity (local agy CLI) as they are (@tongzhenbao on X). `AgyMoveUsers` names the plugin's sign-ins (then the built-in's never moved) whose email agy-cli doesn't have, as `agyMove` in `/api/providers`; the line over the list (`agymove.js`, imported only when there are any) has Move and Not now. `MoveToAgy` (`provider/toagy`) installs agy-cli at `agyCLIMin` (0.1.68, whose `auth.import` takes them; from the plugins repo's dist branch while npm has none), agy when it is missing, and hands every sign-in to its import, which writes each into an agy home of its own and keeps it only once `agy models` runs with it; one agy refuses is said by name (`agyMoved`). The token goes only where it went (Google, through agy), and the old sign-ins are left where they are. `TestAgyMoveUsersAreTheOldPluginsNotInAgyCLI`, `TestMoveToAgyImportsTheOldSignIns`, `TestToAgyMovesAndSaysEachAccount`, `agy-move.test.cjs`. | [`agy_move.go`](../../internal/provider/agy_move.go), [`providers.go`](../../internal/gui/providers.go), [`agymove.js`](../../internal/gui/assets/agymove.js) | | Export to files | `ExportLogins` (ChatGPT, Claude) writes the saved accounts in the two formats `ImportLogins` reads (heyiwei5 and Rk1ngggg on X): Sub2API's `sub2api-data` (one file, `sub2apiAccount`: `platform` openai or anthropic, as Sub2API's `account_data.go` has it) or CLIProxyAPI's auth files (one an account, `cliproxyAuth`, named `-[-].json`), so a round trip into magpie, Sub2API or CLIProxyAPI works (`TestExportClaudeRoundTrip`, `TestExportCodexRoundTrip`). A CLIProxyAPI Claude file also carries `account_uuid` and `org_uuid`, which its own readers ignore and `loginEntry` keeps, so two seats of one email stay two accounts. The file holds live sign-ins: it is written 0600 and never over a file (`WriteExport`), no surface prints a token, and each says first (`ExportRisk`) that whoever has the file is signed in as the account, and that a ChatGPT refresh token renews in one place only, so the first tool to renew it signs the other out. An account with no refresh token (access-only, a setup-token) is skipped and named with why. The window's *Export accounts to a file…* row on a ChatGPT or Claude account list (`acctexport.js`, `POST /api/signin/export`) saves into Downloads (a folder of its own for CLIProxyAPI's) and shows the path; `magpie accounts export [...] [--format sub2api\|cliproxyapi] [--to ] [--yes]` asks first without `--yes`. | [`login_export.go`](../../internal/provider/login_export.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go), [`gui/providers.go`](../../internal/gui/providers.go), [`acctexport.js`](../../internal/gui/assets/acctexport.js) | | 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) | diff --git a/internal/provider/login_import.go b/internal/provider/login_import.go index 464c7b3aa..3df833683 100644 --- a/internal/provider/login_import.go +++ b/internal/provider/login_import.go @@ -15,7 +15,9 @@ package provider // swapVersion, encrypted, accounts: [{email, uuid, organizationUuid, // organizationName, credentials: {claudeAiOauth: {…}}, config: // {oauthAccount: {…}}, alias, kind}]} (see cswapEntry). A bare refresh token -// a line is taken too. They all sign in with the agents' own OAuth clients, the ones +// a line is taken too, and for Claude a setup-token a line (what `claude +// setup-token` prints, sk-ant-oat…): that one is added as the setup-token +// path adds it (AddClaudeSetupToken), never taken for a refresh token. They all sign in with the agents' own OAuth clients, the ones // magpie uses. // // A ChatGPT one is checked the way a sign-in is finished: its refresh token @@ -55,6 +57,28 @@ type loginImport struct { // milliseconds, 0 when it doesn't say: a refresh gives a later one, // so it tells which of two sign-ins of one account is the newer expiresAt int64 + // setupToken: a Claude setup-token pasted on a line of its own + // (claude_setup_token.go), added as one, never as a sign-in + setupToken string +} + +// bareImport is one token a line (or a JSON string) holds: a refresh +// token, or for Claude a setup-token. A setup-token is told by its own +// prefix, so it is never sent anywhere as a refresh token, nor an API key. +func bareImport(agent, line string) loginImport { + tok := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "export ")) + tok = strings.Trim(strings.TrimPrefix(tok, "CLAUDE_CODE_OAUTH_TOKEN="), `"'`) + switch { + case strings.HasPrefix(tok, "sk-ant-oat") && agent != "claude": + return loginImport{err: "a Claude setup-token, not a ChatGPT sign-in"} + case strings.HasPrefix(tok, "sk-ant-oat"), strings.HasPrefix(tok, "sk-ant-api") && agent == "claude": + t, err := checkClaudeSetupToken(tok) + if err != nil { + return loginImport{err: err.Error()} + } + return loginImport{setupToken: t} + } + return loginImport{refreshToken: strings.TrimSpace(line)} } // jsonMillis is the number under key, 0 when there is none. @@ -123,7 +147,7 @@ func parseLoginImport(agent, data string) ([]loginImport, error) { } out = append(out, loginEntry(agent, x)) case string: - out = append(out, loginImport{refreshToken: strings.TrimSpace(x)}) + out = append(out, bareImport(agent, x)) default: out = append(out, loginImport{err: "not an account"}) } @@ -135,6 +159,10 @@ func parseLoginImport(agent, data string) ([]loginImport, error) { if line == "" || strings.HasPrefix(line, "#") { continue } + if e := bareImport(agent, line); e.refreshToken == "" { + out = append(out, e) // a setup-token, or why it isn't one + continue + } // an address (a sign-in's callback among them) is never sent to // the vendor as a token if strings.ContainsAny(line, " \t") || looksLikeAddress(line) { @@ -408,6 +436,9 @@ func importLogins(ctx context.Context, agent string, files []string, accessOnly if t := loginAccessToken(l); t != "" { haveAccess[t] = l.User } + if t := claudeSetupToken(l.Auth); t != "" && agent == "claude" { + have["setup:"+t] = l.User + } } loginsMu.Unlock() @@ -438,6 +469,15 @@ func importLogins(ctx context.Context, agent string, files []string, accessOnly out[i] = ImportedAccount{User: name, Status: "failed", Error: "in the files twice"} continue case accessOnly: + case e.setupToken != "" && have["setup:"+e.setupToken] != "": + out[i] = ImportedAccount{User: have["setup:"+e.setupToken], Status: "exists"} + continue + case e.setupToken != "": + key = "setup:" + e.setupToken + if seen[key] { + out[i] = ImportedAccount{User: claudeTokenName(e.setupToken), Status: "failed", Error: "in the files twice"} + continue + } case e.refreshToken == "": out[i] = ImportedAccount{User: name, Status: "failed", Error: "no refresh_token in it"} continue @@ -460,6 +500,10 @@ func importLogins(ctx context.Context, agent string, files []string, accessOnly out[i] = importAccessOnly(e, name, kept) return } + if e.setupToken != "" { + out[i] = importSetupToken(e.setupToken) + return + } out[i] = importLogin(c, agent, e, name, kept) }() } @@ -559,6 +603,18 @@ func importAccessOnly(e loginImport, name string, kept []savedLogin) ImportedAcc return ImportedAccount{User: l.User, Status: status, Plan: l.Plan} } +// importSetupToken adds a pasted Claude setup-token as the setup-token +// path does: kept for Claude Code's CLAUDE_CODE_OAUTH_TOKEN, nothing asked +// of Anthropic. Its name is the token's short hash; the token is never +// said back. +func importSetupToken(token string) ImportedAccount { + user, err := AddClaudeSetupToken(token) + if err != nil { + return ImportedAccount{User: claudeTokenName(token), Status: "failed", Error: err.Error()} + } + return ImportedAccount{User: user, Status: "added"} +} + // claudeImportOlder is why a Claude sign-in in a file wasn't taken. const claudeImportOlder = "magpie has a newer sign-in for this account (Claude Code's own, when it is signed in to it): kept, not replaced by this file's" diff --git a/internal/provider/login_import_test.go b/internal/provider/login_import_test.go index c6cfbe567..a5a283a9a 100644 --- a/internal/provider/login_import_test.go +++ b/internal/provider/login_import_test.go @@ -227,3 +227,57 @@ func TestImportCockpitExports(t *testing.T) { t.Errorf("team seats kept: %v (%d logins)", ws, len(ls)) } } + +// liukaybee on X: the token `claude setup-token` prints, pasted into the +// Claude import, is added as a setup-token account (AddClaudeSetupToken), +// never taken for a refresh token; beside it in one paste a refresh token +// a line is read as before. Nothing is asked of Anthropic, the token is +// never said back, and a ChatGPT import says it is Claude's without +// sending it to ChatGPT. +func TestImportClaudeSetupToken(t *testing.T) { + claudeHome(t) + asked := 0 + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked++ + w.WriteHeader(500) + })) + defer fake.Close() + oldBase, oldToken := claudeBase, codexTokenURL + t.Cleanup(func() { claudeBase, codexTokenURL = oldBase, oldToken }) + claudeBase, codexTokenURL = fake.URL, fake.URL + + paste := "# from claude setup-token\nexport CLAUDE_CODE_OAUTH_TOKEN=\"" + testSetupToken + "\"\nsk-ant-ort01-bare\n" + testSetupToken + "\nsk-ant-api03-key\n" + cpa := `{"type":"claude","access_token":"sk-ant-oat01-old","refresh_token":"sk-ant-ort01-cpa","email":"max@example.com"}` + rs, err := ImportLogins(context.Background(), "claude", []string{cpa, paste}) + if err != nil { + t.Fatal(err) + } + name := claudeTokenName(testSetupToken) + if got := importStatuses(rs); got != "max@example.com:added,"+name+":added,#3:failed,"+name+":failed,#5:failed" || asked != 0 { + t.Fatalf("got %s %+v, asked %d", got, rs, asked) + } + if !strings.Contains(rs[4].Error, "API key") { + t.Fatalf("an API key pasted: %q", rs[4].Error) + } + for _, r := range rs { + if strings.Contains(r.User+r.Error, "sk-ant-oat01-setup") { + t.Fatalf("the token said back: %+v", r) + } + } + if tok := ClaudeDirToken(claudeAccountDir(name)); tok != testSetupToken { + t.Fatalf("the setup-token account's token %q", tok) + } + if !claudeTokenAccount(name) { + t.Fatal("not kept as a setup-token account") + } + // the same token again is the account magpie has + rs, err = ImportLogins(context.Background(), "claude", []string{testSetupToken}) + if err != nil || importStatuses(rs) != name+":exists" { + t.Fatalf("again: %+v %v", rs, err) + } + + rs, err = ImportLogins(context.Background(), "codex", []string{testSetupToken}) + if err != nil || len(rs) != 1 || rs[0].Status != "failed" || !strings.Contains(rs[0].Error, "Claude setup-token") || asked != 0 { + t.Fatalf("a setup-token in the ChatGPT import: %+v %v, asked %d", rs, err, asked) + } +}