diff --git a/accounts_cli.go b/accounts_cli.go index 142da1dc5..7fcdced57 100644 --- a/accounts_cli.go +++ b/accounts_cli.go @@ -1,17 +1,23 @@ package main import ( + "context" "fmt" + "os" + "os/exec" + "os/signal" + "runtime" "strings" "github.com/yetone/magpie/internal/provider" ) -// accountsCmd: `magpie accounts [agent]`, `magpie accounts switch|forget ` +// accountsCmd: `magpie accounts [agent]`, `magpie accounts add `, +// `magpie accounts switch|forget ` // — the Claude Code and Codex subscriptions magpie remembers, and switching // the agent between them. func accountsCmd(args []string) error { - const usage = "usage: magpie accounts [claude|codex] | magpie accounts switch|forget " + const usage = "usage: magpie accounts [claude|codex] | magpie accounts add | magpie accounts switch|forget " agentID := func(s string) (string, error) { switch strings.ToLower(s) { case "claude", "cc": @@ -21,6 +27,16 @@ func accountsCmd(args []string) error { } return "", fmt.Errorf("%q: only Claude Code and Codex accounts can be switched\n%s", s, usage) } + if len(args) > 1 && args[1] == "add" { + if len(args) != 3 { + return fmt.Errorf("%s", usage) + } + id, err := agentID(args[2]) + if err != nil { + return err + } + return addAccount(id) + } if len(args) > 1 && (args[1] == "switch" || args[1] == "forget") { if len(args) != 4 { return fmt.Errorf("%s", usage) @@ -52,7 +68,7 @@ func accountsCmd(args []string) error { } ls := provider.Logins(which) if len(ls) == 0 { - fmt.Println(muted.Render("no accounts yet ·"), "sign in to Claude Code or Codex and magpie remembers the account") + fmt.Println(muted.Render("no accounts yet ·"), "add one: magpie accounts add ") return nil } for _, l := range ls { @@ -66,6 +82,49 @@ func accountsCmd(args []string) error { } fmt.Printf("%s%-7s %s%s\n", mark, l.Agent, l.User, plan) } - fmt.Println(faint.Render(" add one: sign in to it in the agent (codex login · claude → /login); switch: magpie accounts switch ")) + fmt.Println(faint.Render(" add one: magpie accounts add · switch: magpie accounts switch ")) return nil } + +// addAccount signs in to one more subscription in the browser, the way the +// window's "Add account" does. +func addAccount(agentID string) error { + st, err := provider.StartSignIn(agentID) + if err != nil { + return err + } + fmt.Println("Finish signing in in your browser. If it didn't open, go to:") + fmt.Println(faint.Render(st.URL)) + openInBrowser(st.URL) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + st, err = provider.WaitSignIn(ctx, st.ID) + if err != nil { + return err + } + switch st.State { + case "done": + if st.Using { + fmt.Println(green.Render("✓"), agentID, "is signed in as", st.User) + } else { + fmt.Println(green.Render("✓"), "added", st.User, muted.Render("· use it: magpie accounts switch "+agentID+" "+st.User)) + } + return nil + case "failed": + return fmt.Errorf("sign-in didn't finish: %s", st.Error) + } + return fmt.Errorf("sign-in canceled") +} + +func openInBrowser(url string) { + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "windows": + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url) + default: + cmd = exec.Command("xdg-open", url) + } + _ = cmd.Start() +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index fb79dd55a..168b76b5b 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -511,9 +511,39 @@ body.window .foot { padding-left: 18px; } .acct { display: flex; align-items: center; gap: 8px; min-height: 26px; font-size: 12.5px; } .acct .n { font-weight: 500; } .acct .plan { color: var(--muted); font-size: 11.5px; padding: 1px 6px; border-radius: 5px; background: var(--pill-hover); } -.logins { display: grid; gap: 2px; } -.logins .acct .grow { flex: 1; } -.logins .none { color: var(--muted); font-size: 12.5px; min-height: 26px; display: flex; align-items: center; } +/* a subscription's accounts: the one in use first, a way to add another */ +.accts { display: grid; border: 1px solid var(--line); border-radius: 10px; background: var(--card); overflow: hidden; } +.acc { display: flex; align-items: center; gap: 9px; min-height: 38px; padding: 5px 8px 5px 11px; font-size: 12.5px; text-align: left; } +.acc + .acc, .accts .signing { border-top: 1px solid var(--line-2); } +.acc .n { font-weight: 500; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.acc .plan { color: var(--muted); font-size: 11px; padding: 1px 6px; border-radius: 5px; background: var(--pill); white-space: nowrap; } +.acc .grow { flex: 1; } +.acc .dot { width: 16px; height: 16px; flex: none; border-radius: 50%; display: grid; place-items: center; box-shadow: inset 0 0 0 1.5px var(--faint); color: var(--muted); } +.acc.in-use .dot { background: var(--fg); box-shadow: none; color: var(--card); } +.acc .using { font-size: 11px; color: var(--fg-2); padding: 2px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px var(--line); } +.acc .text.quiet { color: var(--muted); opacity: 0; transition: opacity .15s; } +.acc:hover .text.quiet, .acc .text.quiet:focus-visible { opacity: 1; } +.acc.new { animation: sub-in .5s cubic-bezier(.2, .8, .2, 1); } +.acc.new .dot { animation: copy-pop .45s cubic-bezier(.2, .8, .2, 1); } +@keyframes sub-in { from { opacity: 0; transform: translateY(-4px); background: var(--pill-hover); } } +.acc.add { width: 100%; color: var(--fg-2); background: none; border: 0 solid var(--line-2); cursor: default; } +.acc + .acc.add { border-top-width: 1px; } +.acc.add .dot { box-shadow: inset 0 0 0 1.5px var(--faint); border-radius: 50%; } +.acc.add .n { font-weight: 450; } +.acc.add:hover { background: var(--card-2); color: var(--fg); } +.acc.add:hover .dot { box-shadow: inset 0 0 0 1.5px var(--fg); color: var(--fg); } + +/* a sign-in under way, waiting on the browser */ +.signing { display: flex; align-items: flex-start; gap: 11px; padding: 11px 10px 11px 12px; font-size: 12.5px; background: var(--card-2); animation: fade-in .2s; } +.sheet .signing { margin-top: 8px; border: 1px solid var(--line); border-radius: 10px; } +.signing .tt { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; line-height: 1.35; } +.signing .n { font-weight: 500; } +.signing .s { color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; } +.signing > .text { margin: -3px 0; } +.signing .acts { display: flex; gap: 2px; margin: 2px 0 0 -4px; } +.signing .acts .link { color: var(--fg-2); } +.signing .spinner { width: 16px; height: 16px; flex: none; margin-top: 1px; border-radius: 50%; border: 1.75px solid var(--line); border-top-color: var(--fg); animation: spin .8s linear infinite; } +.signing .mark { width: 16px; height: 16px; flex: none; margin-top: 1px; border-radius: 50%; display: grid; place-items: center; background: var(--fg); color: var(--card); font-size: 11px; font-weight: 700; } .fallback { display: grid; gap: 6px; } .fallback .fbl { display: grid; gap: 2px; } .fbrow { display: flex; align-items: center; gap: 8px; min-height: 28px; font-size: 12.5px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9e61b70a8..6ded91964 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1078,6 +1078,16 @@ function renderAdd() { const f = presetQuery.trim().toLowerCase(); const hit = (pr) => !f || pr.name.toLowerCase().includes(f) || pr.id.includes(f) || hostOf(pr.chat || pr.responses || pr.anthropic).includes(f) || (pr.note || "").toLowerCase().includes(f); let any = false; + const subs = SUBS.filter((x) => !f || x.name.toLowerCase().includes(f) || x.agent.includes(f) || "subscription".includes(f)); + if (subs.length) { + any = true; + tiles.append(el("div", "kind", t("Subscriptions · sign in, no key"))); + const grid = el("div", "grid"); + for (const x of subs) grid.append(subTile(x)); + tiles.append(grid); + const w = subs.find((x) => signing?.agent === x.agent); + if (w) tiles.append(renderSigning(w)); + } for (const [kind, title] of [["vendor", "Vendors"], ["relay", "Relays · many vendors behind one key"], ["local", "On this machine"]]) { const ps = providers.presets.filter((p) => p.kind === kind && hit(p)); if (!ps.length && !(kind === "local" && !f)) continue; @@ -1109,6 +1119,20 @@ function renderAdd() { return editing && typeof editing === "object" ? renderEditor(null, editing.preset) : null; } +// subTile adds a subscription: one more account when the agent has some. +function subTile(x) { + const have = providers.providers.find((p) => p.account?.agent === x.agent); + const n = have ? (have.account.logins?.length || 1) : 0; + const b = el("button", "tile" + (signing?.agent === x.agent ? " on" : "")); + b.append(icon(x.icon)); + const tt = el("span", "tt"); + tt.append(el("span", "n", t("{name} subscription", { name: x.name })), + el("span", "s", n ? t(n === 1 ? "1 account · add another" : "{n} accounts · add another", { n }) : x.plans)); + b.append(tt); + b.onclick = () => startSignIn(x.agent); + return b; +} + function tile(pr) { const b = el("button", "tile" + (pr.added ? " added" : "") + (editing?.preset === pr.id ? " on" : "")); b.append(icon(pr.icon || "generic")); @@ -1408,10 +1432,13 @@ function renderEditor(p, presetID) { if (p?.account) { // the sign-in belongs to the agent; magpie only borrows it const a = p.account; - const acct = el("div", "acct"); - acct.append(icon(a.agentIcon), el("span", "n", a.user), el("span", "plan", accountPlan(a))); - ed.append(...field(t("Account"), acct, t("{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.", { agent: a.agentName }))); - if (a.logins) ed.append(...field(t("Other accounts"), renderLogins(a), t("To add one, sign in to it in {agent} ({how}); magpie remembers every account it sees there. Sessions already running keep their account until restarted.", { agent: a.agentName, how: a.agent === "codex" ? "codex login" : "claude → /login" }))); + if (subOf(a.agent)) { + ed.append(...field(t("Accounts"), renderAccounts(a), t("{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.", { agent: a.agentName }))); + } else { + const acct = el("div", "acct"); + acct.append(icon(a.agentIcon), el("span", "n", a.user), el("span", "plan", accountPlan(a))); + ed.append(...field(t("Account"), acct, t("{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.", { agent: a.agentName }))); + } ed.append(...field(t("Models"), renderModels(p), "")); ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p))); ed.append(...field(t("Endpoints"), renderEndpoints(p, p))); @@ -1773,24 +1800,134 @@ function fallbackHint(p) { return t("When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.", { name: p.name }); } -// renderLogins: the agent's other accounts magpie remembers, each one a -// click away from being the one the agent is signed in to. -function renderLogins(a) { - const list = el("div", "logins"); - const others = a.logins.filter((l) => !l.active); - if (!others.length) list.append(el("div", "none", t("None yet"))); - for (const l of others) { - const row = el("div", "acct"); - row.append(el("span", "n", l.user), el("span", "plan", accountPlan({ agent: a.agent, plan: l.plan })), el("span", "grow")); - const forget = el("button", "text", t("Forget")); - forget.title = t("magpie forgets this account's sign-in; the account itself is untouched"); - forget.onclick = () => providerAction("forget", { agent: a.agent, user: l.user }, t("{user} forgotten", { user: l.user }), "login/"); - const use = el("button", "text", t("Switch")); - use.title = t("Sign {agent} in to this account", { agent: a.agentName }); - use.onclick = () => { use.classList.add("busy"); providerAction("switch", { agent: a.agent, user: l.user }, t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }), "login/"); }; - row.append(forget, use); +// ---------- subscriptions ---------- +// +// A Claude or ChatGPT subscription is added here, not in a terminal: magpie +// opens the vendor's own sign-in in the browser, takes the account when it +// comes back, and lists it with the others — any of them one click from +// being the one in use. + +const SUBS = [ + { agent: "claude", name: "Claude", icon: "claude-color", plans: "Pro · Max · Team" }, + { agent: "codex", name: "ChatGPT", icon: "openai", plans: "Plus · Pro · Business" }, +]; +const subOf = (agent) => SUBS.find((x) => x.agent === agent); +let signing = null; // the sign-in under way: { id, agent, url, state, error } +let justAdded = ""; // the account that just came in, to greet it + +async function startSignIn(agent) { + if (signing?.state === "waiting") api("signin/" + signing.id + "/cancel", {}).catch(() => {}); + signing = { agent, state: "starting" }; + renderProviders(); + try { + signing = await api("signin", { agent }); + renderProviders(); + followSignIn(signing.id); + } catch (e) { + signing = { agent, state: "failed", error: e.message }; + renderProviders(); + } +} + +async function followSignIn(id) { + while (signing?.id === id && signing.state === "waiting") { + await new Promise((r) => setTimeout(r, 800)); + let st; + try { st = await api("signin/" + id); } catch { continue; } + if (signing?.id !== id || st.state === "waiting") continue; + if (st.state === "done") { + signing = null; + justAdded = st.user; + providers = await api("providers"); + const p = providers.providers.find((x) => x.account?.agent === st.agent); + if (p) { editing = p.id; draft = null; adding = false; presetQuery = ""; } + renderProviders(); + status(st.using ? t("Signed in as {user}", { user: st.user }) : t("{user} added — switch to it any time", { user: st.user }), "ok"); + state = await api("state"); + renderAgents(); + setTimeout(() => { justAdded = ""; }, 2000); + return; + } + signing = st.state === "canceled" ? null : st; + renderProviders(); + } +} + +function cancelSignIn() { + if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); + signing = null; + renderProviders(); +} + +// renderSigning: where a sign-in stands, in place of the button that +// started it — waiting on the browser, or what went wrong. +function renderSigning(sub) { + const box = el("div", "signing" + (signing.state === "failed" ? " failed" : "")); + const tt = el("span", "tt"); + if (signing.state === "failed") { + box.append(el("span", "mark", "!")); + tt.append(el("span", "n", t("Sign-in didn't finish")), el("span", "s", signing.error || "")); + box.append(tt); + const again = el("button", "text primary", t("Try again")); + again.onclick = () => startSignIn(sub.agent); + const close = el("button", "text", t("Cancel")); + close.onclick = cancelSignIn; + box.append(close, again); + return box; + } + box.append(el("span", "spinner")); + tt.append(el("span", "n", t("Finish signing in to {name} in your browser", { name: sub.name })), + el("span", "s", t("magpie opened the sign-in page. The account shows up here as soon as you're done."))); + box.append(tt); + if (signing.url) { + const acts = el("span", "acts"); + const open = el("button", "link", t("Open again")); + open.onclick = () => api("open", { url: signing.url }).catch(() => {}); + const cp = el("button", "link", t("Copy link")); + cp.onclick = () => copy(signing.url, t("Sign-in link"), cp); + acts.append(open, cp); + tt.append(acts); + } + const x = el("button", "text", t("Cancel")); + x.onclick = cancelSignIn; + box.append(x); + return box; +} + +// renderAccounts: every account of an agent magpie has, the one in use +// first, and a way to add another. +function renderAccounts(a) { + const sub = subOf(a.agent); + const list = el("div", "accts"); + let ls = a.logins?.length ? [...a.logins] : [{ user: a.user, plan: a.plan, active: true }]; + ls.sort((x, y) => (y.active ? 1 : 0) - (x.active ? 1 : 0)); + for (const l of ls) { + const row = el("div", "acc" + (l.active ? " in-use" : "") + (l.user === justAdded ? " new" : "")); + const dot = el("span", "dot"); + if (l.active) dot.append(svg(CHECK, 10, 2.2)); + row.append(dot, el("span", "n", l.user), el("span", "plan", accountPlan({ agent: a.agent, plan: l.plan })), el("span", "grow")); + if (l.active) { + row.append(el("span", "using", t("In use"))); + } else { + const forget = el("button", "text quiet", t("Remove")); + forget.title = t("magpie forgets this account's sign-in; the account itself is untouched"); + forget.onclick = () => providerAction("forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user }), "login/"); + const use = el("button", "text", t("Use")); + use.title = t("Sign {agent} in to this account", { agent: a.agentName }); + use.onclick = () => { use.classList.add("busy"); providerAction("switch", { agent: a.agent, user: l.user }, t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }), "login/"); }; + row.append(forget, use); + } list.append(row); } + if (signing?.agent === a.agent) list.append(renderSigning(sub)); + else { + const add = el("button", "acc add"); + const ic = el("span", "dot"); + ic.append(svg(PLUS, 10, 1.8)); + add.append(ic, el("span", "n", t("Add another {name} account", { name: sub.name }))); + add.onclick = () => startSignIn(a.agent); + list.append(add); + } return list; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5153e35fe..21c48a784 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -120,7 +120,7 @@ const I18N = { "Anthropic compatible": "Anthropic 兼容", "the root URL, what ANTHROPIC_BASE_URL would take": "根地址,即 ANTHROPIC_BASE_URL 的值", "Account": "账号", - "Other accounts": "其他账号", + "Accounts": "账号", "Fallback": "备用", "add a model: filter, or type provider/model…": "添加模型:筛选,或输入 provider/model…", "No provider serves {id} now; it is skipped": "现在没有供应商提供 {id},会跳过它", @@ -128,12 +128,25 @@ const I18N = { "Enter adds {id}": "回车添加 {id}", "No model matches": "没有匹配的模型", "When {name} is out of quota, rate limited or down, a request goes to these instead, top first. It only happens before any of the reply is sent, and {name} then sits out a minute.": "当 {name} 额度用完、被限流或不可用时,请求会按从上到下的顺序改发给这些模型。只在回复开始发送之前切换,之后 {name} 会暂停一分钟再用。", - "To add one, sign in to it in {agent} ({how}); magpie remembers every account it sees there. Sessions already running keep their account until restarted.": "要添加账号,在 {agent} 里登录它({how});magpie 会记住在那里见过的每个账号。已在运行的会话会保持原账号,重启后才切换。", - "None yet": "暂无", - "Forget": "忘记", + "{agent} and the gateway use the one in use. Sessions already running keep theirs until restarted.": "{agent} 和网关使用标记为「使用中」的账号。已在运行的会话保持原账号,重启后切换。", + "In use": "使用中", + "Use": "使用", + "Add another {name} account": "添加另一个 {name} 账号", + "Subscriptions · sign in, no key": "订阅 · 登录即可,无需 Key", + "{name} subscription": "{name} 订阅", + "1 account · add another": "1 个账号 · 再添加一个", + "{n} accounts · add another": "{n} 个账号 · 再添加一个", + "Finish signing in to {name} in your browser": "请在浏览器中完成 {name} 登录", + "magpie opened the sign-in page. The account shows up here as soon as you're done.": "magpie 已打开登录页面,完成后账号会立即出现在这里。", + "Open again": "重新打开", + "Copy link": "复制链接", + "Sign-in link": "登录链接", + "Sign-in didn't finish": "登录未完成", + "Try again": "重试", + "Signed in as {user}": "已登录 {user}", + "{user} added — switch to it any time": "已添加 {user},随时可以切换", + "{user} removed": "已移除 {user}", "magpie forgets this account's sign-in; the account itself is untouched": "magpie 忘掉这个账号的登录信息;账号本身不受影响", - "{user} forgotten": "已忘记 {user}", - "Switch": "切换", "Sign {agent} in to this account": "让 {agent} 登录到这个账号", "{agent} is now signed in as {user}": "{agent} 已切换为 {user}", "{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登录信息,读取自它自己的文件。在那里退出登录,此供应商即消失。", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index c24d93859..80dae162b 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -353,6 +353,34 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) { } writeJSON(rw, providersState(gw)) }) + // Adding a subscription: magpie opens the vendor's sign-in in the + // browser and the window follows it until the account is in. + mux.HandleFunc("POST /api/signin", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Agent string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + st, err := provider.StartSignIn(in.Agent) + if err != nil { + fail(rw, err) + return + } + w.OpenURL(st.URL) + writeJSON(rw, st) + }) + mux.HandleFunc("GET /api/signin/{id}", func(rw http.ResponseWriter, r *http.Request) { + st, ok := provider.SignInStatus(r.PathValue("id")) + if !ok { + http.NotFound(rw, r) + return + } + writeJSON(rw, st) + }) + mux.HandleFunc("POST /api/signin/{id}/cancel", func(rw http.ResponseWriter, r *http.Request) { + provider.CancelSignIn(r.PathValue("id")) + rw.WriteHeader(http.StatusNoContent) + }) mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) { var in struct{ URL string } _ = json.NewDecoder(r.Body).Decode(&in) diff --git a/internal/provider/account.go b/internal/provider/account.go index db7974994..a5dc7bea3 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -574,10 +574,11 @@ func claimString(m map[string]any, keys ...string) string { // ---- Codex CLI: a ChatGPT account ---------------------------------------------- -const ( - codexClientID = "app_EMoamEEZ73f0CkXaXp7hrann" // Codex CLI's own OAuth client - codexTokenURL = "https://auth.openai.com/oauth/token" -) +const codexClientID = "app_EMoamEEZ73f0CkXaXp7hrann" // Codex CLI's own OAuth client + +// codexTokenURL is where ChatGPT's tokens are issued and refreshed; a var +// so tests can point it elsewhere. +var codexTokenURL = "https://auth.openai.com/oauth/token" // CodexBase is where a ChatGPT account's Codex requests go; a var so tests // can point it elsewhere. diff --git a/internal/provider/signin.go b/internal/provider/signin.go new file mode 100644 index 000000000..41d8964a3 --- /dev/null +++ b/internal/provider/signin.go @@ -0,0 +1,511 @@ +package provider + +// Adding a subscription from magpie itself. magpie runs the vendor's own +// browser sign-in — the one Claude Code's /login and `codex login` run, with +// their OAuth clients — takes the tokens at a callback on this machine, and +// keeps the account with the others in logins.json. An agent that has no +// account yet is signed in to it straight away; otherwise it stays one +// click away, beside the rest. + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "html" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// The vendors' sign-in pages; vars so tests can point them elsewhere. +var ( + claudeAuthorizeURL = "https://claude.com/cai/oauth/authorize" + codexAuthorizeURL = "https://auth.openai.com/oauth/authorize" + // codexCallbackAddr is fixed: OpenAI only sends Codex's client back to + // port 1455. + codexCallbackAddr = "127.0.0.1:1455" +) + +// claudeScopes are what Claude Code asks for at /login. +const claudeScopes = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload user:plugins" + +const codexScopes = "openid profile email offline_access api.connectors.read api.connectors.invoke" + +// signInTimeout is how long a sign-in waits for the browser. +var signInTimeout = 10 * time.Minute + +// SignInState is where a sign-in stands, for the window to show. +type SignInState struct { + ID string `json:"id"` + Agent string `json:"agent"` + URL string `json:"url"` // the vendor's page, to open or copy + State string `json:"state"` // waiting, done, failed or canceled + User string `json:"user,omitempty"` // the account, once done + Plan string `json:"plan,omitempty"` // + Using bool `json:"using,omitempty"` // the agent was signed in to it too + Error string `json:"error,omitempty"` +} + +type signInFlow struct { + mu sync.Mutex + st SignInState + verifier string + state string + redirect string + srv *http.Server + done chan struct{} +} + +var signIns = struct { + sync.Mutex + m map[string]*signInFlow +}{m: map[string]*signInFlow{}} + +func randomToken(n int) string { + b := make([]byte, n) + _, _ = rand.Read(b) + return base64.RawURLEncoding.EncodeToString(b) +} + +// StartSignIn begins adding an account to an agent: open the returned URL +// in a browser and the rest happens on its own; SignInStatus follows it. +func StartSignIn(agent string) (SignInState, error) { + s := &signInFlow{verifier: randomToken(48), state: randomToken(24), done: make(chan struct{})} + s.st = SignInState{ID: randomToken(9), Agent: agent, State: "waiting"} + sum := sha256.Sum256([]byte(s.verifier)) + challenge := base64.RawURLEncoding.EncodeToString(sum[:]) + + var ln net.Listener + var err error + q := url.Values{} + switch agent { + case "claude": + if ln, err = net.Listen("tcp", "127.0.0.1:0"); err != nil { + return SignInState{}, err + } + s.redirect = fmt.Sprintf("http://localhost:%d/callback", ln.Addr().(*net.TCPAddr).Port) + q.Set("code", "true") + q.Set("client_id", claudeClientID) + q.Set("response_type", "code") + q.Set("redirect_uri", s.redirect) + q.Set("scope", claudeScopes) + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + q.Set("state", s.state) + s.st.URL = claudeAuthorizeURL + "?" + q.Encode() + case "codex": + if ln, err = listenCodexCallback(); err != nil { + return SignInState{}, err + } + _, port, _ := net.SplitHostPort(codexCallbackAddr) + s.redirect = "http://localhost:" + port + "/auth/callback" + q.Set("response_type", "code") + q.Set("client_id", codexClientID) + q.Set("redirect_uri", s.redirect) + q.Set("scope", codexScopes) + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + q.Set("id_token_add_organizations", "true") + q.Set("codex_cli_simplified_flow", "true") + q.Set("state", s.state) + q.Set("originator", "codex_cli_rs") + s.st.URL = codexAuthorizeURL + "?" + q.Encode() + default: + return SignInState{}, fmt.Errorf("magpie can't sign in to %s accounts", agent) + } + + mux := http.NewServeMux() + mux.HandleFunc("/", s.callback) + s.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} + go func() { _ = s.srv.Serve(ln) }() + go func() { + select { + case <-s.done: + case <-time.After(signInTimeout): + s.finish(SignInState{State: "failed", Error: "the sign-in timed out; start it again"}) + } + }() + + signIns.Lock() + // only one sign-in per agent at a time: a newer one replaces the older + for id, o := range signIns.m { + if o.st.Agent == agent { + o.finish(SignInState{State: "canceled"}) + delete(signIns.m, id) + } + } + signIns.m[s.st.ID] = s + signIns.Unlock() + return s.status(), nil +} + +// listenCodexCallback takes Codex's callback port. A `codex login` left +// waiting there is asked to stop first, the way Codex itself does it. +func listenCodexCallback() (net.Listener, error) { + for i := 0; i < 10; i++ { + ln, err := net.Listen("tcp", codexCallbackAddr) + if err == nil { + return ln, nil + } + if i == 0 { + c := http.Client{Timeout: 2 * time.Second} + if resp, err := c.Get("http://" + codexCallbackAddr + "/cancel"); err == nil { + resp.Body.Close() + } + } + time.Sleep(200 * time.Millisecond) + } + return nil, errors.New("port 1455, where ChatGPT sends the sign-in back, is busy; close any other Codex sign-in and try again") +} + +// SignInStatus reports on a sign-in StartSignIn began. +func SignInStatus(id string) (SignInState, bool) { + signIns.Lock() + s, ok := signIns.m[id] + signIns.Unlock() + if !ok { + return SignInState{}, false + } + return s.status(), true +} + +// CancelSignIn stops waiting for the browser. +func CancelSignIn(id string) { + signIns.Lock() + s, ok := signIns.m[id] + signIns.Unlock() + if ok { + s.finish(SignInState{State: "canceled"}) + } +} + +// WaitSignIn blocks until a sign-in is over, for the command line. +func WaitSignIn(ctx context.Context, id string) (SignInState, error) { + signIns.Lock() + s, ok := signIns.m[id] + signIns.Unlock() + if !ok { + return SignInState{}, errors.New("no such sign-in") + } + select { + case <-s.done: + return s.status(), nil + case <-ctx.Done(): + s.finish(SignInState{State: "canceled"}) + return s.status(), ctx.Err() + } +} + +func (s *signInFlow) status() SignInState { + s.mu.Lock() + defer s.mu.Unlock() + return s.st +} + +// finish records the outcome once and lets the callback server go. +func (s *signInFlow) finish(out SignInState) bool { + s.mu.Lock() + if s.st.State != "waiting" { + s.mu.Unlock() + return false + } + out.ID, out.Agent, out.URL = s.st.ID, s.st.Agent, s.st.URL + s.st = out + s.mu.Unlock() + close(s.done) + go func() { + // after the browser has had its page + time.Sleep(time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = s.srv.Shutdown(ctx) + }() + return true +} + +func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/callback", "/auth/callback": + case "/cancel": + s.finish(SignInState{State: "canceled"}) + w.WriteHeader(http.StatusNoContent) + return + default: + http.NotFound(w, r) + return + } + q := r.URL.Query() + if s.status().State != "waiting" { + signInPage(w, false, "This sign-in is over", "Start it again from magpie.") + return + } + if e := q.Get("error"); e != "" { + msg := q.Get("error_description") + if msg == "" { + msg = e + } + s.finish(SignInState{State: "failed", Error: msg}) + signInPage(w, false, "Sign-in didn't finish", msg) + return + } + if q.Get("state") != s.state || q.Get("code") == "" { + // not ours: someone else's page, or a stale tab + signInPage(w, false, "This link isn't from magpie's sign-in", "Start it again from magpie.") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + l, err := s.exchange(ctx, q.Get("code")) + if err == nil { + var using bool + if using, err = addLogin(l); err == nil { + s.finish(SignInState{State: "done", User: l.User, Plan: l.Plan, Using: using}) + signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", l.User)) + return + } + } + s.finish(SignInState{State: "failed", Error: err.Error()}) + signInPage(w, false, "Sign-in didn't finish", err.Error()) +} + +// exchange trades the code for tokens and makes them into a login. +func (s *signInFlow) exchange(ctx context.Context, code string) (savedLogin, error) { + if s.st.Agent == "codex" { + return codexExchange(ctx, code, s.verifier, s.redirect) + } + return claudeExchange(ctx, code, s.verifier, s.redirect, s.state) +} + +func postToken(ctx context.Context, tokenURL, ctype string, body []byte, out any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Content-Type", ctype) + req.Header.Set("Accept", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode != http.StatusOK { + var e struct { + Error any `json:"error"` + ErrorDescription string `json:"error_description"` + } + _ = json.Unmarshal(b, &e) + msg := e.ErrorDescription + if msg == "" { + if m, ok := e.Error.(map[string]any); ok { + msg, _ = m["message"].(string) + } else if s, ok := e.Error.(string); ok { + msg = s + } + } + if msg == "" { + msg = http.StatusText(resp.StatusCode) + } + return fmt.Errorf("the sign-in was refused (%d): %s", resp.StatusCode, msg) + } + return json.Unmarshal(b, out) +} + +func claudeExchange(ctx context.Context, code, verifier, redirect, state string) (savedLogin, error) { + body, _ := json.Marshal(map[string]string{"grant_type": "authorization_code", "code": code, + "redirect_uri": redirect, "client_id": claudeClientID, "code_verifier": verifier, "state": state}) + var tok struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresIn int64 `json:"expires_in"` + Scope string `json:"scope"` + Account struct { + UUID string `json:"uuid"` + Email string `json:"email_address"` + } `json:"account"` + Organization struct { + UUID string `json:"uuid"` + Name string `json:"name"` + } `json:"organization"` + } + if err := postToken(ctx, claudeTokenURL, "application/json", body, &tok); err != nil { + return savedLogin{}, err + } + if tok.AccessToken == "" || tok.RefreshToken == "" { + return savedLogin{}, errors.New("Claude sent back no token") + } + acct := map[string]any{"accountUuid": tok.Account.UUID, "emailAddress": tok.Account.Email, + "organizationUuid": tok.Organization.UUID} + if tok.Organization.Name != "" { + acct["organizationName"] = tok.Organization.Name + } + c := claudeCredentials{raw: map[string]any{}, OAuth: claudeAuth{ + AccessToken: tok.AccessToken, RefreshToken: tok.RefreshToken, + ExpiresAt: time.Now().Add(time.Duration(tok.ExpiresIn) * time.Second).UnixMilli(), + Scopes: strings.Fields(tok.Scope), + }} + // the plan comes with the profile, as it does for Claude Code + if p, err := claudeProfile(ctx, tok.AccessToken); err == nil { + c.OAuth.SubscriptionType = claudePlans[p.Organization.Type] + c.OAuth.RateLimitTier = p.Organization.RateLimitTier + if p.Account.Email != "" { + acct["emailAddress"] = p.Account.Email + } + if p.Account.DisplayName != "" { + acct["displayName"] = p.Account.DisplayName + } + if p.Organization.BillingType != "" { + acct["billingType"] = p.Organization.BillingType + } + acct["hasExtraUsageEnabled"] = p.Organization.ExtraUsage + } + email, _ := acct["emailAddress"].(string) + if email == "" { + return savedLogin{}, errors.New("Claude didn't say which account signed in") + } + auth, err := c.marshal() + if err != nil { + return savedLogin{}, err + } + profile, _ := json.Marshal(acct) + return savedLogin{Agent: "claude", User: email, Plan: c.OAuth.SubscriptionType, Auth: auth, Profile: profile}, nil +} + +// claudePlans names Claude's organization types the way Claude Code does. +var claudePlans = map[string]string{"claude_max": "max", "claude_pro": "pro", "claude_enterprise": "enterprise", "claude_team": "team"} + +type claudeProfileInfo struct { + Account struct { + Email string `json:"email"` + DisplayName string `json:"display_name"` + } `json:"account"` + Organization struct { + Type string `json:"organization_type"` + RateLimitTier string `json:"rate_limit_tier"` + BillingType string `json:"billing_type"` + ExtraUsage bool `json:"has_extra_usage_enabled"` + } `json:"organization"` +} + +func claudeProfile(ctx context.Context, token string) (claudeProfileInfo, error) { + var p claudeProfileInfo + req, err := http.NewRequestWithContext(ctx, http.MethodGet, claudeBase+"/api/oauth/profile", nil) + if err != nil { + return p, err + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return p, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return p, fmt.Errorf("profile: %s", resp.Status) + } + return p, json.NewDecoder(resp.Body).Decode(&p) +} + +func codexExchange(ctx context.Context, code, verifier, redirect string) (savedLogin, error) { + form := url.Values{"grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {redirect}, + "client_id": {codexClientID}, "code_verifier": {verifier}} + var tok struct { + IDToken string `json:"id_token"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + } + if err := postToken(ctx, codexTokenURL, "application/x-www-form-urlencoded", []byte(form.Encode()), &tok); err != nil { + return savedLogin{}, err + } + if tok.AccessToken == "" || tok.RefreshToken == "" || tok.IDToken == "" { + return savedLogin{}, errors.New("ChatGPT sent back no token") + } + id := jwtClaims(tok.IDToken) + user := claimString(id, "email") + if user == "" { + return savedLogin{}, errors.New("ChatGPT didn't say which account signed in") + } + // auth.json as `codex login` writes it + auth, err := json.MarshalIndent(map[string]any{ + "OPENAI_API_KEY": nil, + "auth_mode": "chatgpt", + "tokens": map[string]string{"id_token": tok.IDToken, "access_token": tok.AccessToken, + "refresh_token": tok.RefreshToken, "account_id": claimString(id, "https://api.openai.com/auth", "chatgpt_account_id")}, + "last_refresh": time.Now().UTC().Format(time.RFC3339Nano), + }, "", " ") + if err != nil { + return savedLogin{}, err + } + return savedLogin{Agent: "codex", User: user, Plan: claimString(id, "https://api.openai.com/auth", "chatgpt_plan_type"), Auth: auth}, nil +} + +// addLogin keeps a freshly signed-in account. The agent is signed in to it +// too when it has no account yet, or had this one: the new tokens replace +// the old, so one refresh token stays in one place. +func addLogin(l savedLogin) (using bool, err error) { + loginsMu.Lock() + defer loginsMu.Unlock() + l.Seen = time.Now().UTC().Truncate(time.Second) + live, signedIn := liveLogin(l.Agent) + using = !signedIn || strings.EqualFold(live.User, l.User) + ls := readLogins() + if signedIn && !using { + // the current account, as fresh as the agent has it + live.Seen = l.Seen + ls = upsertLogin(ls, live) + } + if err := writeLogins(upsertLogin(ls, l)); err != nil { + return false, err + } + if using { + switch l.Agent { + case "codex": + err = writePrivate(codexAuthPath(), append(bytes.TrimSpace(l.Auth), '\n')) + case "claude": + err = putClaudeLogin(l) + } + if err != nil { + return false, err + } + } + loginsSeenAt = time.Time{} + forgetAccountCaches() + return using, nil +} + +// signInPage is what the browser shows at the end: magpie's, in its own +// quiet black and white, never the vendor's "return to the CLI". +func signInPage(w http.ResponseWriter, ok bool, title, msg string) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + if !ok { + w.WriteHeader(http.StatusBadRequest) + } + mark := `` + if !ok { + mark = `` + } + fmt.Fprintf(w, ` +magpie · %[1]s
%[3]s
+

