From f3ad175fb237eb9bdab903dcc51440b4dfe4e375 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 15:12:31 +0800 Subject: [PATCH] library: an MCP server's sign-in keeps to its link when Settings say so (hkxhkxhkx on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hkxhkxhkx asked for magpie never to open OAuth pages in the browser on its own. Settings › Privacy › Sign-in pages › "Open sign-in pages in the browser" (signInLinkOnly, since a45a0f1c5) already does that for every account's sign-in, built-in and plugin, in the window, a web tab and the command line (`magpie accounts add`, a plugin's login; `magpie settings set signInLinkOnly true` sets it there). Audit of every route that opens a sign-in page: the one it missed is an MCP server's OAuth sign-in from the Library, which /api/library/mcp-signin opened in the default browser whatever the setting. The TUI starts no sign-in; `magpie web` opens magpie's own page (it has --no-open), not a vendor's. Now /api/library/mcp-signin goes through openMCPSignIn: with the setting on it opens nothing and answers linkOnly. The Library opens no tab of its own on linkOnly (web), opens the server's editor from a row's sign-in, and shows the same words as an account's link-only sign-in, the link with Copy, and Open in browser. No new strings. Still opened whatever the setting: a plugin whose own sign-in opens the page or a Chrome window (Grok Build's CLI on macOS and Windows; agnes, inkstone, astudio, mclaw, sensenova drive Chrome to sign in). Run (Linux, magpie-desktop via wsl-run; mote was over its load the whole time with eight full suites queued, mica's disk full): - TestMCPSignInLinkOnlyOpensNothing (new), TestSignInLinkOnlyOpensNothing, TestMCPSignInSaysTheBrowserDidntOpen, TestOpenSignInLinkOnlyAsked, TestCoreScriptBudget, TestI18n* (-tags nogui): ok. - mcp-signin-link-only.test.cjs (new; en, zh, zh-TW, ja, de; desktop and web; 1100 and 420px; Chromium and WebKit) with signin-browser-down, mcp-signin, mcp-signin-click, mcp-accounts, signin-link-only and i18n-keys: 146/146. Broken by hand: the route back on openError, the new Go test red ("its page was opened 1 times"); client.js back to main's, the new GUI test red (no link-only note). Not tried: a real MCP server's sign-in in the app; the whole GUI suite; the full Go suite before the push (started after it). --- internal/gui/api.go | 12 ++ internal/gui/assets/plugins/library/client.js | 17 ++- internal/gui/library.go | 2 +- internal/gui/signin_link_only_test.go | 48 +++++++ .../gui/tests/mcp-signin-link-only.test.cjs | 120 ++++++++++++++++++ internal/settings/settings.go | 4 +- 6 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 internal/gui/tests/mcp-signin-link-only.test.cjs diff --git a/internal/gui/api.go b/internal/gui/api.go index bf5d784ed..8dbf3cd35 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -3373,6 +3373,18 @@ func openSignIn(w Windows, st provider.SignInState, linkOnly bool) signInOpened type mcpSignInOpened struct { mcpauth.State OpenError string `json:"openError,omitempty"` + LinkOnly bool `json:"linkOnly,omitempty"` +} + +// openMCPSignIn is openSignIn for a sign-in to an MCP server: kept to its +// link when the user keeps sign-in pages to a browser of their own +// (settings.SignInLinkOnly), as an account's is. It opened the page in the +// default browser whatever the setting (hkxhkxhkx on X). +func openMCPSignIn(w Windows, st mcpauth.State) mcpSignInOpened { + if settings.Load().SignInLinkOnly { + return mcpSignInOpened{State: st, LinkOnly: true} + } + return mcpSignInOpened{State: st, OpenError: openError(w, st.URL)} } // openError opens url in the browser, and says why it didn't open: "" when diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index c9ca299e7..a01dcfa0f 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -3560,10 +3560,10 @@ magpie.plugin("library", (ctx) => { try { const st = await api("library/mcp-signin", { name }); if (mcpSigning?.name !== name || mcpSigning.id) return; // canceled - if (web && st.url) api("open", { url: st.url }).catch(() => {}); + if (web && st.url && !st.linkOnly) api("open", { url: st.url }).catch(() => {}); mcpSigning = { ...st, name }; signMoved(name); - if (st.openError) editServer(s); + if (st.openError || st.linkOnly) editServer(s); followSignIn(st.id, name); } catch (e) { if (mcpSigning?.name !== name) return; @@ -3623,15 +3623,20 @@ magpie.plugin("library", (ctx) => { } box.append(line); // the browser didn't start (#2043): the page to open by hand, rather - // than waiting on one that never opened until the sign-in times out - if (sg?.state === "waiting" && sg.openError && sg.url) { - box.append(el("div", "lib-signin-err", t("magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.", { error: sg.openError }))); + // than waiting on one that never opened until the sign-in times out; + // or the user keeps sign-in pages to a browser of their own + // (settings.SignInLinkOnly): the link to copy there, or open here + if (sg?.state === "waiting" && (sg.openError || sg.linkOnly) && sg.url) { + box.append(sg.linkOnly + ? el("div", "note", t("magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with.")) + : el("div", "lib-signin-err", t("magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.", { error: sg.openError }))); const link = el("div", "lib-signin-link"); const u = el("code", "", sg.url); u.title = sg.url; const cp = copyBtn(sg.url, t("Sign-in link")); cp.title = t("Copy link"); link.append(u, cp); + if (sg.linkOnly) link.append(button(t("Open in browser"), "", () => browse(sg.url))); box.append(link); } if (sg?.state === "failed") box.append(el("div", "lib-signin-err", sg.error)); @@ -3661,7 +3666,7 @@ magpie.plugin("library", (ctx) => { mcpSigning = { name, state: "starting" }; } const st = await api("library/mcp-signin", typeof label === "string" ? { name, add: true, label } : { name }); - if (web && st.url) api("open", { url: st.url }).catch(() => {}); + if (web && st.url && !st.linkOnly) api("open", { url: st.url }).catch(() => {}); mcpSigning = { ...st, name }; draw(); followSignIn(st.id, name); diff --git a/internal/gui/library.go b/internal/gui/library.go index 5ff6ab312..ac12b2e13 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -539,7 +539,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } - writeJSON(rw, mcpSignInOpened{st, openError(w, st.URL)}) + writeJSON(rw, openMCPSignIn(w, st)) }) mux.HandleFunc("GET /api/library/mcp-signin/{id}", func(rw http.ResponseWriter, r *http.Request) { st, ok := mcpauth.Progress(r.PathValue("id")) diff --git a/internal/gui/signin_link_only_test.go b/internal/gui/signin_link_only_test.go index 06e6937a0..19d5ea98a 100644 --- a/internal/gui/signin_link_only_test.go +++ b/internal/gui/signin_link_only_test.go @@ -9,6 +9,9 @@ import ( "strings" "testing" + "github.com/yetone/magpie/internal/library" + "github.com/yetone/magpie/internal/mcpauth" + "github.com/yetone/magpie/internal/mcpauth/mcpauthtest" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" @@ -86,3 +89,48 @@ func TestSignInLinkOnlyOpensNothing(t *testing.T) { } } } + +// An MCP server's OAuth sign-in from the Library is kept to its link too +// when the user keeps sign-in pages to a browser of their own (hkxhkxhkx on +// X: it opened the default browser whatever the setting). It still starts +// and gives its link; with the setting off, as by default, it opens once. +func TestMCPSignInLinkOnlyOpensNothing(t *testing.T) { + sandboxHome(t) + f := mcpauthtest.New(t) + if _, err := library.SaveServer("", library.Server{Name: "cloudflare-api", Transport: "http", URL: f.URL}); err != nil { + t.Fatal(err) + } + for _, linkOnly := range []bool{true, false} { + s := settings.Load() + s.SignInLinkOnly = linkOnly + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + w := &openCounter{} + rec := httptest.NewRecorder() + Handler(w, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/library/mcp-signin", strings.NewReader(`{"name":"cloudflare-api"}`))) + if rec.Code != http.StatusOK { + t.Fatalf("sign-in: %d %s", rec.Code, rec.Body) + } + var st struct { + ID, URL, State string + LinkOnly bool `json:"linkOnly"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &st); err != nil { + t.Fatal(err) + } + mcpauth.Cancel(st.ID) + if st.State != "waiting" || !strings.HasPrefix(st.URL, f.Server.URL) { + t.Fatalf("link only %v: not waiting on its page: %+v", linkOnly, st) + } + w.mu.Lock() + n := len(w.opened) + w.mu.Unlock() + if linkOnly && (n != 0 || !st.LinkOnly) { + t.Fatalf("kept to its link, its page was opened %d times (linkOnly %v)", n, st.LinkOnly) + } + if !linkOnly && (n != 1 || st.LinkOnly) { + t.Fatalf("by default its page was opened %d times (linkOnly %v)", n, st.LinkOnly) + } + } +} diff --git a/internal/gui/tests/mcp-signin-link-only.test.cjs b/internal/gui/tests/mcp-signin-link-only.test.cjs new file mode 100644 index 000000000..5e701c336 --- /dev/null +++ b/internal/gui/tests/mcp-signin-link-only.test.cjs @@ -0,0 +1,120 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// hkxhkxhkx on X: with Settings › Privacy › "Open sign-in pages in the +// browser" off (signInLinkOnly), an account's sign-in kept to its link, but +// an MCP server's OAuth sign-in from the Library still opened the default +// browser. Now /api/library/mcp-signin answers linkOnly and opens nothing, +// and the Library says so with the link to copy and an Open in browser of +// its own; a web tab opens no tab of its own either. Every language, +// Chromium and WebKit, 1100 and 420px; 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 MCP_LINK = "https://dash.cloudflare.com/oauth2/auth?client_id=c1&state=" + "y".repeat(80); + +function server(lang, web, st) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data, status) => route.fulfill({ status: status || 200, json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + 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", signInLinkOnly: true } }); + if (url.pathname === "/api/providers") return json({ providers: [], 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/open") { + st.opens.push(req.postDataJSON().url); + return route.fulfill({ status: 204, body: "" }); + } + if (url.pathname === "/api/library") { + return json({ + dir: "/h/.magpie/library", backups: "/h/.magpie/backups", home: "/h", + agents: [{ id: "codex", name: "Codex", icon: "", skills: "/h/.codex/skills", mcp: "/h/.codex/mcp.json" }], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], + servers: [{ name: "cloudflare-api", transport: "http", url: "https://mcp.cloudflare.com/mcp", agents: ["codex"], signIn: { signedIn: false } }], + }); + } + // the start says it was kept to its link; a poll knows nothing of it + if (url.pathname === "/api/library/mcp-signin") return json({ id: "m1", server: "cloudflare-api", state: "waiting", url: MCP_LINK, linkOnly: true }); + if (url.pathname.startsWith("/api/library/mcp-signin/")) return json({ id: "m1", server: "cloudflare-api", state: "waiting", url: MCP_LINK }); + if (url.pathname === "/api/usage/quotas") return json([]); + 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: { signIn: "Sign in", open: "Open in browser", said: "magpie didn't open the sign-in page, as set in Settings. Copy the link below into the browser you sign in with." }, + zh: { signIn: "登录", open: "在浏览器中打开", said: "magpie 按设置没有打开登录页。把下面的链接复制到你用来登录的浏览器里。" }, + "zh-TW": { signIn: "登入", open: "在瀏覽器中開啟", said: "magpie 依設定沒有開啟登入頁。把下面的連結複製到你用來登入的瀏覽器裡。" }, + ja: { signIn: "サインイン", open: "ブラウザで開く", said: "設定に従い、magpie はサインインページを開いていません。下のリンクをサインインに使うブラウザにコピーしてください。" }, + de: { signIn: "Anmelden", open: "Im Browser öffnen", said: "magpie hat die Anmeldeseite wie in den Einstellungen festgelegt nicht geöffnet. Kopiere den Link unten in den Browser, mit dem du dich anmeldest." }, +}; + +const overflow = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(W)) { + for (const width of [1100, 420]) { + for (const web of [false, true]) { + test(`${engine} ${lang} ${width}${web ? " web" : ""}: an MCP sign-in kept to its link opens nothing and shows it`, async (t) => { + const w = W[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const st = { opens: [] }; + const ctx = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" }); + // window.open is counted, never followed: a test reaches no network + await ctx.addInitScript(() => { + try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} + window.__opened = []; + window.open = (u) => { window.__opened.push(String(u)); return null; }; + }); + const popups = () => page.evaluate(() => window.__opened); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, web, st)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + await page.locator("#view-library .lib-row", { has: page.locator(".name", { hasText: /^cloudflare-api/ }) }).click(); + const lib = page.locator("#modal .lib-signin"); + await Promise.all([page.waitForResponse((r) => r.url().endsWith("/api/library/mcp-signin")), lib.getByRole("button", { name: w.signIn, exact: true }).click()]); + const note = lib.locator(".note", { hasText: w.said }); + await note.waitFor(); + assert.equal(await note.textContent(), w.said); + assert.equal(await lib.locator(".lib-signin-err").count(), 0, "not said as an error"); + const code = lib.locator(".lib-signin-link code"); + assert.equal(await code.textContent(), MCP_LINK); + // a poll later still shows it (the poll says nothing of linkOnly) + await page.waitForResponse((r) => r.url().endsWith("/api/library/mcp-signin/m1")); + await note.waitFor(); + assert.deepEqual(st.opens, [], "nothing was opened by the start"); + assert.deepEqual(await popups(), [], "no tab of its own was opened"); + const box = await code.boundingBox(), modal = await page.locator("#modal .lib-editor").boundingBox(); + assert.ok(box.x + box.width <= modal.x + modal.width + 1, "the link stays inside the editor"); + assert.equal(await overflow(page), 0, "nothing past the right edge"); + // the reader's own Open in browser opens it + const open = lib.locator(".lib-signin-link button", { hasText: w.open }); + if (web) { + await open.click(); + await page.waitForFunction(() => window.__opened.length > 0); + assert.deepEqual(await popups(), [MCP_LINK]); + } else { + await Promise.all([page.waitForResponse((r) => r.url().endsWith("/api/open")), open.click()]); + assert.deepEqual(st.opens, [MCP_LINK]); + } + await ctx.close(); + assert.deepEqual(errors, []); + }); + } + } + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index a08c682fe..bc46d0f63 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -523,7 +523,9 @@ type Settings struct { // SignInLinkOnly keeps an account's sign-in page out of the default // browser: the window (and the command line) shows its link to copy // into a browser the user picks, a separate or fingerprint browser - // (max2020 on Discord). Off, as by default, the page opens as ever. A + // (max2020 on Discord). An MCP server's OAuth sign-in from the Library + // is kept to its link too (hkxhkxhkx on X). Off, as by default, the + // page opens as ever. A // plugin whose own CLI opens its page (Grok Build on macOS and // Windows) still does: magpie can't stop that. SignInLinkOnly bool `json:"signInLinkOnly,omitempty"`