accounts: export ChatGPT and Claude accounts as Sub2API or CLIProxyAPI files (heyiwei5 and Rk1ngggg on X)

WIP commit before the full checks; body rewritten at ship.
This commit is contained in:
yetone
2026-11-11 04:07:09 +08:00
parent 3ebb1ba2cb
commit b9f8548d22
14 changed files with 1037 additions and 3 deletions
File diff suppressed because one or more lines are too long
+92
View File
@@ -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 <codex|claude> [<email>...] [--format sub2api|cliproxyapi] [--to <folder>] [--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
+104
View File
@@ -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")
}
}
+1
View File
@@ -106,6 +106,7 @@ const usage = `magpie — one place to pick every agent's model
magpie accounts add copilot [--host <name>.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 <codex|claude|antigravity|factory> <file>... [--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 <codex|claude> [<email>...] [--format sub2api|cliproxyapi] [--to <folder>] [--yes] write accounts as a file Sub2API, CLIProxyAPI or magpie imports (0600; holds live sign-ins)
magpie accounts import codex <file>... --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 <email> [on|off] keep a ChatGPT account access token only, or let magpie renew its sign-in again
magpie accounts switch <agent> <email|name> sign the agent in to another of them, by its email or the name you gave it
+67
View File
@@ -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;
};
+5 -2
View File
@@ -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);
+16
View File
@@ -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",
+86
View File
@@ -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")
}
}
+51
View File
@@ -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
+96
View File
@@ -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, []);
});
}
}
+1 -1
View File
@@ -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 () => {
+324
View File
@@ -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: <type>-<email>.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
}
+192
View File
@@ -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")
}
}
+1
View File
@@ -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")
}