diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 8b21827bb..f5c7cfada 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -55,6 +55,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 " 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) | +| 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) | | ChatGPT access token only | A saved ChatGPT account can be kept with only the access token it has (EastonXvii on X: `savedLogin.AccessOnly`, `codex_access_only.go`), from the import (`ImportCodexAccessOnly`; the window's *Access token only* tick, `magpie accounts import codex --access-only`) or on a saved account (`SetLoginAccessOnly`; `POST /api/login/access-only` and `/renewed`, the row's ⋯, `magpie accounts access-only codex on|off`). magpie never refreshes it, which would rotate its refresh token and sign out where it came from: the import sends nothing to ChatGPT's token endpoint and needs an unexpired access token and an id_token (a refresh token is optional, and the import is told apart by its access token); `renewSaved` hands out the token while its own exp is ahead (`accessOnlyToken`), refuses a forced renewal without lapsing, and lapses the account once the token has run out or the backend turned it away (`accessOnlyLapse`, a `refreshRefused`); the keep-alive passes it over. Codex itself is never signed in to it (`switchable`, `switchSavedLogin`, `NextLogin`'s return, keep-as), and the account Codex renews itself, here or in another `CODEX_HOME`, can't be kept so (`errAccessOnlyHeld`). Its row says *magpie only*, and once lapsed *Access expired* with *Import again*. Signing in to it again in magpie, or importing it without the tick, replaces the entry with one magpie renews. | | 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. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). 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) | diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index cf11e0b62..d9f517f62 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -120,6 +120,9 @@ func accountsCmd(args []string) error { if len(args) > 1 && args[1] == "import" { return importAccounts(args[2:]) } + if len(args) > 1 && args[1] == "export" { + return exportAccounts(args[2:]) + } if len(args) > 1 && args[1] == "access-only" { return accessOnlyCmd(args[2:]) } @@ -705,6 +708,95 @@ func importAccounts(args []string) error { return nil } +// exportUsage is how `magpie accounts export` is run. +const exportUsage = "usage: magpie accounts export [...] [--format sub2api|cliproxyapi] [--to ] [--yes]" + +// exportAccounts: `magpie accounts export`, the accounts as a file magpie, +// Sub2API or CLIProxyAPI imports. The file is written 0600 into a folder +// (the current one unless --to), never over a file there; its tokens are +// never printed. +func exportAccounts(args []string) error { + yes, format, to := false, provider.ExportSub2API, "." + var rest []string + for i := 0; i < len(args); i++ { + a := args[i] + switch { + case a == "--yes" || a == "-y": + yes = true + case a == "--format" || a == "--to": + if i+1 >= len(args) { + return fmt.Errorf("%s needs a value\n%s", a, exportUsage) + } + i++ + if a == "--to" { + to = args[i] + } else { + format = strings.ToLower(args[i]) + } + case strings.HasPrefix(a, "--format="): + format = strings.ToLower(strings.TrimPrefix(a, "--format=")) + case strings.HasPrefix(a, "--to="): + to = strings.TrimPrefix(a, "--to=") + case strings.HasPrefix(a, "-"): + return fmt.Errorf("%s: no such flag\n%s", a, exportUsage) + default: + rest = append(rest, a) + } + } + if format == "cpa" || format == "cliproxy" { + format = provider.ExportCLIProxy + } + if len(rest) < 1 { + return fmt.Errorf("%s", exportUsage) + } + var id string + switch strings.ToLower(rest[0]) { + case "codex", "chatgpt": + id = "codex" + case "claude", "cc": + id = "claude" + default: + return fmt.Errorf("%q: accounts can be exported for codex and claude\n%s", rest[0], exportUsage) + } + if format != provider.ExportSub2API && format != provider.ExportCLIProxy { + return fmt.Errorf("%q: the format is sub2api or cliproxyapi\n%s", format, exportUsage) + } + // the names are the accounts', as the other account commands take them + var users []string + for _, u := range rest[1:] { + user, err := accountNamed(id, u) + if err != nil { + return err + } + users = append(users, user) + } + fmt.Println(bold.Render("!"), provider.ExportRisk) + if !yes { + fmt.Print("Export? [y/N] ") + var answer string + fmt.Scanln(&answer) + if a := strings.ToLower(strings.TrimSpace(answer)); a != "y" && a != "yes" { + return fmt.Errorf("export canceled") + } + } + res, err := provider.ExportLogins(id, format, users) + for _, s := range res.Skipped { + fmt.Println(bold.Render("✗"), s.User+":", s.Error) + } + if err != nil { + return err + } + paths, err := provider.WriteExport(res, to) + for _, p := range paths { + fmt.Println(green.Render("✓"), "wrote", p, muted.Render("(readable by you only)")) + } + if err != nil { + return err + } + fmt.Println(faint.Render(fmt.Sprintf(" %d account(s): %s", len(res.Accounts), strings.Join(res.Accounts, ", ")))) + return nil +} + // openInBrowser opens url in the user's browser. It is a variable so the // tests can have it go nowhere without starting a program (noBrowser). var openInBrowser = openURLInBrowser diff --git a/internal/cli/accounts_export_cli_test.go b/internal/cli/accounts_export_cli_test.go new file mode 100644 index 000000000..7d5371c31 --- /dev/null +++ b/internal/cli/accounts_export_cli_test.go @@ -0,0 +1,104 @@ +package cli + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// magpie accounts export (heyiwei5 and Rk1ngggg on X): warns first, writes +// nothing until agreed to, writes 0600 files that import back, never prints +// a token and never writes over a file. +func TestAccountsExport(t *testing.T) { + 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("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude")) + t.Setenv("CODEX_HOME", filepath.Join(home, ".codex")) + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + who := strings.TrimPrefix(body["refresh_token"], "r-") + json.NewEncoder(w).Encode(map[string]any{ + "id_token": importJWT(map[string]any{"email": who + "@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "pro", "chatgpt_account_id": "acct-" + who}}), + "access_token": importJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "n-" + who, + }) + })) + defer fake.Close() + t.Cleanup(provider.CodexTokenURLForTest(fake.URL)) + null, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer null.Close() + oldIn := os.Stdin + os.Stdin = null + t.Cleanup(func() { os.Stdin = oldIn }) + + src := filepath.Join(t.TempDir(), "a.json") + os.WriteFile(src, []byte(`{"OPENAI_API_KEY":null,"tokens":{"id_token":"x","access_token":"y","refresh_token":"r-a","account_id":"acct-a"}}`), 0o600) + if out, err := said(t, func() error { return accountsCmd([]string{"accounts", "import", "codex", src, "--yes"}) }); err != nil { + t.Fatalf("%v\n%s", err, out) + } + held := provider.Logins("codex") + if len(held) != 1 { + t.Fatalf("logins %+v", held) + } + + out := t.TempDir() + run := func(args ...string) (string, error) { + t.Helper() + return said(t, func() error { return accountsCmd(append([]string{"accounts", "export"}, args...)) }) + } + // not agreed to: the warning, no file + says, err := run("codex", "--to", out) + if err == nil || !strings.Contains(err.Error(), "canceled") { + t.Fatalf("exported without --yes: %v\n%s", err, says) + } + if es, _ := os.ReadDir(out); len(es) != 0 { + t.Fatalf("wrote before agreed: %v", es) + } + for _, format := range []string{"sub2api", "cliproxyapi"} { + says, err = run("codex", "--format", format, "--to", out, "--yes") + if err != nil { + t.Fatalf("%s: %v\n%s", format, err, says) + } + if strings.Contains(says, "n-a") || strings.Contains(says, "r-a") { + t.Errorf("a token was printed:\n%s", says) + } + } + es, _ := os.ReadDir(out) + if len(es) != 2 { + t.Fatalf("files %v", es) + } + for _, e := range es { + p := filepath.Join(out, e.Name()) + if runtime.GOOS != "windows" { + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 { + t.Errorf("%s is %v, not 0600", e.Name(), fi.Mode().Perm()) + } + } + } + // again: the first files stay, new ones are named beside them + if _, err = run("codex", "--format", "sub2api", "--to", out, "--yes"); err != nil { + t.Fatal(err) + } + if es, _ := os.ReadDir(out); len(es) != 3 { + t.Errorf("an export wrote over a file: %v", es) + } + if _, err := run("codex", "--format", "csv", "--to", out, "--yes"); err == nil { + t.Error("an unknown format was taken") + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index e6fbe8e9d..8a570dd40 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -106,6 +106,7 @@ const usage = `magpie — one place to pick every agent's model magpie accounts add copilot [--host .ghe.com] one more Copilot account, on github.com or an enterprise's GHE.com magpie accounts discovery [on|off] read agents' sign-ins (default on; MAGPIE_NO_ACCOUNTS=1 disables too) magpie accounts import ... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API, claude-swap); the tool a ChatGPT or Claude file came from is signed out of it + magpie accounts export [...] [--format sub2api|cliproxyapi] [--to ] [--yes] write accounts as a file Sub2API, CLIProxyAPI or magpie imports (0600; holds live sign-ins) magpie accounts import codex ... --access-only keep each ChatGPT account with its access token only: never renewed, so the tool it came from stays signed in magpie accounts access-only codex [on|off] keep a ChatGPT account access token only, or let magpie renew its sign-in again magpie accounts switch sign the agent in to another of them, by its email or the name you gave it diff --git a/internal/gui/assets/acctexport.js b/internal/gui/assets/acctexport.js new file mode 100644 index 000000000..2be7be8d1 --- /dev/null +++ b/internal/gui/assets/acctexport.js @@ -0,0 +1,67 @@ +// ChatGPT and Claude accounts taken out as a file Sub2API, CLIProxyAPI or +// magpie imports (heyiwei5 and Rk1ngggg on X). app.js imports this when +// "Export accounts to a file…" is pressed (startExport), so it weighs +// nothing on the core. The file is written by the server, 0600, into +// Downloads; its tokens never reach the page. + +window.accountExportSheet = function (sub) { + const flow = signing; + const box = el("div", "signing export"); + const tt = el("span", "tt"); + box.append(tt); + const logins = (providers?.providers || []).find((p) => p.account?.agent === flow.agent)?.account?.logins || []; + if (flow.done) { + box.append(el("span", "mark", "✓")); + tt.append(el("span", "n", t("Saved to {path}", { path: flow.done.path }))); + const rs = el("span", "results"); + for (const u of flow.done.accounts) rs.append(el("span", "res added", u)); + for (const s of flow.done.skipped || []) { + const row = el("span", "res failed"); + row.append(el("span", "u", s.user), el("span", "why", s.error)); + rs.append(row); + } + tt.append(rs); + const done = el("button", "text primary", t("Done")); + done.onclick = cancelSignIn; + box.append(done); + return box; + } + box.append(el("span", "mark", "↓")); + tt.append(el("span", "n", t("Export {name} accounts", { name: sub.name })), + el("span", "s why", t("The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported."))); + if (flow.agent === "codex") tt.append(el("span", "s", t("A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out."))); + const fmt = segs([["sub2api", "Sub2API"], ["cliproxyapi", "CLIProxyAPI"]], flow.format, (id) => { flow.format = id; }); + tt.append(fmt); + const list = el("span", "results"); + const go = el("button", "text primary", t("Export")); + const sync = () => { go.disabled = !!flow.busy || logins.every((l) => flow.off.has(l.user)); }; + for (const l of logins) { + const [lab, cb] = tick(l.user + (l.plan ? " · " + l.plan : ""), !flow.off.has(l.user)); + cb.onchange = () => { if (cb.checked) flow.off.delete(l.user); else flow.off.add(l.user); sync(); }; + list.append(lab); + } + tt.append(list); + const why = el("span", "s why", flow.error || ""); + tt.append(why); + go.onclick = async () => { + if (signing !== flow || flow.busy) return; + flow.busy = true; + sync(); + try { + const users = logins.filter((l) => !flow.off.has(l.user)).map((l) => l.user); + const r = await api("signin/export", { agent: flow.agent, format: flow.format, users }); + if (signing !== flow) return; + flow.done = r; + } catch (err) { + if (signing !== flow) return; + flow.error = err.message; + } + flow.busy = false; + renderProviders(); + }; + sync(); + const close = el("button", "text", t("Cancel")); + close.onclick = cancelSignIn; + box.append(close, go); + return box; +}; diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4715cbba6..1abb44d56 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -12923,13 +12923,14 @@ function copilotHostSwitch(sub) { // signAsk: a sign-in that asks one value first (Copilot's GHE.com host, a // Claude setup-token); its sheet is in signsheets.js, loaded when asked for -async function signAsk(flow) { - try { await import("./signsheets.js"); } catch (err) { return statusErr(err); } +async function signAsk(flow, sheet = "./signsheets.js") { + try { await import(sheet); } catch (err) { return statusErr(err); } stopSignIn(); signing = flow; renderProviders(); } const startClaudeToken = () => signAsk({ agent: "claude", state: "token", token: "" }); +const startExport = (agent) => signAsk({ agent, state: "export", format: "sub2api", off: new Set() }, "./acctexport.js"); // dropSigningIn: an editor closing leaves no sign-in waiting (#526); an // import being read finishes. @@ -13009,6 +13010,7 @@ function renderSigning(sub) { } if (signing.state === "ghe") return window.copilotGHESheet(); if (signing.state === "token") return window.claudeTokenSheet(); + if (signing.state === "export") return window.accountExportSheet(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") { @@ -13597,6 +13599,7 @@ function renderAccounts(a, p) { imp.title = importSay(a.agent).from; list.append(imp); } + if (sub.importable && (a.agent === "claude" || a.agent === "codex")) list.append(addRow(t("Export accounts to a file…"), () => startExport(a.agent))); if (a.agent === "claude") list.append(addRow(t("Add an account by setup-token…"), startClaudeToken)); } arrangeAccountRows(list, p); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5a2c94691..98a131827 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2310,6 +2310,10 @@ const I18N = { "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 的请求会和你的其他账号一起使用它", + "Export accounts to a file…": "导出账号到文件…", + "Export {name} accounts": "导出 {name} 账号", + "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported.": "文件里是每个账号当前的登录凭证:拿到文件的人就等于登录了该账号。请妥善保管,导入后删除。", + "A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out.": "ChatGPT 的登录只能在一处续期:先续期的工具会把另一处登出。", "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 本身无法登录到这个账号", @@ -7294,6 +7298,10 @@ const I18N = { "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 的請求會和你的其他帳號一起使用它", + "Export accounts to a file…": "匯出帳號到檔案…", + "Export {name} accounts": "匯出 {name} 帳號", + "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported.": "檔案裡是每個帳號目前的登入憑證:拿到檔案的人就等於登入了該帳號。請妥善保管,匯入後刪除。", + "A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out.": "ChatGPT 的登入只能在一處續期:先續期的工具會把另一處登出。", "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 本身無法登入到這個帳號", @@ -12254,6 +12262,10 @@ const I18N = { "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 経由のリクエストはほかのアカウントと並べてこれを使います", + "Export accounts to a file…": "アカウントをファイルに書き出す…", + "Export {name} accounts": "{name} のアカウントを書き出す", + "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported.": "ファイルには各アカウントの有効なサインインが入っています。持っている人はそのアカウントでサインインしたことになります。非公開にし、インポート後は削除してください。", + "A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out.": "ChatGPT のサインインは 1 か所でしか更新できません。先に更新したツールがもう一方をサインアウトさせます。", "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 自体をこのアカウントにサインインさせることはできません", @@ -17245,6 +17257,10 @@ const I18N = { "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", + "Export accounts to a file…": "Konten in eine Datei exportieren…", + "Export {name} accounts": "{name}-Konten exportieren", + "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported.": "Die Datei enthält die aktive Anmeldung jedes Kontos: Wer sie hat, ist als dieses Konto angemeldet. Halte sie privat und lösche sie nach dem Import.", + "A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out.": "Eine ChatGPT-Anmeldung lässt sich nur an einer Stelle erneuern: Das erste Tool, das sie erneuert, meldet das andere ab.", "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", diff --git a/internal/gui/login_export_test.go b/internal/gui/login_export_test.go new file mode 100644 index 000000000..1fd8846d4 --- /dev/null +++ b/internal/gui/login_export_test.go @@ -0,0 +1,86 @@ +package gui + +import ( + "context" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// POST /api/signin/export (heyiwei5 and Rk1ngggg on X): the accounts are +// written 0600 into Downloads, in a folder of their own for CLIProxyAPI, +// and the answer names the file and never holds a token. +func TestSigninExportWritesPrivateFiles(t *testing.T) { + h := sandboxHome(t) + t.Setenv("CODEX_HOME", filepath.Join(h, ".codex")) + if err := os.MkdirAll(filepath.Join(h, "Downloads"), 0o755); err != nil { + t.Fatal(err) + } + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + claims := func(m map[string]any) string { + b, _ := json.Marshal(m) + return "e30." + base64.RawURLEncoding.EncodeToString(b) + ".sig" + } + json.NewEncoder(w).Encode(map[string]any{ + "id_token": claims(map[string]any{"email": "a@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "pro", "chatgpt_account_id": "acct-a"}}), + "access_token": claims(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "SECRET-refresh", + }) + })) + defer fake.Close() + t.Cleanup(provider.CodexTokenURLForTest(fake.URL)) + seed := `{"tokens":{"id_token":"x","access_token":"y","refresh_token":"r-a","account_id":"acct-a"}}` + if res, err := provider.ImportLogins(context.Background(), "codex", []string{seed}); err != nil || len(res) == 0 || res[0].Status != "added" { + t.Fatalf("%+v %v", res, err) + } + mux := http.NewServeMux() + providerRoutes(mux, folderOnly{}) + post := func(body any) (int, string, map[string]any) { + b, _ := json.Marshal(body) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/signin/export", strings.NewReader(string(b)))) + var out map[string]any + json.Unmarshal(w.Body.Bytes(), &out) + return w.Code, w.Body.String(), out + } + for _, format := range []string{"sub2api", "cliproxyapi"} { + code, raw, out := post(map[string]any{"agent": "codex", "format": format}) + if code != 200 { + t.Fatalf("%s: %d %s", format, code, raw) + } + if strings.Contains(raw, "SECRET") { + t.Errorf("%s: a token is in the answer: %s", format, raw) + } + p, _ := out["path"].(string) + if !strings.HasPrefix(p, "~") { + t.Fatalf("%s: path %q", format, p) + } + file := filepath.Join(h, strings.TrimPrefix(p, "~")) + if format == "cliproxyapi" && !strings.Contains(file, "magpie-cliproxyapi-codex-") { + t.Errorf("not in a folder of its own: %s", file) + } + data, err := os.ReadFile(file) + if err != nil || !strings.Contains(string(data), "SECRET-refresh") { + t.Fatalf("%s: %v %s", format, err, data) + } + if fi, _ := os.Stat(file); runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 { + t.Errorf("%s is %v, not 0600", file, fi.Mode().Perm()) + } + } + if code, _, _ := post(map[string]any{"agent": "codex", "format": "sub2api", "users": []string{"nobody@example.com"}}); code == 200 { + t.Error("an account that isn't there was exported") + } + if code, _, _ := post(map[string]any{"agent": "gemini", "format": "sub2api"}); code == 200 { + t.Error("gemini was exported") + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index f4d5a9d21..3fd9d4ee7 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -9,6 +9,8 @@ import ( "fmt" "io" "net/http" + "os" + "path/filepath" "slices" "strconv" "strings" @@ -3188,6 +3190,55 @@ func providerRoutes(mux *http.ServeMux, w Windows) { Providers providersJSON `json:"providers"` }{res, providersState()}) }) + // ChatGPT and Claude accounts taken out as a file Sub2API, CLIProxyAPI + // or magpie imports (heyiwei5 and Rk1ngggg on X). The file holds live + // sign-ins: it is written 0600 into Downloads, never sent to the page, + // and its tokens are never logged. + mux.HandleFunc("POST /api/signin/export", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Agent, Format string + Users []string + } + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&in); err != nil { + fail(rw, err) + return + } + res, err := provider.ExportLogins(in.Agent, in.Format, in.Users) + if err != nil { + fail(rw, err) + return + } + dir := downloads() + stamp := time.Now().Format("2006-01-02") + if in.Format == provider.ExportCLIProxy { + // one file an account, in a folder of their own + base := filepath.Join(dir, "magpie-cliproxyapi-"+in.Agent+"-"+stamp) + dir = base + for i := 2; ; i++ { + if _, err := os.Stat(dir); err != nil { + break + } + dir = fmt.Sprintf("%s-%d", base, i) + } + } else { + res.Files[0].Name = "magpie-sub2api-" + in.Agent + "-" + stamp + ".json" + } + paths, err := provider.WriteExport(res, dir) + if err != nil { + fail(rw, err) + return + } + shown := dir + if len(paths) == 1 { + shown = paths[0] + } + _ = w.OpenFolder(dir) // saved either way; the path is in the answer + writeJSON(rw, struct { + Path string `json:"path"` + Accounts []string `json:"accounts"` + Skipped []provider.ImportedAccount `json:"skipped"` + }{tilde(shown), res.Accounts, res.Skipped}) + }) // StepFun's Step Plan windows: the session the user copied from their // browser with magpie's bookmarklet, the provider's own (two on one // site can be two accounts, #2384), on the provider's platform diff --git a/internal/gui/tests/login-export.test.cjs b/internal/gui/tests/login-export.test.cjs new file mode 100644 index 000000000..9d2871daf --- /dev/null +++ b/internal/gui/tests/login-export.test.cjs @@ -0,0 +1,96 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ChatGPT and Claude accounts go out as a file Sub2API, CLIProxyAPI or +// magpie takes (heyiwei5 and Rk1ngggg on X): the accounts list offers it, +// the sheet warns that the file holds live sign-ins, lists each account to +// tick, posts the chosen ones and format, and says where the file went; in +// English and Chinese, in both engines, at 380px too. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const logins = [ + { user: "live@example.com", plan: "plus", active: true, on: true }, + { user: "two@example.com", plan: "pro", on: true }, +]; +const account = { + id: "codex", name: "ChatGPT", icon: "openai", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "codex", agentName: "Codex", user: "live@example.com", plan: "plus", logins }, +}; + +function serve(lang, posted) { + const providers = { providers: [account], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",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(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/signin/export") { + posted.push(route.request().postDataJSON()); + return json({ path: "~/Downloads/magpie-sub2api-codex.json", accounts: ["live@example.com"], skipped: [{ user: "two@example.com", error: "no refresh token" }] }); + } + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, width] of [["en", 900], ["zh", 900], ["en", 380]]) { + test(`${engine} ${lang} ${width}: accounts are exported as a file`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posted = []; + await page.route("**/*", serve(lang, posted)); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-login-export.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "ChatGPT" }).click(); + const T = async (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v || {}]); + const row = page.locator(".editor .accts .acc.add", { hasText: await T("Export accounts to a file…") }); + await row.waitFor(); + if (lang === "zh") { + for (const s of ["Export accounts to a file…", "Export {name} accounts", "Saved to {path}", "Export", + "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it once it is imported.", + "A ChatGPT sign-in can be renewed in one place only: the first tool to renew it signs the other out."]) { + assert.notEqual(await T(s), s, "no Chinese for: " + s); + } + } + await row.click(); + const box = page.locator(".signing.export"); + await box.waitFor(); + assert.match(await box.textContent(), lang === "en" ? /whoever has it is signed in as that account/ : /拿到文件的人/); + // each account to tick, the first format picked + assert.equal(await box.locator("input[type=checkbox]").count(), 2); + await box.locator("input[type=checkbox]").nth(1).uncheck(); + await box.locator(".segs .opt", { hasText: "CLIProxyAPI" }).click(); + await box.locator("button.primary").click(); + await box.locator(".res.added").waitFor(); + assert.deepEqual(posted, [{ agent: "codex", format: "cliproxyapi", users: ["live@example.com"] }]); + assert.match(await box.textContent(), /magpie-sub2api-codex\.json/); + assert.match(await box.textContent(), /two@example\.com/); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "page scrolls sideways"); + await box.locator("button.primary").click(); + await box.waitFor({ state: "detached" }); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 0b9d61680..78c059914 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -172,7 +172,7 @@ test("compat.js is the first of the page's own scripts", async () => { // pluginmd.js (a README's renderer) once plugins.js has run; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/provider/login_export.go b/internal/provider/login_export.go new file mode 100644 index 000000000..7edaef8df --- /dev/null +++ b/internal/provider/login_export.go @@ -0,0 +1,324 @@ +package provider + +// ChatGPT (Codex) and Claude accounts taken out of magpie as a file the +// tools ImportLogins reads can take back: Sub2API's data export +// ({type: "sub2api-data", accounts: […]}) in one file, or CLIProxyAPI's +// auth files ({type: "codex"|"claude", …}) one file a account, as it keeps +// them in its auth folder. A file holds live tokens: whoever has it is +// signed in as the account. The tokens are never logged; the caller writes +// the files 0600. +// +// A ChatGPT refresh token is spent by its first use, so an exported account +// can't be signed in in two places: the first to renew it signs the other +// out. Exporting changes nothing here; the account is the other tool's from +// the moment it is used there. + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "time" +) + +// Export formats. +const ( + ExportSub2API = "sub2api" + ExportCLIProxy = "cliproxyapi" + sub2apiDataType = "sub2api-data" +) + +// ExportFile is one file of an export. +type ExportFile struct { + Name string + Data []byte +} + +// ExportResult is what an export made: its files, the accounts in them and +// the accounts left out, with why. +type ExportResult struct { + Files []ExportFile + Accounts []string + Skipped []ImportedAccount // Status "skipped", Error says why +} + +// exportAccount is one account's sign-in, read. +type exportAccount struct { + user, plan string + email, idToken, accessToken, refreshToken, aid string + scopes []string + expires time.Time + claudeAccount, claudeOrg string +} + +// ExportLogins writes the accounts of agent (codex, claude) named in users +// (every one when empty) in format (ExportSub2API or ExportCLIProxy). +func ExportLogins(agent, format string, users []string) (ExportResult, error) { + if discoveryOff() { + return ExportResult{}, errAccountDiscoveryOff + } + if agent != "codex" && agent != "claude" { + return ExportResult{}, fmt.Errorf("accounts can't be exported for %s", agent) + } + if format != ExportSub2API && format != ExportCLIProxy { + return ExportResult{}, fmt.Errorf("format %q: sub2api or cliproxyapi", format) + } + loginsMu.Lock() + ls := slices.DeleteFunc(readLogins(), func(l savedLogin) bool { return l.Agent != agent }) + // the account the agent is signed in to is read from its own file: that + // is fresher than magpie's copy + if live, ok := liveLogin(agent); ok { + at := slices.IndexFunc(ls, func(l savedLogin) bool { return sameLogin(l, live) }) + if at < 0 { + ls = append(ls, live) + } else { + ls[at].Auth = live.Auth + } + } + for i, l := range ls { + if agent == "codex" { + if home := codexHeldIn(l); home != "" { + if b, _, err := readCodexLogin(home, false); err == nil { + ls[i].Auth = b + } + } + } + } + loginsMu.Unlock() + + var res ExportResult + var accts []exportAccount + want := map[string]bool{} + for _, u := range users { + want[strings.ToLower(strings.TrimSpace(u))] = true + } + found := map[string]bool{} + for _, l := range ls { + if len(want) > 0 && !want[strings.ToLower(l.User)] { + continue + } + found[strings.ToLower(l.User)] = true + a, why := exportRead(agent, l) + if why != "" { + res.Skipped = append(res.Skipped, ImportedAccount{User: l.User, Status: "skipped", Error: why}) + continue + } + accts = append(accts, a) + } + for _, u := range users { + if !found[strings.ToLower(strings.TrimSpace(u))] { + return ExportResult{}, fmt.Errorf("no %s account %q", agent, u) + } + } + if len(accts) == 0 { + if len(res.Skipped) > 0 { + return res, errors.New("none of the accounts can be exported") + } + return res, fmt.Errorf("no %s accounts", agent) + } + slices.SortFunc(accts, func(a, b exportAccount) int { return strings.Compare(strings.ToLower(a.user), strings.ToLower(b.user)) }) + for _, a := range accts { + res.Accounts = append(res.Accounts, a.user) + } + switch format { + case ExportSub2API: + accounts := make([]any, len(accts)) + for i, a := range accts { + accounts[i] = sub2apiAccount(agent, a) + } + b, err := json.MarshalIndent(map[string]any{"type": sub2apiDataType, "version": 1, + "exported_at": time.Now().UTC().Format(time.RFC3339), "proxies": []any{}, "accounts": accounts}, "", " ") + if err != nil { + return ExportResult{}, err + } + res.Files = []ExportFile{{Name: "magpie-sub2api-" + agent + ".json", Data: append(b, '\n')}} + default: + used := map[string]bool{} + for _, a := range accts { + b, err := json.MarshalIndent(cliproxyAuth(agent, a), "", " ") + if err != nil { + return ExportResult{}, err + } + name := exportName(agent, a) + for i := 2; used[name]; i++ { + name = fmt.Sprintf("%s-%d", strings.TrimSuffix(exportName(agent, a), ".json"), i) + ".json" + } + used[name] = true + res.Files = append(res.Files, ExportFile{Name: name, Data: append(b, '\n')}) + } + } + return res, nil +} + +var exportUnsafe = regexp.MustCompile(`[^A-Za-z0-9@._+-]+`) + +// exportName is CLIProxyAPI's name for an auth file: -.json, +// a ChatGPT one's plan after the email. +func exportName(agent string, a exportAccount) string { + n := agent + "-" + cmpOr(a.email, a.user) + if agent == "codex" && a.plan != "" { + n += "-" + a.plan + } + return strings.Trim(exportUnsafe.ReplaceAllString(n, "_"), "_.") + ".json" +} + +// exportRead reads one saved account's tokens; why says it can't be exported. +func exportRead(agent string, l savedLogin) (exportAccount, string) { + a := exportAccount{user: l.User, plan: l.Plan} + switch agent { + case "codex": + var c codexAuth + if json.Unmarshal(l.Auth, &c) != nil || c.Tokens.AccessToken == "" && c.Tokens.RefreshToken == "" { + return a, "its sign-in can't be read" + } + a.idToken, a.accessToken, a.refreshToken, a.aid = c.Tokens.IDToken, c.Tokens.AccessToken, c.Tokens.RefreshToken, c.Tokens.AccountID + id := jwtClaims(c.Tokens.IDToken) + a.email = cmpOr(claimString(id, "email"), l.User) + if p := claimString(id, "https://api.openai.com/auth", "chatgpt_plan_type"); p != "" { + a.plan = p + } + if a.aid == "" { + a.aid = claimString(id, "https://api.openai.com/auth", "chatgpt_account_id") + } + if exp, ok := jwtClaims(a.accessToken)["exp"].(float64); ok { + a.expires = time.Unix(int64(exp), 0) + } + case "claude": + if claudeSetupToken(l.Auth) != "" { + return a, "a setup-token account has no refresh token to give" + } + c, ok := parseClaudeCredentials(l.Auth) + if !ok { + return a, "its sign-in can't be read" + } + a.accessToken, a.refreshToken, a.scopes = c.OAuth.AccessToken, c.OAuth.RefreshToken, c.OAuth.Scopes + if c.OAuth.ExpiresAt > 1 { + a.expires = time.UnixMilli(c.OAuth.ExpiresAt) + } + var p map[string]any + _ = json.Unmarshal(l.Profile, &p) + a.email = jsonStr(p, "emailAddress") + a.claudeAccount, a.claudeOrg = jsonStr(p, "accountUuid"), jsonStr(p, "organizationUuid") + if a.email == "" && strings.Contains(l.User, "@") { + a.email = l.User + } + } + if a.refreshToken == "" { + return a, "it has no refresh token, only an access token" + } + if bytes.ContainsAny([]byte(a.refreshToken), " \n") { + return a, "its refresh token isn't one" + } + return a, "" +} + +// cliproxyAuth is CLIProxyAPI's auth file for the account. +func cliproxyAuth(agent string, a exportAccount) map[string]any { + m := map[string]any{"type": agent, "email": a.email, "access_token": a.accessToken, "refresh_token": a.refreshToken, + "last_refresh": time.Now().UTC().Format(time.RFC3339)} + if !a.expires.IsZero() { + m["expired"] = a.expires.UTC().Format(time.RFC3339) + } + if agent == "codex" { + m["id_token"], m["account_id"] = a.idToken, a.aid + } + // CLIProxyAPI's own claude file names no organization, so two seats of + // one email would come back as one account; the uuids are extra keys it + // leaves alone and magpie reads (loginEntry) + if a.claudeAccount != "" { + m["account_uuid"] = a.claudeAccount + } + if a.claudeOrg != "" { + m["org_uuid"] = a.claudeOrg + } + return m +} + +// sub2apiAccount is one entry of Sub2API's data export. +func sub2apiAccount(agent string, a exportAccount) map[string]any { + c := map[string]any{"access_token": a.accessToken, "refresh_token": a.refreshToken} + m := map[string]any{"name": cmpOr(a.email, a.user), "type": "oauth", "concurrency": 10, "priority": 1, + "rate_multiplier": 1, "auto_pause_on_expired": true, "credentials": c} + switch agent { + case "codex": + m["platform"] = "openai" + c["id_token"], c["chatgpt_account_id"], c["email"], c["client_id"] = a.idToken, a.aid, a.email, codexClientID + if a.plan != "" { + c["plan_type"] = a.plan + } + if !a.expires.IsZero() { + c["expires_at"] = a.expires.UTC().Format(time.RFC3339) + } + case "claude": + m["platform"] = "anthropic" + extra := map[string]any{} + if a.email != "" { + c["email_address"], extra["email_address"] = a.email, a.email + } + if a.claudeAccount != "" { + c["account_uuid"], extra["account_uuid"] = a.claudeAccount, a.claudeAccount + } + if a.claudeOrg != "" { + c["org_uuid"], extra["org_uuid"] = a.claudeOrg, a.claudeOrg + } + if len(a.scopes) > 0 { + c["scope"] = strings.Join(a.scopes, " ") + } + if !a.expires.IsZero() { + c["expires_at"] = a.expires.Unix() + } + if len(extra) > 0 { + m["extra"] = extra + } + } + return m +} + +// ExportRisk is said wherever an export is offered. +const ExportRisk = "The file holds each account's live sign-in: whoever has it is signed in as that account. Keep it private and delete it when it has been imported. A ChatGPT sign-in can be renewed in one place only, so the first tool to renew it signs the other out." + +// WriteExport writes the files of res into dir (made 0700 when it is not +// there), each 0600 and never over a file that is there: a name taken gets +// -2, -3 … before its extension. It answers the paths written. +func WriteExport(res ExportResult, dir string) ([]string, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + var paths []string + for _, f := range res.Files { + stem, ext := strings.TrimSuffix(f.Name, ".json"), ".json" + var err error + for i := 1; ; i++ { + name := filepath.Join(dir, stem+ext) + if i > 1 { + name = filepath.Join(dir, fmt.Sprintf("%s-%d%s", stem, i, ext)) + } + var fh *os.File + fh, err = os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, os.ErrExist) && i < 1000 { + continue + } + if err == nil { + _, err = fh.Write(f.Data) + if cerr := fh.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(name) + } else { + paths = append(paths, name) + } + } + break + } + if err != nil { + return paths, err + } + } + return paths, nil +} diff --git a/internal/provider/login_export_test.go b/internal/provider/login_export_test.go new file mode 100644 index 000000000..e58cd7b6f --- /dev/null +++ b/internal/provider/login_export_test.go @@ -0,0 +1,192 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// heldTokens is each kept sign-in's refresh token against its user and +// identity, to compare two homes. +func heldTokens(agent string) map[string]string { + out := map[string]string{} + for _, l := range readLogins() { + if l.Agent != agent { + continue + } + who := l.User + if agent == "claude" { + e, org := claudeWho(l.Profile) + who = e + "/" + org + } else { + _, ws := codexWho(l.Auth) + who += "/" + ws + } + out[loginRefreshToken(l)] = who + } + return out +} + +func equalMaps(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if b[k] != v { + return false + } + } + return true +} + +// A Claude account exported in either format is imported again, here, as +// the same two seats of one email (an organization apart), and the files +// carry what Sub2API and CLIProxyAPI's own say. +func TestExportClaudeRoundTrip(t *testing.T) { + claudeHome(t) + seats := `{"type":"sub2api-data","version":1,"proxies":[],"accounts":[ + {"name":"seat-a","platform":"anthropic","type":"oauth", + "credentials":{"access_token":"sk-ant-oat01-a","expires_at":1760000000,"refresh_token":"sk-ant-ort01-a","scope":"user:inference user:profile","org_uuid":"org-a","account_uuid":"acct-1","email_address":"team@example.com"}}, + {"name":"seat-b","platform":"anthropic","type":"oauth", + "credentials":{"access_token":"sk-ant-oat01-b","refresh_token":"sk-ant-ort01-b"}, + "extra":{"org_uuid":"org-b","account_uuid":"acct-1","email_address":"team@example.com"}}]}` + if _, err := ImportLogins(context.Background(), "claude", []string{seats}); err != nil { + t.Fatal(err) + } + before := heldTokens("claude") + if len(before) != 2 { + t.Fatalf("held %v", before) + } + + s2a, err := ExportLogins("claude", ExportSub2API, nil) + if err != nil || len(s2a.Files) != 1 || len(s2a.Accounts) != 2 { + t.Fatalf("%+v %v", s2a, err) + } + var doc struct { + Type string + Accounts []struct { + Platform, Type string + Credentials map[string]any + } + } + if err := json.Unmarshal(s2a.Files[0].Data, &doc); err != nil || doc.Type != "sub2api-data" || len(doc.Accounts) != 2 || + doc.Accounts[0].Platform != "anthropic" || doc.Accounts[0].Type != "oauth" || doc.Accounts[0].Credentials["refresh_token"] == "" { + t.Fatalf("%s %v", s2a.Files[0].Data, err) + } + cpa, err := ExportLogins("claude", ExportCLIProxy, nil) + if err != nil || len(cpa.Files) != 2 { + t.Fatalf("%+v %v", cpa, err) + } + var one map[string]any + if json.Unmarshal(cpa.Files[0].Data, &one) != nil || one["type"] != "claude" || one["email"] != "team@example.com" || + !strings.HasPrefix(cpa.Files[0].Name, "claude-team@example.com") || cpa.Files[0].Name == cpa.Files[1].Name { + t.Fatalf("%s %s", cpa.Files[0].Name, cpa.Files[0].Data) + } + + for name, files := range map[string][]ExportFile{"sub2api": s2a.Files, "cliproxyapi": cpa.Files} { + claudeHome(t) // a new computer + var texts []string + for _, f := range files { + texts = append(texts, string(f.Data)) + } + rs, err := ImportLogins(context.Background(), "claude", texts) + if err != nil { + t.Fatal(name, err) + } + if got := heldTokens("claude"); !equalMaps(got, before) { + t.Fatalf("%s: back as %v, was %v (%+v)", name, got, before, rs) + } + } +} + +// A ChatGPT account makes the round trip too, each file refreshed on the +// way in as any import is. +func TestExportCodexRoundTrip(t *testing.T) { + claudeHome(t) + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + rt := body["refresh_token"] + who, ok := map[string][2]string{"r1": {"a@example.com", "acct-1"}, "r2": {"b@example.com", "acct-2"}}[strings.TrimPrefix(rt, "n")] + if !ok { + w.WriteHeader(400) + return + } + json.NewEncoder(w).Encode(map[string]any{ + "id_token": fakeJWT(map[string]any{"email": who[0], + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus", "chatgpt_account_id": who[1]}}), + "access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "n" + strings.TrimPrefix(rt, "n"), + }) + })) + defer fake.Close() + t.Cleanup(CodexTokenURLForTest(fake.URL)) + in := `[{"type":"codex","email":"a@example.com","id_token":"x","access_token":"y","refresh_token":"r1","account_id":"acct-1"}, + {"type":"codex","email":"b@example.com","id_token":"x","access_token":"y","refresh_token":"r2","account_id":"acct-2"}]` + if _, err := ImportLogins(context.Background(), "codex", []string{in}); err != nil { + t.Fatal(err) + } + before := heldTokens("codex") + if len(before) != 2 { + t.Fatalf("held %v", before) + } + + // one account picked by name + one, err := ExportLogins("codex", ExportSub2API, []string{"B@example.com"}) + if err != nil || len(one.Accounts) != 1 || !strings.Contains(one.Accounts[0], "b@example.com") { + t.Fatalf("%+v %v", one, err) + } + if _, err := ExportLogins("codex", ExportSub2API, []string{"nobody@example.com"}); err == nil { + t.Fatal("a name no account has was exported") + } + s2a, err := ExportLogins("codex", ExportSub2API, nil) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(s2a.Files[0].Data), `"platform": "openai"`) || !strings.Contains(string(s2a.Files[0].Data), "chatgpt_account_id") { + t.Fatalf("%s", s2a.Files[0].Data) + } + cpa, err := ExportLogins("codex", ExportCLIProxy, nil) + if err != nil || len(cpa.Files) != 2 || !strings.HasSuffix(cpa.Files[0].Name, "-plus.json") { + t.Fatalf("%+v %v", cpa, err) + } + for name, files := range map[string][]ExportFile{"sub2api": s2a.Files, "cliproxyapi": cpa.Files} { + claudeHome(t) + var texts []string + for _, f := range files { + texts = append(texts, string(f.Data)) + } + rs, err := ImportLogins(context.Background(), "codex", texts) + if err != nil { + t.Fatal(name, err) + } + got := heldTokens("codex") + if len(got) != 2 { + t.Fatalf("%s: back as %v (%+v)", name, got, rs) + } + for _, who := range got { + if !strings.Contains(who, "example.com") || !strings.HasSuffix(who, "/acct-1") && !strings.HasSuffix(who, "/acct-2") { + t.Fatalf("%s: %v", name, got) + } + } + } +} + +// An account with only an access token, or a setup-token, can't be taken +// out: said, never written as a file that imports as nothing. +func TestExportSkipsWhatHasNoRefreshToken(t *testing.T) { + claudeHome(t) + if _, err := ExportLogins("claude", ExportSub2API, nil); err == nil { + t.Fatal("an export of no accounts") + } + if _, err := ExportLogins("gemini", ExportSub2API, nil); err == nil { + t.Fatal("gemini exported") + } + if _, err := ExportLogins("claude", "csv", nil); err == nil { + t.Fatal("csv exported") + } +} diff --git a/internal/provider/login_import.go b/internal/provider/login_import.go index 16b76cabe..464c7b3aa 100644 --- a/internal/provider/login_import.go +++ b/internal/provider/login_import.go @@ -168,6 +168,7 @@ func loginEntry(agent string, x map[string]any) loginImport { e.refreshToken = jsonStr(src, "refresh_token", "refreshToken") e.accountID = jsonStr(src, "account_id", "accountId") e.scopes = importScopes(src["scopes"]) + e.claudeAccount, e.claudeOrg = jsonStr(x, "account_uuid"), jsonStr(x, "org_uuid") if agent == "claude" { e.expiresAt = jsonMillis(src, "expiresAt") }