library: an MCP server whose sign-in has no client registration (GitHub's) is signed in to as the user's own OAuth app (新v学员 on Discord)
What changed: GitHub's remote MCP server (api.githubcopilot.com/mcp/)
points to https://github.com/login/oauth, whose metadata has no
registration_endpoint, so magpie's sign-in, which always registered
itself (DCR), could never sign in to it. A server now carries an
optional OAuth app, `oauth: {clientId, clientSecret, callbackPort}`,
Claude Code's names for --client-id/--client-secret/--callback-port
(oauth.clientId in its .claude.json). mcpauth.StartWith signs in as
that app without registering: PKCE S256, a loopback callback
http://127.0.0.1:<port>/callback (any port unless callbackPort is set),
client_secret_post with a secret (basic only when the server lists
basic alone), "none" without one.
Without an app, a server with no registration endpoint now fails with
mcpauth.ErrNoRegistration, which says to make an OAuth app with the
vendor (GitHub's under Settings > Developer settings > OAuth Apps, with
http://127.0.0.1/callback) and give it under "OAuth app" in the editor.
The editor opens those fields with Client ID focused when that error
comes back. Filling them makes Sign in read "Save and sign in", and
Cancel asks before dropping them, as the earlier Cancel fix does.
GitHub answers token errors with 200 and {"error": ...}; tokenRequest
now reads a 2xx body with `error` as the error, and bad_refresh_token /
incorrect_client_credentials count as a dead sign-in as
invalid_grant/invalid_client do.
Secrets: the client secret sits in library.json like header and env
values. A backup without keys blanks it; WithSecrets puts this
computer's secret back only for the same client ID. No agent file is
given the app. The TUI editor, which doesn't show it, keeps it on save.
check() keeps it only on an HTTP server, requires a client ID when a
secret or port is given, and a port 1-65535.
Run (worktree at 98b5a02d1 + the two earlier commits):
- go test -race ./internal/mcpauth/... (new github_app_test.go: an
httptest fake built from GitHub's real PRM and AS metadata bytes:
no app -> ErrNoRegistration, sign-in as the app, wrong secret, fixed
callback port, bad refresh token)
- go test -tags nogui ./internal/library ./internal/tui ./internal/gui;
go test ./internal/gateway -run MCP
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
- GUI, Chromium and WebKit, 1100/390, en zh zh-TW ja de:
mcp-oauth-app (new, 22/22), mcp-editor-cancel, mcp-signin,
mcp-signin-health, library-mcp-health, i18n-keys - all pass
- Broken by hand, each went red: no 2xx error parse, GitHub codes out
of dead(), app ignored in StartWith, secret not blanked / not matched
by client ID in carry, check() without the non-HTTP rule; in the GUI,
oauth left out of the save, and the failed hook not opening the fields.
- Sandbox HOME, rebuilt magpie web, against the real GitHub server:
Sign in showed the new error and opened the fields; Save and sign in
saved the app and produced a real github.com/login/oauth/authorize
URL with the app's client_id, S256 and a 127.0.0.1 redirect, which
GitHub answered with its login page. .claude.json didn't hold the app.
Not run: a real GitHub sign-in to completion. There's no real OAuth app
to use, and I didn't make one on the owner's account. Claude Code's
callback says localhost where magpie's says 127.0.0.1, so an app made
for Claude Code needs its callback URL changed; that isn't bridged.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1767,6 +1767,14 @@ const I18N = {
|
||||
"Sign-in ran out": "登录已失效",
|
||||
"Sign in again": "重新登录",
|
||||
"Save and sign in": "保存并登录",
|
||||
"Use your own OAuth app": "使用自己的 OAuth 应用",
|
||||
"For a server whose sign-in doesn't let magpie register itself, as GitHub's": "用于不允许 magpie 自行注册的服务器登录,如 GitHub 的",
|
||||
"OAuth app": "OAuth 应用",
|
||||
"Client ID": "客户端 ID",
|
||||
"Client secret": "客户端密钥",
|
||||
"Callback port": "回调端口",
|
||||
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服务方创建(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 {url}",
|
||||
"the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "该服务器的登录不允许应用自行注册(不支持动态客户端注册),因此 magpie 只能以你自己的 OAuth 应用登录:在服务方创建一个(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 http://127.0.0.1/callback,再在该服务器编辑器的「OAuth 应用」中填入它的客户端 ID 和密钥",
|
||||
"Sign-in required": "需要重新登录",
|
||||
"GitHub refused this Copilot sign-in; sign in again": "GitHub 拒绝了这个 Copilot 登录,请重新登录",
|
||||
"The vendor revoked this sign-in; sign in again": "服务商已撤销这个登录,请重新登录",
|
||||
@@ -6243,6 +6251,14 @@ const I18N = {
|
||||
"Sign-in ran out": "登入已失效",
|
||||
"Sign in again": "重新登入",
|
||||
"Save and sign in": "儲存並登入",
|
||||
"Use your own OAuth app": "使用自己的 OAuth 應用程式",
|
||||
"For a server whose sign-in doesn't let magpie register itself, as GitHub's": "用於不允許 magpie 自行註冊的伺服器登入,如 GitHub 的",
|
||||
"OAuth app": "OAuth 應用程式",
|
||||
"Client ID": "用戶端 ID",
|
||||
"Client secret": "用戶端密鑰",
|
||||
"Callback port": "回呼連接埠",
|
||||
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服務方建立(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 {url}",
|
||||
"the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "該伺服器的登入不允許應用程式自行註冊(不支援動態用戶端註冊),因此 magpie 只能以你自己的 OAuth 應用程式登入:在服務方建立一個(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 http://127.0.0.1/callback,再在該伺服器編輯器的「OAuth 應用程式」中填入它的用戶端 ID 和密鑰",
|
||||
"Sign-in required": "需要重新登入",
|
||||
"GitHub refused this Copilot sign-in; sign in again": "GitHub 拒絕了這個 Copilot 登入,請重新登入",
|
||||
"The vendor revoked this sign-in; sign in again": "服務商已撤銷這個登入,請重新登入",
|
||||
@@ -10695,6 +10711,14 @@ const I18N = {
|
||||
"Sign-in ran out": "サインインの期限切れ",
|
||||
"Sign in again": "再度サインイン",
|
||||
"Save and sign in": "保存してサインイン",
|
||||
"Use your own OAuth app": "自分の OAuth アプリを使う",
|
||||
"For a server whose sign-in doesn't let magpie register itself, as GitHub's": "magpie が自身を登録できないサーバー(GitHub など)のサインイン用",
|
||||
"OAuth app": "OAuth アプリ",
|
||||
"Client ID": "クライアント ID",
|
||||
"Client secret": "クライアントシークレット",
|
||||
"Callback port": "コールバックポート",
|
||||
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "提供元で作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に {url} を指定します",
|
||||
"the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "このサーバーのサインインはアプリの自己登録(動的クライアント登録)を受け付けないため、magpie は自分で用意した OAuth アプリとしてのみサインインできます。提供元でアプリを作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に http://127.0.0.1/callback を指定してから、サーバーの編集画面の「OAuth アプリ」にクライアント ID とシークレットを入力してください",
|
||||
"Sign-in required": "サインインが必要です",
|
||||
"GitHub refused this Copilot sign-in; sign in again": "GitHub がこの Copilot のサインインを拒否しました。再度サインインしてください",
|
||||
"The vendor revoked this sign-in; sign in again": "ベンダーがこのサインインを取り消しました。再度サインインしてください",
|
||||
@@ -15166,6 +15190,14 @@ const I18N = {
|
||||
"Sign-in ran out": "Anmeldung abgelaufen",
|
||||
"Sign in again": "Erneut anmelden",
|
||||
"Save and sign in": "Speichern und anmelden",
|
||||
"Use your own OAuth app": "Eigene OAuth-App verwenden",
|
||||
"For a server whose sign-in doesn't let magpie register itself, as GitHub's": "Für einen Server, bei dessen Anmeldung sich magpie nicht selbst registrieren kann, wie bei GitHub",
|
||||
"OAuth app": "OAuth-App",
|
||||
"Client ID": "Client-ID",
|
||||
"Client secret": "Client-Secret",
|
||||
"Callback port": "Callback-Port",
|
||||
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "Beim Anbieter angelegt (bei GitHub unter Settings › Developer settings › OAuth Apps), mit {url} als Callback-URL",
|
||||
"the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor": "die Anmeldung dieses Servers lässt keine App sich selbst registrieren (keine dynamische Client-Registrierung), daher meldet sich magpie nur als eigene OAuth-App an: Lege beim Anbieter eine an (bei GitHub unter Settings › Developer settings › OAuth Apps) mit http://127.0.0.1/callback als Callback-URL und trage ihre Client-ID und ihr Secret unter „OAuth-App“ im Editor des Servers ein",
|
||||
"Sign-in required": "Anmeldung erforderlich",
|
||||
"GitHub refused this Copilot sign-in; sign in again": "GitHub hat diese Copilot-Anmeldung abgelehnt; bitte erneut anmelden",
|
||||
"The vendor revoked this sign-in; sign in again": "Der Anbieter hat diese Anmeldung widerrufen; bitte erneut anmelden",
|
||||
|
||||
@@ -130,6 +130,9 @@ body.window .lib-head { top: -2px; margin: -2px 0 0; padding: 8px 0 4px; --bleed
|
||||
/* magpie's sign-in to a remote server, in its editor (#615) */
|
||||
.lib-signin-line { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-height: 28px; }
|
||||
.lib-signin-line .note { font-size: 12px; color: var(--fg-2); }
|
||||
.lib-app { display: flex; gap: 6px; width: 100%; align-items: center; flex-wrap: wrap; }
|
||||
.lib-app input { flex: 1 1 9em; min-width: 0; font-family: var(--code-font, var(--code)); font-size: 12px; }
|
||||
.lib-app input.port { flex: 0 1 7.5em; }
|
||||
.lib-signin-err { margin-top: 6px; font-size: 12px; color: var(--red); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
|
||||
/* the switch */
|
||||
|
||||
@@ -1665,6 +1665,7 @@
|
||||
// magpie's words in the reader's language, where it has them
|
||||
mcpSigning = { name, state: "failed", error: t(e.message) };
|
||||
draw();
|
||||
ready?.failed?.(e.message);
|
||||
}
|
||||
}
|
||||
// followed with the dialog closed too, for the row to say it's signed in
|
||||
@@ -1829,6 +1830,11 @@
|
||||
// refHint: how a value is read from a variable (#1250)
|
||||
const refHint = () => t("A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings", { ref: "${NAME}" });
|
||||
|
||||
// the start of mcpauth.ErrNoRegistration
|
||||
const NO_REGISTRATION = "the server's sign-in doesn't let an app register itself";
|
||||
// a server's own OAuth app, to tell a changed one: "" for none
|
||||
const appOf = (x) => (x?.transport === "http" && x.oauth?.clientId ? JSON.stringify([x.oauth.clientId, x.oauth.clientSecret || "", x.oauth.callbackPort || 0]) : "");
|
||||
|
||||
function editServer(s, prefill) {
|
||||
const all = mcpAgents();
|
||||
const d = prefill || (s ? structuredClone(s) : { name: "", transport: "stdio", command: "", args: [], env: {}, url: "", headers: {}, agents: all.map((a) => a.id) });
|
||||
@@ -1844,7 +1850,46 @@
|
||||
let signBox = null; // the sign-in's, for its button to say it saves
|
||||
// a sign-in saves the form first only to sign in to another server than
|
||||
// the saved one; see ready
|
||||
ready.saves = () => !s || d.name !== s.name || d.transport !== s.transport || d.url !== (s.url || "");
|
||||
ready.saves = () => !s || d.name !== s.name || d.transport !== s.transport || d.url !== (s.url || "") || appOf(d) !== appOf(s);
|
||||
// a server whose sign-in doesn't let magpie register itself (GitHub's,
|
||||
// 新v学员 on Discord): the fields for the user's own app open
|
||||
ready.failed = (msg) => {
|
||||
if (!msg.startsWith(NO_REGISTRATION) || !appBox) return;
|
||||
appOpen = true;
|
||||
drawApp();
|
||||
appBox.querySelector("input")?.focus();
|
||||
};
|
||||
let appOpen = !!d.oauth?.clientId, appBox = null, appHint = null;
|
||||
// the user's own OAuth app, by Claude Code's names (--client-id,
|
||||
// --client-secret, --callback-port)
|
||||
function drawApp() {
|
||||
appBox.replaceChildren();
|
||||
const hint = appHint;
|
||||
if (!appOpen) {
|
||||
appBox.append(button(t("Use your own OAuth app"), "lib-addpair", () => { appOpen = true; drawApp(); appBox.querySelector("input")?.focus(); }));
|
||||
if (hint) hint.textContent = t("For a server whose sign-in doesn't let magpie register itself, as GitHub's");
|
||||
return;
|
||||
}
|
||||
const a = () => (d.oauth ||= { clientId: "", clientSecret: "", callbackPort: 0 });
|
||||
const id = field2(d.oauth?.clientId, t("Client ID"), (v) => { a().clientId = v.trim(); signBox?.redraw(); });
|
||||
const secret = field2(d.oauth?.clientSecret, t("Client secret"), (v) => { a().clientSecret = v.trim(); signBox?.redraw(); });
|
||||
secret.type = "password";
|
||||
const port = field2(d.oauth?.callbackPort || "", t("Callback port"), (v) => {
|
||||
port.value = v.replace(/\D/g, "").slice(0, 5);
|
||||
a().callbackPort = Number(port.value) || 0;
|
||||
signBox?.redraw();
|
||||
if (hint) hint.textContent = callback();
|
||||
});
|
||||
port.inputMode = "numeric";
|
||||
port.classList.add("port");
|
||||
for (const [i, l] of [[id, t("Client ID")], [secret, t("Client secret")], [port, t("Callback port")]]) i.setAttribute("aria-label", l);
|
||||
const x = button("", "lib-x", () => { d.oauth = s?.oauth ? null : undefined; appOpen = false; drawApp(); signBox?.redraw(); });
|
||||
x.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6));
|
||||
x.title = t("Remove");
|
||||
appBox.append(id, secret, port, x);
|
||||
if (hint) hint.textContent = callback();
|
||||
}
|
||||
const callback = () => t("Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL", { url: "http://127.0.0.1" + (d.oauth?.callbackPort ? ":" + d.oauth.callbackPort : "") + "/callback" });
|
||||
const name = field2(d.name, t("e.g. github"), (v) => { d.name = v.trim(); signBox?.redraw(); });
|
||||
ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it")));
|
||||
const kindOf = () => segs([["stdio", t("Command")], ["http", "HTTP"], ["sse", "SSE"]], d.transport, (v) => { d.transport = v; draw(); });
|
||||
@@ -1877,9 +1922,16 @@
|
||||
// the saved one, so a URL just changed (or a server just added) is
|
||||
// the one signed in to
|
||||
signBox = d.transport === "http" ? signInBox(s ? s.name : "", ready) : null;
|
||||
if (signBox) g.append(...field(t("Sign-in"), signBox, t("For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in")));
|
||||
if (signBox) {
|
||||
appBox = el("div", "lib-app");
|
||||
const f = field(t("OAuth app"), appBox, " ");
|
||||
appHint = f[1].querySelector(".hint");
|
||||
g.append(...f);
|
||||
g.append(...field(t("Sign-in"), signBox, t("For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in")));
|
||||
} else appBox = null;
|
||||
}
|
||||
slot.append(g);
|
||||
if (appBox) drawApp();
|
||||
// its own icon while it runs as it did; another way of running is another server
|
||||
head.firstChild.replaceWith(mark(s && d.transport === s.transport ? s.icon : "", d.transport === "stdio" ? GLYPH.cmd : GLYPH.web));
|
||||
drawAgents();
|
||||
@@ -1898,7 +1950,7 @@
|
||||
const send = async () => {
|
||||
const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents } };
|
||||
if (d.transport === "stdio") Object.assign(body.server, { command: d.command, args: d.args, env: d.env });
|
||||
else Object.assign(body.server, { url: d.url, headers: d.headers });
|
||||
else Object.assign(body.server, { url: d.url, headers: d.headers, oauth: d.transport === "http" && d.oauth?.clientId ? d.oauth : null });
|
||||
take(await api("library/servers/save", body));
|
||||
const was = s;
|
||||
s = lib.servers.find((x) => x.name === d.name) || s;
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// 新v学员 on Discord: GitHub's remote MCP server signs in with GitHub's own
|
||||
// OAuth, which doesn't let an app register itself, so magpie couldn't sign
|
||||
// in to it. The server's editor takes an OAuth app of the user's own (a
|
||||
// client ID, its secret, a callback port: Claude Code's --client-id,
|
||||
// --client-secret, --callback-port), and the sign-in's error says so and
|
||||
// opens those fields. The app is saved with the server, the sign-in button
|
||||
// saying so first; Cancel keeps a server's app as saved. Every language,
|
||||
// Chromium and WebKit, 1100 and 390 wide; nothing scrolls sideways. No
|
||||
// backend: the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const fsSync = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const I18N = new Function(fsSync.readFileSync(path.join(assets, "i18n.js"), "utf8") + ";return I18N;")();
|
||||
const tr = (lang, s, vars = {}) => ((lang === "en" ? s : I18N[lang][s]) || s).replace(/\{(\w+)\}/g, (_, k) => vars[k]);
|
||||
const HOME = "/Users/xv";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
|
||||
const GH = "https://api.githubcopilot.com/mcp/";
|
||||
const ID = "Ov23liAbCdEfGhIjKlMn", SECRET = "0123456789abcdef0123456789abcdef01234567";
|
||||
// mcpauth.ErrNoRegistration, as the backend says it
|
||||
const NO_REG = "the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor";
|
||||
|
||||
function server(lang, calls) {
|
||||
const lib = {
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("claude", "Claude Code")],
|
||||
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [],
|
||||
servers: [{ name: "github", transport: "http", url: GH, agents: ["claude"], signIn: { signedIn: false } }],
|
||||
};
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
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 route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
|
||||
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
|
||||
if (url.pathname === "/api/library") return route.fulfill({ json: lib });
|
||||
if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } });
|
||||
if (url.pathname === "/api/library/mcp-signin") {
|
||||
const s = lib.servers.find((x) => x.name === req.postDataJSON().name);
|
||||
calls.push("start " + s.name + " " + (s.oauth?.clientId || "-"));
|
||||
// GitHub's sign-in has no registration: only the user's app gets in
|
||||
if (!s.oauth) return route.fulfill({ status: 400, json: { error: NO_REG } });
|
||||
return route.fulfill({ json: { id: "s1", server: s.name, state: "waiting" } });
|
||||
}
|
||||
if (url.pathname === "/api/library/mcp-signin/s1/cancel") { calls.push("cancel"); return route.fulfill({ json: {} }); }
|
||||
if (url.pathname === "/api/library/mcp-signin/s1") return route.fulfill({ json: { id: "s1", state: "waiting" } });
|
||||
if (url.pathname === "/api/library/servers/save") {
|
||||
const { old, server: s } = req.postDataJSON();
|
||||
calls.push("save " + s.name + " " + JSON.stringify(s.oauth));
|
||||
const i = lib.servers.findIndex((x) => x.name === old);
|
||||
lib.servers[i] = { ...lib.servers[i], ...s };
|
||||
if (!s.oauth) delete lib.servers[i].oauth;
|
||||
return route.fulfill({ json: { ...lib, result: { changed: ["claude"] } } });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
|
||||
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
|
||||
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
|
||||
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": an MCP server signed in to as the user's own OAuth app", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
});
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [1100, 390]) {
|
||||
await t.test(`${lang} ${width}`, async () => {
|
||||
const w = (s, v) => tr(lang, s, v);
|
||||
const calls = [];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 800 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, calls));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const row = page.locator("#view-library .lib-server", { has: page.locator('.lib-health[data-server="github"]') });
|
||||
const ed = page.locator("#modal .lib-editor");
|
||||
const box = ed.locator(".lib-signin");
|
||||
const app = ed.locator(".lib-app");
|
||||
const input = (label) => app.getByLabel(w(label), { exact: true });
|
||||
const hint = (u) => ed.locator(".hint", { hasText: u });
|
||||
const open = async () => { await row.locator(".name").click(); await ed.waitFor(); };
|
||||
const cancel = async (asked) => {
|
||||
await ed.locator(":scope > .bar button", { hasText: new RegExp("^" + w("Cancel") + "$") }).click();
|
||||
const ask = page.locator("dialog.action-confirm");
|
||||
if (asked) await ask.locator("button.primary", { hasText: w("Discard") }).click();
|
||||
await ed.waitFor({ state: "detached" });
|
||||
assert.equal(await ask.count(), 0, "asked to discard");
|
||||
};
|
||||
|
||||
// the reporter's case: GitHub's sign-in has no registration; the
|
||||
// error says what to do, in the reader's language, and the app's
|
||||
// fields open
|
||||
await open();
|
||||
await app.getByRole("button", { name: w("Use your own OAuth app"), exact: true }).waitFor();
|
||||
await box.getByRole("button", { name: w("Sign in"), exact: true }).click();
|
||||
await box.locator(".lib-signin-err", { hasText: w(NO_REG) }).waitFor();
|
||||
await input("Client ID").waitFor();
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), w("Client ID"));
|
||||
await hint("http://127.0.0.1/callback").waitFor();
|
||||
|
||||
// typed but not saved: Cancel asks, and nothing is saved
|
||||
await input("Client ID").fill(ID);
|
||||
await box.getByRole("button", { name: w("Save and sign in"), exact: true }).waitFor();
|
||||
await cancel(true);
|
||||
assert.deepEqual(calls, ["start github -"]);
|
||||
|
||||
// the app given: "Save and sign in" saves it and signs in as it
|
||||
await open();
|
||||
await app.getByRole("button", { name: w("Use your own OAuth app"), exact: true }).click();
|
||||
await input("Client ID").fill(ID);
|
||||
await input("Client secret").fill(SECRET);
|
||||
assert.equal(await input("Client secret").getAttribute("type"), "password");
|
||||
await input("Callback port").pressSequentially("31a18");
|
||||
assert.equal(await input("Callback port").inputValue(), "3118");
|
||||
await hint("http://127.0.0.1:3118/callback").waitFor();
|
||||
await box.getByRole("button", { name: w("Save and sign in"), exact: true }).click();
|
||||
await box.getByRole("button", { name: w("Cancel"), exact: true }).click();
|
||||
await box.getByRole("button", { name: w("Sign in"), exact: true }).waitFor();
|
||||
assert.deepEqual(calls.slice(1), ["save github " + JSON.stringify({ clientId: ID, clientSecret: SECRET, callbackPort: 3118 }), "start github " + ID, "cancel"]);
|
||||
await cancel(false);
|
||||
|
||||
// kept: shown again; taken away, saved without it
|
||||
await open();
|
||||
assert.equal(await input("Client ID").inputValue(), ID);
|
||||
assert.equal(await input("Client secret").inputValue(), SECRET);
|
||||
await app.locator(".lib-x").click();
|
||||
await app.getByRole("button", { name: w("Use your own OAuth app"), exact: true }).waitFor();
|
||||
await ed.locator(":scope > .bar button.primary").click();
|
||||
await ed.waitFor({ state: "detached" });
|
||||
assert.equal(calls.at(-1), "save github null");
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
@@ -235,6 +235,12 @@ func (b *Bundle) WithoutSecrets(secret func(string) bool) {
|
||||
for i, s := range b.MCP {
|
||||
c := *s
|
||||
c.Env, c.Headers = blank(s.Env, secret), blank(s.Headers, secret)
|
||||
// an OAuth app's secret is a key too; its client ID isn't
|
||||
if s.OAuth != nil && s.OAuth.ClientSecret != "" {
|
||||
a := *s.OAuth
|
||||
a.ClientSecret = ""
|
||||
c.OAuth = &a
|
||||
}
|
||||
b.MCP[i] = &c
|
||||
}
|
||||
}
|
||||
@@ -267,6 +273,12 @@ func (b *Bundle) WithSecrets(have *Bundle, secret func(string) bool) *Bundle {
|
||||
i := slices.IndexFunc(have.MCP, func(h *Server) bool { return h.Name == s.Name })
|
||||
if i >= 0 {
|
||||
c.Env, c.Headers = filled(s.Env, have.MCP[i].Env, secret), filled(s.Headers, have.MCP[i].Headers, secret)
|
||||
// the same app's secret, kept here
|
||||
if h := have.MCP[i].OAuth; s.OAuth != nil && s.OAuth.ClientSecret == "" && h != nil && h.ClientID == s.OAuth.ClientID {
|
||||
a := *s.OAuth
|
||||
a.ClientSecret = h.ClientSecret
|
||||
c.OAuth = &a
|
||||
}
|
||||
}
|
||||
out.MCP = append(out.MCP, &c)
|
||||
}
|
||||
|
||||
@@ -41,6 +41,22 @@ type Server struct {
|
||||
// names the server gives them, written in each agent's own way where
|
||||
// it has one (mcp_tools_off.go)
|
||||
DisabledTools []string `json:"disabledTools,omitempty"`
|
||||
// OAuth is an OAuth app of the user's own that magpie signs in to the
|
||||
// server as, for one whose sign-in doesn't let magpie register itself
|
||||
// (GitHub's, 新v学员 on Discord). It is magpie's alone: the agents are
|
||||
// given the server as before.
|
||||
OAuth *OAuthApp `json:"oauth,omitempty"`
|
||||
}
|
||||
|
||||
// OAuthApp is an OAuth app made with a server's vendor, by the names
|
||||
// Claude Code gives one (--client-id, --client-secret, --callback-port;
|
||||
// "oauth": {"clientId", "callbackPort"}).
|
||||
type OAuthApp struct {
|
||||
ClientID string `json:"clientId"`
|
||||
ClientSecret string `json:"clientSecret,omitempty"`
|
||||
// CallbackPort is the port of the callback URL the app was made with;
|
||||
// 0 for one made with http://127.0.0.1/callback, which takes any
|
||||
CallbackPort int `json:"callbackPort,omitempty"`
|
||||
}
|
||||
|
||||
// Remote reports whether the server is reached by URL.
|
||||
@@ -83,6 +99,23 @@ func (s *Server) check() error {
|
||||
default:
|
||||
return fmt.Errorf("%s: unknown transport %q", s.Name, s.Transport)
|
||||
}
|
||||
// magpie signs in only to a streamable HTTP server
|
||||
if s.Transport != "http" {
|
||||
s.OAuth = nil
|
||||
} else if s.OAuth != nil {
|
||||
a := *s.OAuth
|
||||
a.ClientID, a.ClientSecret = strings.TrimSpace(a.ClientID), strings.TrimSpace(a.ClientSecret)
|
||||
if a.CallbackPort < 0 || a.CallbackPort > 65535 {
|
||||
return fmt.Errorf("%s: the callback port has to be from 1 to 65535", s.Name)
|
||||
}
|
||||
s.OAuth = &a
|
||||
if a.ClientID == "" {
|
||||
if a.ClientSecret != "" || a.CallbackPort != 0 {
|
||||
return fmt.Errorf("%s: the OAuth app needs its client ID", s.Name)
|
||||
}
|
||||
s.OAuth = nil
|
||||
}
|
||||
}
|
||||
for k := range s.Env {
|
||||
if strings.TrimSpace(k) == "" {
|
||||
delete(s.Env, k)
|
||||
|
||||
@@ -102,7 +102,11 @@ func SignInServer(ctx context.Context, name string) (mcpauth.State, error) {
|
||||
if s.Transport != "http" {
|
||||
return mcpauth.State{}, errNotHTTP
|
||||
}
|
||||
return mcpauth.Start(ctx, s.Name, s.URL)
|
||||
var app *mcpauth.App
|
||||
if s.OAuth != nil {
|
||||
app = &mcpauth.App{ClientID: s.OAuth.ClientID, ClientSecret: s.OAuth.ClientSecret, CallbackPort: s.OAuth.CallbackPort}
|
||||
}
|
||||
return mcpauth.StartWith(ctx, s.Name, s.URL, app)
|
||||
}
|
||||
|
||||
// SignOutServer forgets magpie's sign-in to the server called name, and
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
|
||||
)
|
||||
|
||||
// A server whose sign-in doesn't let magpie register itself (GitHub's, 新v学员
|
||||
// on Discord) is signed in to as the user's own OAuth app, given in the
|
||||
// library by Claude Code's names. Without one, the sign-in says to give
|
||||
// one. The app is magpie's alone: no agent's file is given it, its secret
|
||||
// above all.
|
||||
func TestSignInAsTheUsersOwnApp(t *testing.T) {
|
||||
sandbox(t)
|
||||
f := mcpauthtest.New(t)
|
||||
f.NoRegistration = true
|
||||
f.AddApp("Ov23liAbCdEfGhIjKlMn", "s3cr3t-of-the-app")
|
||||
gh := Server{Name: "github", Transport: "http", URL: f.URL, Agents: []string{"claude", "codex"}}
|
||||
ok(t)(SaveServer("", gh))
|
||||
if _, err := SignInServer(t.Context(), "github"); !errors.Is(err, mcpauth.ErrNoRegistration) {
|
||||
t.Fatalf("without an app: %v", err)
|
||||
}
|
||||
|
||||
gh.OAuth = &OAuthApp{ClientID: " Ov23liAbCdEfGhIjKlMn ", ClientSecret: "s3cr3t-of-the-app\n"}
|
||||
ok(t)(SaveServer("github", gh))
|
||||
v, err := Read(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := v.Servers[0].OAuth; a == nil || a.ClientID != "Ov23liAbCdEfGhIjKlMn" || a.ClientSecret != "s3cr3t-of-the-app" {
|
||||
t.Fatalf("the library's app: %+v", a)
|
||||
}
|
||||
st, err := SignInServer(t.Context(), "github")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.Get(st.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
if got, _ := mcpauth.Progress(st.ID); got.State != "done" {
|
||||
t.Fatalf("sign-in %s: %s", got.State, got.Error)
|
||||
}
|
||||
if r, _ := mcpauth.Get("github"); r.ClientID != "Ov23liAbCdEfGhIjKlMn" || r.AuthMethod != "client_secret_post" {
|
||||
t.Fatalf("record = %+v", r)
|
||||
}
|
||||
if len(f.Registered) != 0 {
|
||||
t.Fatalf("registered %v", f.Registered)
|
||||
}
|
||||
for _, id := range []string{"claude", "codex"} {
|
||||
b, err := os.ReadFile(targetByID(id).MCP.Path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(b), "s3cr3t") || strings.Contains(string(b), "Ov23li") {
|
||||
t.Errorf("%s was given the app: %s", id, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The app is checked as it is saved: only an HTTP server has one, an app
|
||||
// needs its client ID, and a callback port is a port.
|
||||
func TestOAuthAppChecked(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
s Server
|
||||
want *OAuthApp
|
||||
err string
|
||||
}{
|
||||
{Server{Name: "a", Transport: "http", URL: "https://x/mcp", OAuth: &OAuthApp{ClientID: "id", CallbackPort: 8080}}, &OAuthApp{ClientID: "id", CallbackPort: 8080}, ""},
|
||||
{Server{Name: "a", Transport: "http", URL: "https://x/mcp", OAuth: &OAuthApp{ClientID: " "}}, nil, ""},
|
||||
{Server{Name: "a", Transport: "sse", URL: "https://x/sse", OAuth: &OAuthApp{ClientID: "id"}}, nil, ""},
|
||||
{Server{Name: "a", Transport: "stdio", Command: "x", OAuth: &OAuthApp{ClientID: "id"}}, nil, ""},
|
||||
{Server{Name: "a", Transport: "http", URL: "https://x/mcp", OAuth: &OAuthApp{ClientSecret: "s"}}, nil, "client ID"},
|
||||
{Server{Name: "a", Transport: "http", URL: "https://x/mcp", OAuth: &OAuthApp{ClientID: "id", CallbackPort: 70000}}, nil, "callback port"},
|
||||
} {
|
||||
s := c.s
|
||||
err := s.check()
|
||||
if c.err != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), c.err) {
|
||||
t.Errorf("%+v: err = %v", c.s.OAuth, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil || (s.OAuth == nil) != (c.want == nil) || (s.OAuth != nil && *s.OAuth != *c.want) {
|
||||
t.Errorf("%s %+v: %+v, %v", c.s.Transport, c.s.OAuth, s.OAuth, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A backup without keys leaves the app's secret out, as it does a header's
|
||||
// key, and putting it back keeps the secret this computer has for the same
|
||||
// app (not for another).
|
||||
func TestOAuthAppSecretCarried(t *testing.T) {
|
||||
secret := func(k string) bool { return k == "Authorization" }
|
||||
app := func(id, s string) *OAuthApp { return &OAuthApp{ClientID: id, ClientSecret: s, CallbackPort: 3118} }
|
||||
b := &Bundle{MCP: []*Server{{Name: "github", Transport: "http", URL: "https://api.githubcopilot.com/mcp/", OAuth: app("Ov23li1", "kept")}}}
|
||||
b.WithoutSecrets(secret)
|
||||
if a := b.MCP[0].OAuth; *a != *app("Ov23li1", "") {
|
||||
t.Fatalf("without secrets: %+v", a)
|
||||
}
|
||||
have := &Bundle{MCP: []*Server{{Name: "github", OAuth: app("Ov23li1", "here")}}}
|
||||
if a := b.WithSecrets(have, secret).MCP[0].OAuth; *a != *app("Ov23li1", "here") {
|
||||
t.Fatalf("with secrets: %+v", a)
|
||||
}
|
||||
other := &Bundle{MCP: []*Server{{Name: "github", OAuth: app("Ov23li2", "another app's")}}}
|
||||
if a := b.WithSecrets(other, secret).MCP[0].OAuth; a.ClientSecret != "" {
|
||||
t.Fatalf("another app's secret: %+v", a)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package mcpauth_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
)
|
||||
|
||||
// GitHub's remote MCP server (新v学员 on Discord): its sign-in is GitHub's
|
||||
// own OAuth, which has no registration endpoint, so magpie signs in only as
|
||||
// an OAuth app the user made. The answers are GitHub's own, saved from
|
||||
// api.githubcopilot.com/mcp/ and github.com/login/oauth on 2026-10-12, with
|
||||
// the addresses pointed here; the token endpoint answers its errors with a
|
||||
// 200, as GitHub's documents.
|
||||
type gitHub struct {
|
||||
*httptest.Server
|
||||
URL string // the MCP endpoint, <server>/mcp/
|
||||
|
||||
id, secret string // the user's OAuth app
|
||||
refresh bool // tokens that run out, with a refresh token (a GitHub App's)
|
||||
|
||||
mu sync.Mutex
|
||||
codes map[string]string // code → its PKCE challenge
|
||||
redirects []string // the redirect_uri of each authorize
|
||||
forms []url.Values // each token request
|
||||
valid map[string]bool
|
||||
n int
|
||||
}
|
||||
|
||||
func newGitHub(t *testing.T, id, secret string) *gitHub {
|
||||
g := &gitHub{id: id, secret: secret, codes: map[string]string{}, valid: map[string]bool{}}
|
||||
mux := http.NewServeMux()
|
||||
g.Server = httptest.NewServer(mux)
|
||||
t.Cleanup(g.Server.Close)
|
||||
g.URL = g.Server.URL + "/mcp/"
|
||||
oauth := g.Server.URL + "/login/oauth"
|
||||
mux.HandleFunc("/mcp/", func(w http.ResponseWriter, r *http.Request) {
|
||||
g.mu.Lock()
|
||||
ok := g.valid[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||
g.mu.Unlock()
|
||||
if !ok {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.Header().Set("Www-Authenticate", `Bearer error="invalid_request", error_description="No access token was provided in this request", resource_metadata="`+g.Server.URL+`/.well-known/oauth-protected-resource/mcp/"`)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
io.WriteString(w, "bad request: missing required Authorization header\n")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"jsonrpc":"2.0","id":0,"result":{}}`)
|
||||
})
|
||||
mux.HandleFunc("/.well-known/oauth-protected-resource/mcp/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"resource":%q,"authorization_servers":[%q],"scopes_supported":["repo","read:org","read:user","user:email","read:packages","write:packages","read:project","project","gist","notifications"],"bearer_methods_supported":["header"],"resource_name":"GitHub MCP Server"}`, g.URL, oauth)
|
||||
})
|
||||
mux.HandleFunc("/.well-known/oauth-authorization-server/login/oauth", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"issuer":%q,"authorization_endpoint":%q,"token_endpoint":%q,"response_types_supported":["code"],"grant_types_supported":["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:device_code"],"service_documentation":"https://docs.github.com/apps/creating-github-apps/registering-a-github-app/registering-a-github-app","code_challenge_methods_supported":["S256"],"device_authorization_endpoint":%q,"authorization_response_iss_parameter_supported":true,"scopes_supported":["offline_access"]}`,
|
||||
oauth, oauth+"/authorize", oauth+"/access_token", g.Server.URL+"/login/device/code")
|
||||
})
|
||||
mux.HandleFunc("/login/oauth/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
back, err := url.Parse(q.Get("redirect_uri"))
|
||||
// a loopback callback URL registered as http://127.0.0.1/callback
|
||||
// takes any port
|
||||
if q.Get("client_id") != g.id || err != nil || back.Hostname() != "127.0.0.1" || back.Path != "/callback" || q.Get("code_challenge_method") != "S256" {
|
||||
http.Error(w, "The redirect_uri is not associated with this application.", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.n++
|
||||
code := fmt.Sprintf("%020x", g.n)
|
||||
g.codes[code] = q.Get("code_challenge")
|
||||
g.redirects = append(g.redirects, q.Get("redirect_uri"))
|
||||
g.mu.Unlock()
|
||||
bq := back.Query()
|
||||
bq.Set("code", code)
|
||||
bq.Set("state", q.Get("state"))
|
||||
bq.Set("iss", oauth)
|
||||
back.RawQuery = bq.Encode()
|
||||
http.Redirect(w, r, back.String(), http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/login/oauth/access_token", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
g.forms = append(g.forms, r.PostForm)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if r.PostForm.Get("client_id") != g.id {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
io.WriteString(w, `{"error":"Not Found"}`)
|
||||
return
|
||||
}
|
||||
if r.PostForm.Get("client_secret") != g.secret {
|
||||
io.WriteString(w, `{"error":"incorrect_client_credentials","error_description":"The client_id and/or client_secret passed are incorrect.","error_uri":"https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#incorrect-client-credentials"}`)
|
||||
return
|
||||
}
|
||||
switch r.PostForm.Get("grant_type") {
|
||||
case "refresh_token":
|
||||
io.WriteString(w, `{"error":"bad_refresh_token","error_description":"The refresh token passed is incorrect or expired.","error_uri":"https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors"}`)
|
||||
return
|
||||
default:
|
||||
challenge, ok := g.codes[r.PostForm.Get("code")]
|
||||
delete(g.codes, r.PostForm.Get("code"))
|
||||
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
|
||||
if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != challenge {
|
||||
io.WriteString(w, `{"error":"bad_verification_code","error_description":"The code passed is incorrect or expired.","error_uri":"https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code"}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
g.n++
|
||||
a := fmt.Sprintf("gho_%036d", g.n)
|
||||
g.valid[a] = true
|
||||
out := map[string]any{"access_token": a, "token_type": "bearer", "scope": "gist,notifications,project,read:org,read:packages,read:user,repo,user:email,write:packages"}
|
||||
if g.refresh {
|
||||
out["expires_in"], out["refresh_token"], out["refresh_token_expires_in"] = 28800, fmt.Sprintf("ghr_%076d", g.n), 15897600
|
||||
}
|
||||
json.NewEncoder(w).Encode(out)
|
||||
})
|
||||
return g
|
||||
}
|
||||
|
||||
func (g *gitHub) lastForm() url.Values {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.forms[len(g.forms)-1]
|
||||
}
|
||||
|
||||
func (g *gitHub) redirect() string {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.redirects[0]
|
||||
}
|
||||
|
||||
// signInAs signs in as app, standing in for the browser; the State the
|
||||
// sign-in ended in.
|
||||
func signInAs(t *testing.T, name, u string, app *mcpauth.App) mcpauth.State {
|
||||
t.Helper()
|
||||
st, err := mcpauth.StartWith(t.Context(), name, u, app)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.Get(st.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
got, _ := mcpauth.Progress(st.ID)
|
||||
return got
|
||||
}
|
||||
|
||||
// Without an app of the user's own, the sign-in says what to do: make one,
|
||||
// and give it in the server's editor.
|
||||
func TestGitHubWithoutAnApp(t *testing.T) {
|
||||
home(t)
|
||||
g := newGitHub(t, "Ov23liAbCdEfGhIjKlMn", "0123456789abcdef0123456789abcdef01234567")
|
||||
_, err := mcpauth.Start(t.Context(), "github", g.URL)
|
||||
if !errors.Is(err, mcpauth.ErrNoRegistration) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
for _, s := range []string{"OAuth app of your own", "http://127.0.0.1/callback", "client ID"} {
|
||||
if !strings.Contains(err.Error(), s) {
|
||||
t.Errorf("the error doesn't say %q: %v", s, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With the user's app, magpie registers nothing: it signs in as that app,
|
||||
// called back at 127.0.0.1's /callback, and gives the secret in the form,
|
||||
// as GitHub's token endpoint takes it. The record keeps the app, to renew
|
||||
// as it.
|
||||
func TestGitHubSignInAsTheUsersApp(t *testing.T) {
|
||||
home(t)
|
||||
id, secret := "Ov23liAbCdEfGhIjKlMn", "0123456789abcdef0123456789abcdef01234567"
|
||||
g := newGitHub(t, id, secret)
|
||||
if st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret}); st.State != "done" {
|
||||
t.Fatalf("sign-in %s: %s", st.State, st.Error)
|
||||
}
|
||||
r, ok := mcpauth.Get("github")
|
||||
if !ok || !strings.HasPrefix(r.Access, "gho_") || r.ClientID != id || r.Secret != secret || r.AuthMethod != "client_secret_post" || r.Resource != g.URL {
|
||||
t.Fatalf("record = %+v", r)
|
||||
}
|
||||
if !mcpauth.SignedIn("github", g.URL) {
|
||||
t.Fatal("not signed in")
|
||||
}
|
||||
f := g.lastForm()
|
||||
if f.Get("client_id") != id || f.Get("client_secret") != secret || f.Get("grant_type") != "authorization_code" {
|
||||
t.Errorf("token request = %v", f)
|
||||
}
|
||||
if u, _ := url.Parse(g.redirect()); u.Hostname() != "127.0.0.1" || u.Path != "/callback" || u.Port() == "" {
|
||||
t.Errorf("redirect_uri = %s", g.redirect())
|
||||
}
|
||||
}
|
||||
|
||||
// A wrong secret: GitHub answers 200 with its error, which the sign-in
|
||||
// says rather than "no access token".
|
||||
func TestGitHubWrongSecret(t *testing.T) {
|
||||
home(t)
|
||||
id := "Ov23liAbCdEfGhIjKlMn"
|
||||
g := newGitHub(t, id, "0123456789abcdef0123456789abcdef01234567")
|
||||
st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: "wrong"})
|
||||
if st.State != "failed" || !strings.Contains(st.Error, "incorrect_client_credentials") {
|
||||
t.Fatalf("sign-in %s: %s", st.State, st.Error)
|
||||
}
|
||||
if mcpauth.SignedIn("github", g.URL) {
|
||||
t.Fatal("signed in with a wrong secret")
|
||||
}
|
||||
}
|
||||
|
||||
// A callback port is the port the callback comes to, for an app
|
||||
// registered with one.
|
||||
func TestGitHubCallbackPort(t *testing.T) {
|
||||
home(t)
|
||||
id, secret := "Ov23liAbCdEfGhIjKlMn", "0123456789abcdef0123456789abcdef01234567"
|
||||
g := newGitHub(t, id, secret)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
// taken: the sign-in says so
|
||||
if _, err := mcpauth.StartWith(t.Context(), "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret, CallbackPort: port}); err == nil || !strings.Contains(err.Error(), fmt.Sprint(port)) {
|
||||
t.Fatalf("a taken port: %v", err)
|
||||
}
|
||||
ln.Close()
|
||||
if st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret, CallbackPort: port}); st.State != "done" {
|
||||
t.Fatalf("sign-in %s: %s", st.State, st.Error)
|
||||
}
|
||||
if want := fmt.Sprintf("http://127.0.0.1:%d/callback", port); g.redirect() != want {
|
||||
t.Errorf("redirect_uri = %s, want %s", g.redirect(), want)
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh token GitHub won't take again (its 200 bad_refresh_token) runs
|
||||
// the sign-in out, as invalid_grant does elsewhere.
|
||||
func TestGitHubBadRefreshToken(t *testing.T) {
|
||||
home(t)
|
||||
id, secret := "Iv23liAbCdEfGhIjKlMn", "0123456789abcdef0123456789abcdef01234567"
|
||||
g := newGitHub(t, id, secret)
|
||||
g.refresh = true
|
||||
if st := signInAs(t, "github", g.URL, &mcpauth.App{ClientID: id, ClientSecret: secret}); st.State != "done" {
|
||||
t.Fatalf("sign-in %s: %s", st.State, st.Error)
|
||||
}
|
||||
r, _ := mcpauth.Get("github")
|
||||
if r.Refresh == "" || r.Expires == 0 {
|
||||
t.Fatalf("record = %+v", r)
|
||||
}
|
||||
if _, err := mcpauth.Renew(t.Context(), "github", r.Access); !errors.Is(err, mcpauth.ErrExpired) {
|
||||
t.Fatalf("renew: %v", err)
|
||||
}
|
||||
if st := mcpauth.StatusOf("github", g.URL); !st.Dead {
|
||||
t.Fatalf("status = %+v", st)
|
||||
}
|
||||
if f := g.lastForm(); f.Get("client_secret") != secret || f.Get("grant_type") != "refresh_token" {
|
||||
t.Errorf("renewal = %v", f)
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,13 @@ var ErrNoSignIn = errors.New("this server already works without signing in, so t
|
||||
// each agent signs in there itself. The GUI has it in every language.
|
||||
var ErrClientRefused = errors.New("this server's sign-in admits only the apps it lists and turned magpie away, so magpie can't sign in for the agents. The agents given it still have the server's own address: sign in from each agent itself (in Claude Code, run /mcp and pick the server)")
|
||||
|
||||
// ErrNoRegistration is a server whose sign-in doesn't let an app register
|
||||
// itself (GitHub's, 新v学员 on Discord): magpie signs in to it only as an
|
||||
// OAuth app of the user's own, made with the server's vendor, as Claude
|
||||
// Code does with --client-id. The page opens the server's fields for one
|
||||
// on it.
|
||||
var ErrNoRegistration = errors.New("the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie signs in to it only as an OAuth app of your own: make one with the server's vendor (GitHub's under Settings › Developer settings › OAuth Apps), with http://127.0.0.1/callback as its callback URL, then give its client ID and secret under \"OAuth app\" in the server's editor")
|
||||
|
||||
// Record is magpie's sign-in to one server.
|
||||
type Record struct {
|
||||
URL string `json:"url"` // the server's, as the library has it
|
||||
@@ -315,7 +322,7 @@ func renew(ctx context.Context, name string, still func(Record) bool) (string, e
|
||||
t, err := tokenRequest(ctx, r, form)
|
||||
if err != nil {
|
||||
var te *tokenError
|
||||
if errors.As(err, &te) && (te.Code == "invalid_grant" || te.Code == "invalid_client" || te.Status == http.StatusUnauthorized) {
|
||||
if errors.As(err, &te) && (dead(te.Code) || te.Status == http.StatusUnauthorized) {
|
||||
markDead(name, r.Access)
|
||||
return "", ErrExpired
|
||||
}
|
||||
@@ -336,6 +343,16 @@ func renew(ctx context.Context, name string, still func(Record) bool) (string, e
|
||||
return t.Access, err
|
||||
}
|
||||
|
||||
// dead says a token endpoint's error means the refresh token, or the app
|
||||
// it was given to, won't be taken again; GitHub's has its own names.
|
||||
func dead(code string) bool {
|
||||
switch code {
|
||||
case "invalid_grant", "invalid_client", "bad_refresh_token", "incorrect_client_credentials":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Rejected says the server refused access, a token magpie had just
|
||||
// renewed: renewing it again won't help, so the sign-in has run out, and
|
||||
// the page says so instead of calling it signed in beside the server's
|
||||
@@ -414,6 +431,10 @@ func tokenRequest(ctx context.Context, r Record, form url.Values) (tokens, error
|
||||
return tokens{}, te
|
||||
}
|
||||
var t tokens
|
||||
// GitHub's answers its errors with a 200 too
|
||||
if te := (&tokenError{Status: resp.StatusCode}); json.Unmarshal(b, te) == nil && te.Code != "" {
|
||||
return tokens{}, te
|
||||
}
|
||||
if err := json.Unmarshal(b, &t); err != nil {
|
||||
// a few answer as a form, as GitHub's does
|
||||
if v, perr := url.ParseQuery(string(b)); perr == nil && v.Get("access_token") != "" {
|
||||
@@ -648,7 +669,7 @@ func contains(l []string, s string) bool {
|
||||
// redirect.
|
||||
func register(ctx context.Context, m meta, redirect string) (id, secret, method string, err error) {
|
||||
if m.RegisterURL == "" {
|
||||
return "", "", "", errors.New("the server's sign-in doesn't let an app register itself (no dynamic client registration), so magpie can't sign in to it")
|
||||
return "", "", "", ErrNoRegistration
|
||||
}
|
||||
method = "none"
|
||||
if len(m.AuthMethods) > 0 && !contains(m.AuthMethods, "none") {
|
||||
@@ -712,6 +733,18 @@ func register(ctx context.Context, m meta, redirect string) (id, secret, method
|
||||
return out.ID, out.Secret, method, nil
|
||||
}
|
||||
|
||||
// appMethod is how an app of the user's own gives its secret to the token
|
||||
// endpoint: in the form unless the endpoint takes only basic auth.
|
||||
func appMethod(m meta, secret string) string {
|
||||
switch {
|
||||
case secret == "":
|
||||
return "none"
|
||||
case contains(m.AuthMethods, "client_secret_basic") && !contains(m.AuthMethods, "client_secret_post"):
|
||||
return "client_secret_basic"
|
||||
}
|
||||
return "client_secret_post"
|
||||
}
|
||||
|
||||
// ---- the sign-in -------------------------------------------------------------
|
||||
|
||||
// State is where a sign-in stands, for the page to show.
|
||||
@@ -743,23 +776,49 @@ func randomToken(n int) string {
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// App is an OAuth app of the user's own, for a server whose sign-in
|
||||
// doesn't let magpie register itself: Claude Code's --client-id,
|
||||
// --client-secret and --callback-port. Without a CallbackPort the
|
||||
// callback comes to any free port of 127.0.0.1, which a loopback callback
|
||||
// URL registered without one takes (GitHub's, RFC 8252).
|
||||
type App struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
CallbackPort int
|
||||
}
|
||||
|
||||
// Start begins signing magpie in to the server called name at serverURL:
|
||||
// open the State's URL in a browser and the rest happens on its own;
|
||||
// StatusOf follows it.
|
||||
func Start(ctx context.Context, name, serverURL string) (State, error) {
|
||||
return StartWith(ctx, name, serverURL, nil)
|
||||
}
|
||||
|
||||
// StartWith is Start as app when there is one, which magpie then doesn't
|
||||
// register in its place.
|
||||
func StartWith(ctx context.Context, name, serverURL string, app *App) (State, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
m, err := discover(ctx, serverURL)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
port := 0
|
||||
if app != nil {
|
||||
port = app.CallbackPort
|
||||
}
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
if port != 0 {
|
||||
return State{}, fmt.Errorf("the OAuth app's callback port %d is in use by another program: %w", port, err)
|
||||
}
|
||||
return State{}, err
|
||||
}
|
||||
redirect := fmt.Sprintf("http://127.0.0.1:%d/callback", ln.Addr().(*net.TCPAddr).Port)
|
||||
id, secret, method, err := register(ctx, m, redirect)
|
||||
if err != nil {
|
||||
var id, secret, method string
|
||||
if app != nil {
|
||||
id, secret, method = app.ClientID, app.ClientSecret, appMethod(m, app.ClientSecret)
|
||||
} else if id, secret, method, err = register(ctx, m, redirect); err != nil {
|
||||
ln.Close()
|
||||
return State{}, err
|
||||
}
|
||||
|
||||
@@ -57,6 +57,9 @@ type Fake struct {
|
||||
// authorization server does a client it doesn't list: 403, a JSON
|
||||
// content type and the bare body "Forbidden" (#1619)
|
||||
RefuseRegistration bool
|
||||
// NoRegistration leaves the registration endpoint out of the metadata,
|
||||
// as GitHub's does: only an app made beforehand (AddApp) signs in
|
||||
NoRegistration bool
|
||||
|
||||
refuse bool // RefuseTokens
|
||||
codes map[string]codeGrant
|
||||
@@ -101,6 +104,9 @@ func New(t *testing.T) *Fake {
|
||||
"registration_endpoint": issuer + "/register", "code_challenge_methods_supported": []string{"S256"},
|
||||
"token_endpoint_auth_methods_supported": methods(),
|
||||
}
|
||||
if f.NoRegistration {
|
||||
delete(m, "registration_endpoint")
|
||||
}
|
||||
if f.OpenID {
|
||||
m["scopes_supported"] = []string{"openid", "email", "offline_access", "profile"}
|
||||
m["grant_types_supported"] = []string{"authorization_code", "refresh_token"}
|
||||
@@ -334,6 +340,18 @@ func (f *Fake) RefuseTokens() {
|
||||
f.refuse = true
|
||||
}
|
||||
|
||||
// AddApp makes an OAuth app the user signs in as, made with the server's
|
||||
// vendor rather than registered by magpie: with a secret, it gives it in
|
||||
// the token request's form.
|
||||
func (f *Fake) AddApp(id, secret string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.methods[id] = "none"
|
||||
if secret != "" {
|
||||
f.methods[id], f.secrets[id] = "client_secret_post", secret
|
||||
}
|
||||
}
|
||||
|
||||
// ForgetRefresh makes every refresh token given out so far unusable.
|
||||
func (f *Fake) ForgetRefresh() {
|
||||
f.mu.Lock()
|
||||
|
||||
@@ -404,7 +404,8 @@ func saveServer(old *library.Server, line string) tea.Cmd {
|
||||
was, done := "", "added "+s.Name+" · ↵ on it gives it to agents"
|
||||
if old != nil {
|
||||
was, done = old.Name, "saved "+s.Name
|
||||
s.Agents, s.Env, s.Headers = old.Agents, old.Env, old.Headers
|
||||
// and its OAuth app, which only the GUI edits
|
||||
s.Agents, s.Env, s.Headers, s.OAuth = old.Agents, old.Env, old.Headers, old.OAuth
|
||||
}
|
||||
return libCmd(func() (*library.Result, error) { return library.SaveServer(was, s) }, done)()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user