signin: a sign-in whose browser can't reach magpie finishes with the address pasted (Jorben on Discord: ChatGPT sign-in in Docker on a server never finished) — ChatGPT sends the browser back only to localhost:1455, which is the user's own computer, not the server, and magpie's paste field refused every built-in sign-in. Claude, Codex, Devin, Kiro (both steps of an AWS sign-in), Gemini, Antigravity and Zed now take the address the browser ended on, in the app and in magpie accounts add: only this sign-in's own port, path and state, traded through the same handler as the browser's, and once, whichever comes first. TestCodexSignInFromPastedAddress, TestPastedAddressAndCallbackFinishOnce, TestLoopbackSignInsTakePastedAddress and signin-paste-codex.test.cjs fail without the change.
This commit is contained in:
@@ -486,11 +486,15 @@ API key, and only then publish the port beyond 127.0.0.1.
|
||||
For the browser UI run the image with `magpie web --addr 0.0.0.0:3430 --no-open`
|
||||
in place of the default `serve`, and open
|
||||
`http://localhost:3430/?k=<key from docker logs magpie>` (set `MAGPIE_WEB_KEY`
|
||||
to keep one key across restarts). There you add providers and import
|
||||
sign-ins from a file; a subscription sign-in started in the container cannot
|
||||
finish, because the vendor sends the browser back to the container's own
|
||||
loopback, so sign in on a machine where magpie runs with a browser. Keys and
|
||||
sign-ins live in the volume, so a restart keeps them.
|
||||
to keep one key across restarts). There you add providers, sign in to
|
||||
subscriptions and import sign-ins from a file. The vendor sends a sign-in's
|
||||
browser back to `localhost` (ChatGPT to `http://localhost:1455/auth/callback?code=…`),
|
||||
which is your own machine, not the container, so that page won't load: copy
|
||||
its whole address from the address bar and paste it into the sign-in's
|
||||
*Callback URL* field. `docker exec -it magpie /magpie accounts add codex`
|
||||
does the same in a terminal: open the link it prints, then paste the address
|
||||
the browser ended on. Keys and sign-ins live in the volume, so a restart
|
||||
keeps them.
|
||||
|
||||
### Developing
|
||||
|
||||
|
||||
+1
-1
@@ -302,7 +302,7 @@ func addAccount(agentID string) error {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
if st.PasteCallback {
|
||||
fmt.Println("If the browser cannot return to magpie, paste its final callback URL here and press Enter:")
|
||||
fmt.Println("If the page the browser ends on won't load (magpie on a server or in Docker), paste its whole address here and press Enter:")
|
||||
id := st.ID
|
||||
go func() {
|
||||
lines := bufio.NewScanner(os.Stdin)
|
||||
|
||||
@@ -5273,7 +5273,7 @@ function renderSigning(sub) {
|
||||
if (signing.pasteCallback || signing.pasteCode) {
|
||||
const flow = signing;
|
||||
const what = flow.pasteCode ? t("Code") : t("Callback URL");
|
||||
if (!flow.pasteCode) tt.append(el("span", "s", t("If the browser cannot return to magpie, paste its final callback URL here.")));
|
||||
if (!flow.pasteCode) tt.append(el("span", "s", t("If the page the browser ends on won't load (magpie runs on a server or in Docker), copy its whole address and paste it here.")));
|
||||
const form = el("form", "callback-form");
|
||||
const url = input(flow.callbackURL || "", what);
|
||||
url.setAttribute("aria-label", what);
|
||||
|
||||
@@ -434,7 +434,7 @@ const I18N = {
|
||||
"Sign-in link": "登录链接",
|
||||
"Account in use": "正在使用的账号",
|
||||
"Open it in another browser or profile: copy it there": "要用其他浏览器或浏览器配置登录,复制此链接到那里打开",
|
||||
"If the browser cannot return to magpie, paste its final callback URL here.": "如果浏览器无法返回 magpie,请在此粘贴浏览器最终跳转的回调 URL。",
|
||||
"If the page the browser ends on won't load (magpie runs on a server or in Docker), copy its whole address and paste it here.": "如果登录后浏览器停在打不开的页面(magpie 运行在服务器或 Docker 里),请把那个页面的完整地址复制并粘贴到这里。",
|
||||
"Callback URL": "回调 URL",
|
||||
"Finish sign-in": "完成登录",
|
||||
"1 provider to bring over": "有 1 个供应商可导入",
|
||||
|
||||
@@ -441,6 +441,15 @@ with a click, with no left-border accent. The copy button beside it
|
||||
says it was copied. Open again is still there, and nothing scrolls. The
|
||||
checks run in English and Chinese, in Chromium and WebKit.
|
||||
|
||||
`signin-paste-codex.test.cjs` checks a ChatGPT sign-in finished from its
|
||||
pasted address, for a magpie the browser can't reach (on a server, in
|
||||
Docker). While the sign-in waits, the box says to copy the address of the
|
||||
page that won't load, and a Callback URL field sits inside it with no
|
||||
left-border accent. Finish sign-in stays off until something is typed, then
|
||||
posts the address to the sign-in's callback route once, and the account is
|
||||
named in the status line. Nothing scrolls. The checks run in English and
|
||||
Chinese, in Chromium and WebKit.
|
||||
|
||||
`tray-inuse.test.cjs` checks Settings, Usage in the menu bar. A
|
||||
subscription with two accounts lists "Account in use" before each account;
|
||||
one with a single account does not. Ticking it saves `claude|*`, the pill
|
||||
@@ -519,7 +528,7 @@ get their counts and don't move.
|
||||
With Node.js and Playwright available:
|
||||
|
||||
```sh
|
||||
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs
|
||||
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs
|
||||
```
|
||||
|
||||
If Playwright is installed outside the repository, set `NODE_PATH` to the
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A ChatGPT sign-in finished from its address (Jorben on Discord: magpie in
|
||||
// Docker on a cloud server, its web UI in his browser; ChatGPT sent the
|
||||
// browser back to http://localhost:1455/auth/callback?code=…, his own
|
||||
// machine, and the sign-in never finished). While the sign-in waits, the box
|
||||
// says what to do with a page that won't load, and a Callback URL field takes
|
||||
// its address: Finish sign-in posts it to the sign-in's callback route once,
|
||||
// and the account is signed in. No click moves the page. English and Chinese,
|
||||
// Chromium and WebKit; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const LINK = "https://auth.openai.com/oauth/authorize?client_id=app&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&state=st1";
|
||||
const BACK = "http://localhost:1455/auth/callback?code=ac_fake&scope=openid&state=st1";
|
||||
|
||||
function server(lang, posted) {
|
||||
let signing = { id: "cx1", agent: "codex", state: "waiting", url: LINK, pasteCallback: true };
|
||||
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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
|
||||
if (url.pathname === "/api/signin/cx1/callback") {
|
||||
posted.push(route.request().postDataJSON());
|
||||
signing = { ...signing, state: "done", user: "cx@example.com", using: true };
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
if (url.pathname === "/api/signin" || url.pathname === "/api/signin/cx1") return json(signing);
|
||||
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)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const W = {
|
||||
en: {
|
||||
say: "If the page the browser ends on won't load (magpie runs on a server or in Docker), copy its whole address and paste it here.",
|
||||
field: "Callback URL", finish: "Finish sign-in",
|
||||
},
|
||||
zh: {
|
||||
say: "如果登录后浏览器停在打不开的页面(magpie 运行在服务器或 Docker 里),请把那个页面的完整地址复制并粘贴到这里。",
|
||||
field: "回调 URL", finish: "完成登录",
|
||||
},
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
test(`${engine} ${lang}: a ChatGPT sign-in takes its pasted address`, async (t) => {
|
||||
const w = W[lang];
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
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}-signin-paste-codex.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posted = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posted));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator("#addProvider").click();
|
||||
const sheet = page.locator("#addSheet");
|
||||
await sheet.locator('.tile[data-pick="ChatGPT"]').click();
|
||||
const box = sheet.locator(".signing");
|
||||
await box.getByText(w.say).waitFor();
|
||||
const field = box.getByRole("textbox", { name: w.field });
|
||||
const finish = box.getByRole("button", { name: w.finish });
|
||||
assert(await field.isVisible());
|
||||
assert(await finish.isDisabled(), "nothing to finish with yet");
|
||||
|
||||
// the field and its button inside the box, with no left-border accent
|
||||
const fit = await box.evaluate((b) => {
|
||||
const r = b.getBoundingClientRect(), f = b.querySelector(".callback-form").getBoundingClientRect();
|
||||
return f.left >= r.left - 0.5 && f.right <= r.right + 0.5;
|
||||
});
|
||||
assert(fit, "the callback field fits its box");
|
||||
const stripes = await page.evaluate(() => [...document.querySelectorAll(".callback-form, .callback-form *")].filter((e) => {
|
||||
const s = getComputedStyle(e);
|
||||
return parseFloat(s.borderLeftWidth) > parseFloat(s.borderTopWidth) || (parseFloat(s.borderLeftWidth) && s.borderLeftColor !== s.borderTopColor);
|
||||
}).map((e) => e.className));
|
||||
assert.deepEqual(stripes, [], "no left-border accent");
|
||||
|
||||
const scrolls = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("#addSheet, #addSheet *")].filter((e) => e.scrollTop).map((e) => e.scrollTop)]);
|
||||
const before = await scrolls();
|
||||
await field.click();
|
||||
await field.fill(BACK);
|
||||
await finish.click();
|
||||
for (let i = 0; i < 40 && !posted.length; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posted, [{ url: BACK }]);
|
||||
// the sign-in over: the box gone, the account named
|
||||
await page.waitForFunction(() => document.querySelector("#status").textContent.includes("cx@example.com") && !document.querySelector("#addSheet .callback-form"));
|
||||
assert.equal(posted.length, 1, "posted once");
|
||||
assert.deepEqual(await scrolls(), before, "nothing scrolled");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,10 @@ func (s *signInFlow) kiroCallback(w http.ResponseWriter, r *http.Request) {
|
||||
fail("AWS sent back no code")
|
||||
return
|
||||
}
|
||||
if !s.claim() {
|
||||
kiroFinishing(w)
|
||||
return
|
||||
}
|
||||
var tok struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
@@ -181,6 +185,10 @@ func (s *signInFlow) kiroCallback(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
switch opt := q.Get("login_option"); opt {
|
||||
case "google", "github":
|
||||
if !s.claim() {
|
||||
kiroFinishing(w)
|
||||
return
|
||||
}
|
||||
var tok struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
@@ -222,7 +230,9 @@ func (s *signInFlow) kiroCallback(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
k.region, k.clientID, k.clientSecret = region, reg.ClientID, reg.ClientSecret
|
||||
k.provider = map[string]string{"builderid": "BuilderId", "awsidc": "Enterprise", "internal": "Internal"}[opt]
|
||||
s.mu.Lock()
|
||||
k.state, k.verifier = randomToken(24), randomToken(48)
|
||||
s.mu.Unlock()
|
||||
sum := sha256.Sum256([]byte(k.verifier))
|
||||
a := url.Values{}
|
||||
a.Set("response_type", "code")
|
||||
@@ -271,6 +281,12 @@ func (s *signInFlow) kiroCallback(w http.ResponseWriter, r *http.Request) {
|
||||
signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", user))
|
||||
}
|
||||
|
||||
// kiroFinishing answers a second callback while the first is traded for
|
||||
// the account: the browser's own, or its address pasted into magpie.
|
||||
func kiroFinishing(w http.ResponseWriter) {
|
||||
signInPage(w, false, "This sign-in is already finishing", "magpie shows the account when it's done.")
|
||||
}
|
||||
|
||||
// awsRedirect is where AWS sends the browser back.
|
||||
func (k *kiroFlow) awsRedirect() string {
|
||||
return fmt.Sprintf("http://127.0.0.1:%d/oauth/callback", k.port)
|
||||
|
||||
+136
-5
@@ -75,7 +75,10 @@ type signInFlow struct {
|
||||
kiro *kiroFlow
|
||||
site string // where to sign in, for an agent with more than one (ZCode: "zai" or "bigmodel")
|
||||
plugin string // a plugin's sign-in session, finished with the code pasted back
|
||||
done chan struct{}
|
||||
// claimed is a callback being traded for the account: the browser's own
|
||||
// or a pasted address, whichever came first
|
||||
claimed bool
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
var signIns = struct {
|
||||
@@ -312,6 +315,9 @@ func (s *signInFlow) begin() error {
|
||||
srv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
|
||||
s.mu.Lock()
|
||||
s.srv = srv
|
||||
// a browser that can't reach this port (magpie on a server, in
|
||||
// Docker) ends on a page that won't load: its address finishes it
|
||||
s.st.PasteCallback = true
|
||||
s.mu.Unlock()
|
||||
go func() { _ = srv.Serve(ln) }()
|
||||
}
|
||||
@@ -359,9 +365,8 @@ func CancelSignIn(id string) {
|
||||
}
|
||||
|
||||
// SubmitSignInCallback finishes a browser sign-in whose callback could not
|
||||
// reach this machine, or a plugin's with the code its page showed. No
|
||||
// built-in sign-in takes a callback now (PasteCallback is never set); the
|
||||
// route and the page's field stay for one that will.
|
||||
// reach this machine — the address the browser ended on, pasted — or a
|
||||
// plugin's with the code its page showed.
|
||||
func SubmitSignInCallback(id, raw string) error {
|
||||
signIns.Lock()
|
||||
s, ok := signIns.m[id]
|
||||
@@ -372,7 +377,128 @@ func SubmitSignInCallback(id, raw string) error {
|
||||
if s.plugin != "" {
|
||||
return s.pluginCode(raw)
|
||||
}
|
||||
return errors.New("this sign-in can't be finished from a pasted address")
|
||||
return s.pastedCallback(raw)
|
||||
}
|
||||
|
||||
// pastedCallback takes the address a sign-in's browser was sent back to,
|
||||
// for a magpie that browser can't reach. Only this sign-in's own address is
|
||||
// taken: its port and path, and its state. It goes through the handler the
|
||||
// callback port serves, so it is checked and traded for the account just as
|
||||
// the browser's own would be, and only once: whichever of the two comes
|
||||
// first finishes the sign-in, and the other waits for how that went.
|
||||
func (s *signInFlow) pastedCallback(raw string) error {
|
||||
s.mu.Lock()
|
||||
st, srv, redirect := s.st, s.srv, s.redirect
|
||||
s.mu.Unlock()
|
||||
if !st.PasteCallback || srv == nil {
|
||||
return errors.New("this sign-in can't be finished from a pasted address")
|
||||
}
|
||||
if st.State != "waiting" {
|
||||
return errors.New("this sign-in is over; start it again")
|
||||
}
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Scheme != "http" || u.RawQuery == "" {
|
||||
return errors.New("paste the whole address the browser ended on, starting with http://")
|
||||
}
|
||||
if !s.ownCallback(u, redirect) {
|
||||
return errors.New("that address isn't from this sign-in: paste the one its browser tab ended on")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+u.Host+u.RequestURI(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rep := &pastedReply{h: http.Header{}}
|
||||
srv.Handler.ServeHTTP(rep, req)
|
||||
|
||||
s.mu.Lock()
|
||||
claimed := s.claimed
|
||||
s.mu.Unlock()
|
||||
if !claimed {
|
||||
// Kiro's page sends an AWS sign-in on to AWS: the next page to open
|
||||
if loc := rep.h.Get("Location"); rep.code/100 == 3 && strings.HasPrefix(loc, "https://") && s.kiro != nil {
|
||||
s.mu.Lock()
|
||||
s.st.URL = loc
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if st := s.status(); st.State == "failed" {
|
||||
return errors.New(st.Error)
|
||||
}
|
||||
return errors.New("that address didn't finish the sign-in; start it again")
|
||||
}
|
||||
select {
|
||||
case <-s.done:
|
||||
case <-ctx.Done():
|
||||
return errors.New("the sign-in is still finishing; magpie shows the account when it's done")
|
||||
}
|
||||
switch st := s.status(); st.State {
|
||||
case "done":
|
||||
return nil
|
||||
case "failed":
|
||||
return errors.New(st.Error)
|
||||
}
|
||||
return errors.New("the sign-in was canceled")
|
||||
}
|
||||
|
||||
// ownCallback says whether a pasted address is where this sign-in's page
|
||||
// sends the browser back to.
|
||||
func (s *signInFlow) ownCallback(u *url.URL, redirect string) bool {
|
||||
want, err := url.Parse(redirect)
|
||||
if err != nil || u.Port() != want.Port() {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(u.Hostname()) {
|
||||
case "localhost", "127.0.0.1", "::1":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
q := u.Query()
|
||||
switch {
|
||||
case s.st.Agent == "zed":
|
||||
// no state: the token in it is encrypted to this sign-in's key
|
||||
return q.Get("user_id") != "" && q.Get("access_token") != ""
|
||||
case s.kiro != nil:
|
||||
if u.Path != "/oauth/callback" && u.Path != "/signin/callback" {
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
aws := s.kiro.state
|
||||
s.mu.Unlock()
|
||||
return q.Get("state") == s.state || (aws != "" && q.Get("state") == aws)
|
||||
}
|
||||
return u.Path == want.Path && q.Get("state") == s.state
|
||||
}
|
||||
|
||||
// pastedReply is what the callback handler answers a pasted address; only
|
||||
// its status and where it sends the browser on to count.
|
||||
type pastedReply struct {
|
||||
h http.Header
|
||||
code int
|
||||
}
|
||||
|
||||
func (p *pastedReply) Header() http.Header { return p.h }
|
||||
func (p *pastedReply) WriteHeader(code int) {
|
||||
if p.code == 0 {
|
||||
p.code = code
|
||||
}
|
||||
}
|
||||
func (p *pastedReply) Write(b []byte) (int, error) {
|
||||
p.WriteHeader(http.StatusOK)
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
// claim takes a sign-in's callback for one caller: the browser's own and a
|
||||
// pasted address can both arrive, and a code is traded only once.
|
||||
func (s *signInFlow) claim() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.st.State != "waiting" || s.claimed {
|
||||
return false
|
||||
}
|
||||
s.claimed = true
|
||||
return true
|
||||
}
|
||||
|
||||
// WaitSignIn blocks until a sign-in is over, for the command line.
|
||||
@@ -464,6 +590,11 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) {
|
||||
signInPage(w, false, "This link isn't from magpie's sign-in", "Start it again from magpie.")
|
||||
return
|
||||
}
|
||||
if !s.claim() {
|
||||
// its address was pasted too, and that one is being finished
|
||||
signInPage(w, false, "This sign-in is already finishing", "magpie shows the account when it's done.")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
if app, ok := googleAppOf(s.st.Agent); ok {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeCodexTokens answers Codex's token endpoint for the code "cx", counting
|
||||
// the trades; hold, when set, keeps each answer until it is closed.
|
||||
func fakeCodexTokens(t *testing.T, hold chan struct{}) *atomic.Int32 {
|
||||
t.Helper()
|
||||
var trades atomic.Int32
|
||||
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
trades.Add(1)
|
||||
if hold != nil {
|
||||
<-hold
|
||||
}
|
||||
if r.Form.Get("code") != "cx" || r.Form.Get("code_verifier") == "" ||
|
||||
!strings.HasSuffix(r.Form.Get("redirect_uri"), "/auth/callback") {
|
||||
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",
|
||||
})
|
||||
}))
|
||||
t.Cleanup(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()
|
||||
return &trades
|
||||
}
|
||||
|
||||
// callbackAddress is the address the vendor's page sends the browser back
|
||||
// to, as the browser shows it: localhost, which from a server or Docker
|
||||
// container is not where magpie is.
|
||||
func callbackAddress(t *testing.T, st SignInState, code, state string) string {
|
||||
t.Helper()
|
||||
u, err := url.Parse(st.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := u.Query()
|
||||
if state == "" {
|
||||
state = q.Get("state")
|
||||
}
|
||||
return q.Get("redirect_uri") + "?" + url.Values{"code": {code}, "state": {state}}.Encode()
|
||||
}
|
||||
|
||||
// Jorben on Discord: magpie in Docker on a cloud server, its web UI in his
|
||||
// browser; ChatGPT sends the browser back to localhost:1455, which is his
|
||||
// own machine, and the sign-in never finished. The address pasted finishes it.
|
||||
func TestCodexSignInFromPastedAddress(t *testing.T) {
|
||||
home := claudeHome(t)
|
||||
trades := fakeCodexTokens(t, nil)
|
||||
|
||||
st, err := StartSignIn("codex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer CancelSignIn(st.ID)
|
||||
if !st.PasteCallback {
|
||||
t.Fatal("ChatGPT's sign-in doesn't take a pasted address")
|
||||
}
|
||||
good := callbackAddress(t, st, "cx", "")
|
||||
|
||||
// another sign-in's address, or one that isn't the callback: refused,
|
||||
// nothing traded, still waiting
|
||||
for _, bad := range []string{
|
||||
callbackAddress(t, st, "cx", "not-ours"),
|
||||
strings.Replace(good, "/auth/callback", "/elsewhere", 1),
|
||||
strings.Replace(good, "localhost", "evil.example", 1),
|
||||
"cx",
|
||||
"",
|
||||
} {
|
||||
if err := SubmitSignInCallback(st.ID, bad); err == nil {
|
||||
t.Fatalf("%q was taken", bad)
|
||||
}
|
||||
}
|
||||
if n := trades.Load(); n != 0 {
|
||||
t.Fatalf("%d trades for refused addresses", n)
|
||||
}
|
||||
if cur, _ := SignInStatus(st.ID); cur.State != "waiting" {
|
||||
t.Fatalf("state %+v", cur)
|
||||
}
|
||||
|
||||
if err := SubmitSignInCallback(st.ID, " "+good+"\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, _ = SignInStatus(st.ID)
|
||||
if 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)
|
||||
}
|
||||
// pasted again: over, and the code isn't traded twice
|
||||
if err := SubmitSignInCallback(st.ID, good); err == nil {
|
||||
t.Fatal("a finished sign-in took its address again")
|
||||
}
|
||||
if n := trades.Load(); n != 1 {
|
||||
t.Fatalf("%d trades", n)
|
||||
}
|
||||
}
|
||||
|
||||
// The browser's own callback and the pasted address, both at once: one
|
||||
// trades the code, the other waits for how that went.
|
||||
func TestPastedAddressAndCallbackFinishOnce(t *testing.T) {
|
||||
claudeHome(t)
|
||||
hold := make(chan struct{})
|
||||
trades := fakeCodexTokens(t, hold)
|
||||
|
||||
st, err := StartSignIn("codex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer CancelSignIn(st.ID)
|
||||
good := callbackAddress(t, st, "cx", "")
|
||||
pasted := make(chan error, 1)
|
||||
go func() { pasted <- SubmitSignInCallback(st.ID, good) }()
|
||||
for i := 0; trades.Load() == 0; i++ {
|
||||
if i > 200 {
|
||||
t.Fatal("the pasted address was never traded")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
// a second trade would wait on hold: it must not start
|
||||
browser := http.Client{Timeout: 3 * time.Second}
|
||||
resp, err := browser.Get(strings.Replace(good, "localhost", "127.0.0.1", 1))
|
||||
if err != nil {
|
||||
close(hold)
|
||||
t.Fatalf("the browser's callback traded the code again: %v", err)
|
||||
}
|
||||
page, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if !strings.Contains(string(page), "already finishing") {
|
||||
t.Fatalf("second callback's page: %s", page)
|
||||
}
|
||||
close(hold)
|
||||
if err := <-pasted; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ = SignInStatus(st.ID); st.State != "done" || st.User != "cx@example.com" {
|
||||
t.Fatalf("state %+v", st)
|
||||
}
|
||||
if n := trades.Load(); n != 1 {
|
||||
t.Fatalf("the code was traded %d times", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Every built-in sign-in that comes back to a port here takes the address
|
||||
// pasted instead; one that doesn't come back through the browser's address
|
||||
// bar doesn't offer it.
|
||||
func TestLoopbackSignInsTakePastedAddress(t *testing.T) {
|
||||
claudeHome(t)
|
||||
fakeCodexTokens(t, nil)
|
||||
for _, agent := range []string{"claude", "codex", "gemini", "antigravity", "kiro", "zed"} {
|
||||
st, err := StartSignIn(agent)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", agent, err)
|
||||
}
|
||||
CancelSignIn(st.ID)
|
||||
if !st.PasteCallback {
|
||||
t.Errorf("%s: no pasted address", agent)
|
||||
}
|
||||
}
|
||||
st, err := StartSignIn(CommandCodePlanID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
CancelSignIn(st.ID)
|
||||
if st.PasteCallback {
|
||||
t.Error("Command Code's key is posted, never in an address to paste")
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,11 @@ func startZedSignIn(s *signInFlow) error {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if !s.claim() {
|
||||
// its address was pasted too, and that one is being finished
|
||||
signInPage(w, false, "This sign-in is already finishing", "magpie shows the account when it's done.")
|
||||
return
|
||||
}
|
||||
select {
|
||||
case got <- callback{uid, tok}:
|
||||
default:
|
||||
@@ -53,6 +58,9 @@ func startZedSignIn(s *signInFlow) error {
|
||||
s.mu.Lock()
|
||||
s.st.URL = zed.SignInURL(zedSite, port, pub, systemID)
|
||||
s.srv, s.stop = srv, cancel
|
||||
s.redirect = fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
// a browser that can't reach the port finishes it with its address
|
||||
s.st.PasteCallback = true
|
||||
s.mu.Unlock()
|
||||
go func() { _ = srv.Serve(ln) }()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user