%[1]s

%[2]s

magpie
`, html.EscapeString(title), html.EscapeString(msg), mark) +} diff --git a/internal/provider/signin_test.go b/internal/provider/signin_test.go new file mode 100644 index 000000000..5167e47a3 --- /dev/null +++ b/internal/provider/signin_test.go @@ -0,0 +1,198 @@ +package provider + +import ( + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// finishInBrowser does what the browser does after the vendor's page: +// come back to magpie's callback with a code. +func finishInBrowser(t *testing.T, st SignInState, code string) string { + t.Helper() + u, err := url.Parse(st.URL) + if err != nil { + t.Fatal(err) + } + q := u.Query() + back := q.Get("redirect_uri") + "?" + url.Values{"code": {code}, "state": {q.Get("state")}}.Encode() + resp, err := http.Get(strings.Replace(back, "localhost", "127.0.0.1", 1)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return string(b) +} + +func waitDone(t *testing.T, id string) SignInState { + t.Helper() + for i := 0; i < 100; i++ { + st, _ := SignInStatus(id) + if st.State != "waiting" { + return st + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("sign-in never finished") + return SignInState{} +} + +func TestClaudeSignInAddsAnAccount(t *testing.T) { + home := claudeHome(t) + var gotVerifier string + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/oauth/token": + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + if body["code"] != "the-code" || body["client_id"] != claudeClientID || body["grant_type"] != "authorization_code" { + w.WriteHeader(400) + return + } + gotVerifier = body["code_verifier"] + json.NewEncoder(w).Encode(map[string]any{ + "access_token": "sk-ant-oat01-new", "refresh_token": "sk-ant-ort01-new", "expires_in": 3600, + "scope": "user:inference user:profile", + "account": map[string]any{"uuid": "u-new", "email_address": "new@example.com"}, + }) + case "/api/oauth/profile": + if r.Header.Get("Authorization") != "Bearer sk-ant-oat01-new" { + w.WriteHeader(401) + return + } + json.NewEncoder(w).Encode(map[string]any{ + "account": map[string]any{"email": "new@example.com", "display_name": "New"}, + "organization": map[string]any{"organization_type": "claude_max", "rate_limit_tier": "default_claude_max_20x"}, + }) + default: + w.WriteHeader(404) + } + })) + defer fake.Close() + claudeTokenURL, claudeBase = fake.URL+"/v1/oauth/token", fake.URL + + // signed in already, to someone else: the new account is added beside it + cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "old@example.com"}}) + + st, err := StartSignIn("claude") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(st.URL, claudeAuthorizeURL+"?") || !strings.Contains(st.URL, "code_challenge_method=S256") { + t.Fatalf("url %s", st.URL) + } + page := finishInBrowser(t, st, "the-code") + if !strings.Contains(page, "signed in") { + t.Fatalf("page %s", page) + } + st = waitDone(t, st.ID) + if st.State != "done" || st.User != "new@example.com" || st.Plan != "max" || st.Using { + t.Fatalf("state %+v", st) + } + if gotVerifier == "" { + t.Fatal("no PKCE verifier sent") + } + users, active := loginUsers(Logins("claude")) + if strings.Join(users, ",") != "new@example.com,old@example.com" || active != "old@example.com" { + t.Fatalf("logins %v, active %q", users, active) + } + // and it's one click away + if err := SwitchLogin("claude", "new@example.com"); err != nil { + t.Fatal(err) + } + var c map[string]map[string]any + readJSON(cred, &c) + if c["claudeAiOauth"]["refreshToken"] != "sk-ant-ort01-new" || c["claudeAiOauth"]["subscriptionType"] != "max" { + t.Fatalf("credentials %v", c["claudeAiOauth"]) + } + b, _ := os.ReadFile(filepath.Join(home, ".claude.json")) + if !strings.Contains(string(b), `"displayName": "New"`) { + t.Fatalf(".claude.json %s", b) + } +} + +func TestCodexSignInSignsInWhenSignedOut(t *testing.T) { + home := claudeHome(t) + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + if r.Form.Get("code") != "cx" || r.Form.Get("client_id") != codexClientID || r.Form.Get("code_verifier") == "" { + w.WriteHeader(400) + json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant", "error_description": "bad code"}) + return + } + json.NewEncoder(w).Encode(map[string]any{ + "id_token": fakeJWT(map[string]any{"email": "cx@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus", "chatgpt_account_id": "acct-cx"}}), + "access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "r-cx", + }) + })) + defer fake.Close() + oldTok, oldAddr := codexTokenURL, codexCallbackAddr + t.Cleanup(func() { codexTokenURL, codexCallbackAddr = oldTok, oldAddr }) + codexTokenURL = fake.URL + ln, _ := net.Listen("tcp", "127.0.0.1:0") + codexCallbackAddr = ln.Addr().String() + ln.Close() + + // a bad code fails, and says why + st, err := StartSignIn("codex") + if err != nil { + t.Fatal(err) + } + finishInBrowser(t, st, "wrong") + if st = waitDone(t, st.ID); st.State != "failed" || !strings.Contains(st.Error, "bad code") { + t.Fatalf("state %+v", st) + } + time.Sleep(1200 * time.Millisecond) // the callback port is let go + + st, err = StartSignIn("codex") + if err != nil { + t.Fatal(err) + } + finishInBrowser(t, st, "cx") + if st = waitDone(t, st.ID); st.State != "done" || st.User != "cx@example.com" || !st.Using { + t.Fatalf("state %+v", st) + } + var a codexAuth + readJSON(filepath.Join(home, ".codex", "auth.json"), &a) + if a.Tokens.RefreshToken != "r-cx" || a.Tokens.AccountID != "acct-cx" { + t.Fatalf("auth.json %+v", a) + } + if _, active := loginUsers(Logins("codex")); active != "cx@example.com" { + t.Fatalf("active %q", active) + } +} + +func TestSignInIgnoresAForeignCallback(t *testing.T) { + claudeHome(t) + st, err := StartSignIn("claude") + if err != nil { + t.Fatal(err) + } + defer CancelSignIn(st.ID) + u, _ := url.Parse(st.URL) + back := strings.Replace(u.Query().Get("redirect_uri"), "localhost", "127.0.0.1", 1) + resp, err := http.Get(back + "?code=x&state=not-ours") + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if st, _ := SignInStatus(st.ID); st.State != "waiting" { + t.Fatalf("state %+v", st) + } + CancelSignIn(st.ID) + if st, _ := SignInStatus(st.ID); st.State != "canceled" { + t.Fatalf("state %+v", st) + } +} diff --git a/main.go b/main.go index 6ea628dc8..f929fc0d0 100644 --- a/main.go +++ b/main.go @@ -48,6 +48,7 @@ const usage = `magpie — one place to pick every agent's model magpie import [-y] add the provider a magpie://import?… link describes magpie models every model agents can pick, as provider/model magpie accounts [agent] the Claude Code and Codex subscriptions magpie remembers + magpie accounts add sign in to one more Claude or ChatGPT subscription magpie accounts switch sign the agent in to another of them magpie serve run the gateway alone (the app runs it too)