library: an MCP server holds several accounts, one in use, switched in place (Elorynth on X)
A remote server can hold several OAuth sign-ins or several sets of headers (Authorization keys), one in use, which every agent given the server follows. - mcpauth: a server's sign-ins are kept with the one in use at m[name] and the others in Spare (Use, RemoveAccount, StartAccount); the gateway sends the one in use from its next request on. - library: Server.Accounts and Server.Account; `live` lays the account's headers over the server's own in through, remoteHeaders and hubKey, so a switch rewrites each agent's file. A save from the editor keeps them, and a backup or sync carries no account's key (carry.go). Add, use and remove calls, POST /api/library/mcp-account, and mcp-signin takes add and label. - GUI: a server with one set of headers or one sign-in looks as before, with a quiet "+ Add account"; with several, a list with the one in use marked, a click to switch, an x to remove. Four languages. - mcp_rename tests compare mcpauth.Record with reflect.DeepEqual now, as Spare makes it not comparable (the windows one too). Run (mote, at this tree): go test ./internal/library ./internal/mcpauth/... ./internal/gui; go vet darwin, linux nogui, windows; mcp-accounts.test.cjs in chromium and webkit, five languages, plus the existing mcp-* and library-mcp-* and i18n GUI files. Broken by hand: live() returning the server unchanged turns TestServerAccountsSwitchEveryAgent red; the use click removed turns mcp-accounts red. Not tried: a real OAuth server with two real accounts; an agent's upstream Mcp-Session-Id is not reset by a switch.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -3486,11 +3486,15 @@ magpie.plugin("library", (ctx) => {
|
||||
draw();
|
||||
signMoved(name);
|
||||
}));
|
||||
} else if (cur.accounts?.length > 1) {
|
||||
// several sign-ins: the one in use is what every agent is given
|
||||
box.append(acctList(cur.accounts.map((a) => ({ id: a.id, name: a.label || t("Account {n}", { n: cur.accounts.indexOf(a) + 1 }), on: a.active, bad: a.dead })), "signin", name, draw));
|
||||
line.append(addSign(), el("span", "grow"), button(t("Sign out"), "", signOut));
|
||||
} else if (cur.signedIn && !cur.dead) {
|
||||
line.append(tag(t("Signed in"), "lib-signed"), el("span", "note", t("The agents given it use magpie's sign-in")), el("span", "grow"), button(t("Sign out"), "", signOut));
|
||||
line.append(tag(t("Signed in"), "lib-signed"), el("span", "note", t("The agents given it use magpie's sign-in")), el("span", "grow"), name ? addSign() : "", button(t("Sign out"), "", signOut));
|
||||
} else {
|
||||
if (cur.dead) line.append(tag(t("Sign-in ran out"), "warn"));
|
||||
line.append(button(ready?.saves?.() ? t("Save and sign in") : cur.dead ? t("Sign in again") : t("Sign in"), "action", start));
|
||||
line.append(button(ready?.saves?.() ? t("Save and sign in") : cur.dead ? t("Sign in again") : t("Sign in"), "action", () => start()));
|
||||
}
|
||||
box.append(line);
|
||||
// the browser didn't start (#2043): the page to open by hand, rather
|
||||
@@ -3507,7 +3511,19 @@ magpie.plugin("library", (ctx) => {
|
||||
}
|
||||
if (sg?.state === "failed") box.append(el("div", "lib-signin-err", sg.error));
|
||||
};
|
||||
async function start() {
|
||||
// another sign-in to the server, called what the reader types
|
||||
let adding = false;
|
||||
function addSign() {
|
||||
if (!adding) return button(t("+ Add account"), "lib-addacct", () => { adding = true; draw(); box.querySelector(".lib-acct-new input")?.focus(); });
|
||||
const f = el("span", "lib-acct-new");
|
||||
const i = field2("", t("Name"), () => {});
|
||||
i.maxLength = 60;
|
||||
const go = () => { adding = false; start(i.value.trim()); };
|
||||
i.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); e.stopPropagation(); go(); } });
|
||||
f.append(i, button(t("Sign in"), "action", go), button(t("Cancel"), "", () => { adding = false; draw(); }));
|
||||
return f;
|
||||
}
|
||||
async function start(label) {
|
||||
const was = name;
|
||||
mcpSigning = { name, state: "starting" };
|
||||
draw();
|
||||
@@ -3519,7 +3535,7 @@ magpie.plugin("library", (ctx) => {
|
||||
name = saved;
|
||||
mcpSigning = { name, state: "starting" };
|
||||
}
|
||||
const st = await api("library/mcp-signin", { name });
|
||||
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(() => {});
|
||||
mcpSigning = { ...st, name };
|
||||
draw();
|
||||
@@ -3546,6 +3562,76 @@ magpie.plugin("library", (ctx) => {
|
||||
return box;
|
||||
}
|
||||
|
||||
// the accounts of a server, one in use (Elorynth on X): a click on a row
|
||||
// puts it in use, in place; every agent given the server follows. kind is
|
||||
// "signin" for magpie's OAuth sign-ins, "header" for sets of headers
|
||||
function acctList(rows, kind, name, redraw) {
|
||||
const list = el("div", "lib-accts");
|
||||
list.setAttribute("role", "radiogroup");
|
||||
const call = async (op, id) => {
|
||||
try {
|
||||
take(await api("library/mcp-account", { name, kind, op, id }));
|
||||
render();
|
||||
redraw();
|
||||
} catch (e) { status(e.message, "err", 6000); }
|
||||
};
|
||||
for (const r of rows) {
|
||||
const row = el("div", "lib-acct" + (r.on ? " on" : ""));
|
||||
const pick = el("button", "lib-acct-pick");
|
||||
pick.setAttribute("role", "radio");
|
||||
pick.setAttribute("aria-checked", r.on ? "true" : "false");
|
||||
pick.append(el("span", "lib-acct-dot"), el("span", "lib-acct-name", r.name));
|
||||
if (r.bad) pick.append(tag(t("Sign-in ran out"), "warn"));
|
||||
pick.onclick = (e) => { e.stopPropagation(); if (!r.on) call("use", r.id); };
|
||||
row.append(pick);
|
||||
if (r.id !== "") {
|
||||
const x = button("", "lib-x", () => call("remove", r.id));
|
||||
x.append(svg("M4.5 4.5l7 7M11.5 4.5l-7 7", 11, 1.6));
|
||||
x.title = t("Remove");
|
||||
row.append(x);
|
||||
}
|
||||
list.append(row);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
// Authorization headers a server can be asked with, besides its own
|
||||
function headerAccounts(name) {
|
||||
const box = el("div", "lib-hdr-accts");
|
||||
let adding = false;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
const s = lib.servers.find((x) => x.name === name);
|
||||
if (!s) return;
|
||||
const l = s.accounts || [];
|
||||
if (l.length) {
|
||||
box.append(acctList([{ id: "", name: t("Default"), on: !s.account }, ...l.map((a) => ({ id: a.id, name: a.name, on: a.id === s.account }))], "header", name, draw));
|
||||
}
|
||||
if (!adding) {
|
||||
box.append(button(t("+ Add account"), "lib-addacct", () => { adding = true; draw(); box.querySelector(".lib-acct-form input")?.focus(); }));
|
||||
return;
|
||||
}
|
||||
const form = el("div", "lib-acct-form");
|
||||
let label = "", headers = { Authorization: "" };
|
||||
const add = async () => {
|
||||
try {
|
||||
take(await api("library/mcp-account", { name, kind: "header", op: "add", label, headers }));
|
||||
adding = false;
|
||||
render();
|
||||
draw();
|
||||
} catch (e) { status(e.message, "err", 6000); }
|
||||
};
|
||||
const n = field2("", t("Name"), (v) => { label = v; });
|
||||
n.maxLength = 60;
|
||||
form.append(n, pairs(headers, "Authorization", "Bearer …", (v) => { headers = v; }),
|
||||
el("div", "lib-acct-act"), );
|
||||
form.lastChild.append(button(t("Add"), "action", add), button(t("Cancel"), "", () => { adding = false; draw(); }));
|
||||
box.append(form);
|
||||
};
|
||||
box.redraw = draw;
|
||||
draw();
|
||||
return box;
|
||||
}
|
||||
|
||||
function foundServerRow(f) {
|
||||
const s = f.server;
|
||||
const row = el("div", "row lib-row");
|
||||
@@ -3902,6 +3988,7 @@ magpie.plugin("library", (ctx) => {
|
||||
url.classList.add("mono");
|
||||
g.append(...field("URL", url));
|
||||
g.append(...field(t("Headers"), pairs(d.headers, "Authorization", "Bearer …", (v) => { d.headers = v; drawAgents(); }), refHint()));
|
||||
if (s && s.transport === d.transport && s.url) g.append(...field(t("Accounts"), headerAccounts(s.name)));
|
||||
// Sign in saves the form first when it is of another server than
|
||||
// the saved one, so a URL just changed (or a server just added) is
|
||||
// the one signed in to
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// kernel adds them to i18n.js's (magpie.strings).
|
||||
magpie.strings({
|
||||
zh: {
|
||||
"+ Add account": "+ 添加账号",
|
||||
"Account {n}": "账号 {n}",
|
||||
"New skill": "新建技能",
|
||||
"e.g. my-skill": "例如 my-skill",
|
||||
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。",
|
||||
@@ -979,6 +981,8 @@ magpie.strings({
|
||||
"{name} read again from its source": "已重新从来源读取 {name}",
|
||||
},
|
||||
"zh-TW": {
|
||||
"+ Add account": "+ 新增帳號",
|
||||
"Account {n}": "帳號 {n}",
|
||||
"New skill": "新增技能",
|
||||
"e.g. my-skill": "例如 my-skill",
|
||||
"e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。",
|
||||
@@ -1956,6 +1960,8 @@ magpie.strings({
|
||||
"{name} read again from its source": "已重新從來源讀取 {name}",
|
||||
},
|
||||
ja: {
|
||||
"+ Add account": "+ アカウントを追加",
|
||||
"Account {n}": "アカウント {n}",
|
||||
"New skill": "新しいスキル",
|
||||
"e.g. my-skill": "例: my-skill",
|
||||
"e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。",
|
||||
@@ -2933,6 +2939,8 @@ magpie.strings({
|
||||
"{name} read again from its source": "{name} をソースから読み直しました",
|
||||
},
|
||||
de: {
|
||||
"+ Add account": "+ Konto hinzufügen",
|
||||
"Account {n}": "Konto {n}",
|
||||
"New skill": "Neuer Skill",
|
||||
"e.g. my-skill": "z. B. my-skill",
|
||||
"e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.",
|
||||
|
||||
@@ -901,3 +901,21 @@ body.window .lib-list .lib-row { --lib-indent: 38px; }
|
||||
input.lib-memq, input.lib-memtags, input.lib-memwhy { padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-size: 12.5px; outline: none; box-sizing: border-box; transition: border-color .12s, box-shadow .12s; }
|
||||
input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
|
||||
.lib-follow .link { font-size: inherit; padding: 0; margin-left: 2px; }
|
||||
|
||||
/* a server's accounts, one in use (Elorynth on X) */
|
||||
.lib-accts { display: flex; flex-direction: column; gap: 4px; margin-bottom: 6px; }
|
||||
.lib-acct { display: flex; align-items: center; gap: 4px; border: 1px solid var(--line); border-radius: 8px; background: var(--card); transition: background-color .12s ease, border-color .12s ease; }
|
||||
.lib-acct.on { border-color: var(--accent); background: var(--accent-soft); }
|
||||
.lib-acct-pick { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 6px 10px; border: 0; background: none; color: var(--fg); font: inherit; text-align: left; cursor: pointer; }
|
||||
.lib-acct.on .lib-acct-pick { cursor: default; }
|
||||
.lib-acct-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lib-acct-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--faint); box-sizing: border-box; transition: background-color .12s ease, border-color .12s ease; }
|
||||
.lib-acct.on .lib-acct-dot { background: var(--accent); border-color: var(--accent); }
|
||||
.lib-acct .lib-x { margin-right: 4px; }
|
||||
.lib-acct-new { display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.lib-acct-new input { width: 11em; max-width: 100%; }
|
||||
.lib-acct-form { display: flex; flex-direction: column; gap: 6px; }
|
||||
.lib-acct-form > input { max-width: 16em; }
|
||||
.lib-acct-act { display: flex; gap: 8px; }
|
||||
@media (hover: hover) and (pointer: fine) { .lib-acct:not(.on):hover { background: var(--hover, var(--accent-soft)); } }
|
||||
@media (prefers-reduced-motion: reduce) { .lib-acct, .lib-acct-dot { transition: none; } }
|
||||
|
||||
+51
-2
@@ -519,12 +519,22 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
})
|
||||
// magpie signs in to a remote server once, for every agent given it (#615)
|
||||
mux.HandleFunc("POST /api/library/mcp-signin", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Name string }
|
||||
var in struct {
|
||||
Name string
|
||||
Add bool // as another account of the server, called Label
|
||||
Label string
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" {
|
||||
http.Error(rw, "no server", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
st, err := library.SignInServer(r.Context(), in.Name)
|
||||
var st mcpauth.State
|
||||
var err error
|
||||
if in.Add {
|
||||
st, err = library.SignInServerAccount(r.Context(), in.Name, in.Label)
|
||||
} else {
|
||||
st, err = library.SignInServer(r.Context(), in.Name)
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
@@ -543,6 +553,45 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
mcpauth.Cancel(r.PathValue("id"))
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
// a server's accounts (Elorynth on X): Kind "signin" is magpie's OAuth
|
||||
// sign-ins to it, "header" the sets of headers it is asked with; ID "" in
|
||||
// a use is the server's own headers
|
||||
mux.HandleFunc("POST /api/library/mcp-account", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Name, Kind, Op, ID, Label string
|
||||
Headers map[string]string
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" {
|
||||
http.Error(rw, "no server", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var err error
|
||||
switch in.Kind + "/" + in.Op {
|
||||
case "signin/use":
|
||||
err = library.UseSignIn(in.Name, in.ID)
|
||||
case "signin/remove":
|
||||
err = library.RemoveSignIn(in.Name, in.ID)
|
||||
case "header/add":
|
||||
_, err = library.AddServerAccount(in.Name, in.Label, in.Headers)
|
||||
case "header/use":
|
||||
_, err = library.UseServerAccount(in.Name, in.ID)
|
||||
case "header/remove":
|
||||
_, err = library.RemoveServerAccount(in.Name, in.ID)
|
||||
default:
|
||||
http.Error(rw, "not an account call", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
v, err := libraryView(nil)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, v)
|
||||
})
|
||||
mux.HandleFunc("POST /api/library/mcp-signout", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Name string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name == "" {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Elorynth on X: a remote MCP server holds several Authorization headers or
|
||||
// several OAuth sign-ins, one in use, switched in place. With one, the
|
||||
// editor looks as it did, plus a quiet "Add account". In every language, in
|
||||
// both engines. 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 HOME = "/Users/aimer";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
|
||||
const base = () => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("codex", "Codex"), agent("claude", "Claude Code")],
|
||||
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [],
|
||||
servers: [
|
||||
{ name: "web", transport: "http", url: "https://web.example/mcp", headers: { Authorization: "Bearer base" }, agents: ["codex", "claude"] },
|
||||
{ name: "two", transport: "http", url: "https://two.example/mcp", headers: {}, agents: ["codex"], account: "2",
|
||||
accounts: [{ id: "1", name: "personal", headers: { Authorization: "Bearer p" } }, { id: "2", name: "work", headers: { Authorization: "Bearer w" } }] },
|
||||
{ name: "one", transport: "http", url: "https://one.example/mcp", agents: ["codex"], signIn: { signedIn: true, at: 1 } },
|
||||
{ name: "many", transport: "http", url: "https://many.example/mcp", agents: ["codex"],
|
||||
signIn: { signedIn: true, at: 1, accounts: [{ id: "1", label: "me", active: true }, { id: "2", label: "team" }] } },
|
||||
],
|
||||
});
|
||||
|
||||
function server(calls) {
|
||||
const lib = base();
|
||||
const lang = process.env.LANG_UNDER_TEST;
|
||||
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-account") {
|
||||
const b = req.postDataJSON();
|
||||
calls.push([b.name, b.kind, b.op, b.id ?? "", b.label ?? "", JSON.stringify(b.headers ?? {})].join("|"));
|
||||
const s = lib.servers.find((x) => x.name === b.name);
|
||||
if (b.kind === "header") {
|
||||
s.accounts = s.accounts || [];
|
||||
if (b.op === "add") { const id = String(s.accounts.length + 1); s.accounts.push({ id, name: b.label, headers: b.headers }); s.account = id; }
|
||||
if (b.op === "use") s.account = b.id;
|
||||
if (b.op === "remove") { s.accounts = s.accounts.filter((a) => a.id !== b.id); if (s.account === b.id) s.account = ""; if (!s.accounts.length) delete s.accounts; }
|
||||
} else if (b.op === "use") s.signIn.accounts.forEach((a) => { a.active = a.id === b.id; });
|
||||
return route.fulfill({ json: lib });
|
||||
}
|
||||
if (url.pathname === "/api/library/mcp-signin") {
|
||||
calls.push("signin " + JSON.stringify(req.postDataJSON()));
|
||||
return route.fulfill({ status: 400, json: { error: "stop here" } });
|
||||
}
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
// core words (i18n.js) and the Library plugin's own
|
||||
const words = {
|
||||
en: { add: "+ Add account", name: "Name", def: "Default", addBtn: "Add", accounts: "Accounts", signIn: "Sign in" },
|
||||
zh: { add: "+ 添加账号", name: "名称", def: "默认", addBtn: "添加", accounts: "账号", signIn: "登录" },
|
||||
"zh-TW": { add: "+ 新增帳號", name: "名稱", def: "預設", addBtn: "新增", accounts: "帳號", signIn: "登入" },
|
||||
ja: { add: "+ アカウントを追加", name: "名前", def: "デフォルト", addBtn: "追加", accounts: "アカウント", signIn: "サインイン" },
|
||||
de: { add: "+ Konto hinzufügen", name: "Name", def: "Standard", addBtn: "Hinzufügen", accounts: "Konten", signIn: "Anmelden" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a server's accounts are switched in its editor", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
if (errors.length) console.log(errors);
|
||||
await browser.close();
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
for (const lang of Object.keys(words)) {
|
||||
await t.test(lang, async () => {
|
||||
const w = words[lang];
|
||||
const calls = [];
|
||||
process.env.LANG_UNDER_TEST = lang;
|
||||
const ctx = await browser.newContext({ viewport: { width: 980, height: 800 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(calls));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const row = (name) => page.locator("#view-library .lib-row", { has: page.locator(".name", { hasText: new RegExp("^" + name) }) });
|
||||
const close = async () => { await page.keyboard.press("Escape"); await page.locator("#modal .lib-editor").waitFor({ state: "detached" }); };
|
||||
await row("web").waitFor();
|
||||
|
||||
// one set of headers: no list, only the quiet button
|
||||
await row("web").click();
|
||||
const accts = page.locator("#modal .lib-hdr-accts");
|
||||
await accts.waitFor();
|
||||
assert.equal(await accts.locator(".lib-acct").count(), 0);
|
||||
await accts.getByRole("button", { name: w.add, exact: true }).click();
|
||||
await accts.locator(".lib-acct-form > input").fill("work");
|
||||
await accts.locator(".lib-pair input").nth(1).fill("Bearer sk-work");
|
||||
await accts.getByRole("button", { name: w.addBtn, exact: true }).click();
|
||||
await accts.locator(".lib-acct.on", { hasText: "work" }).waitFor();
|
||||
assert.equal(calls.at(-1), 'web|header|add||work|{"Authorization":"Bearer sk-work"}');
|
||||
assert.deepEqual(await accts.locator(".lib-acct-name").allTextContents(), [w.def, "work"]);
|
||||
|
||||
// a click on Default puts the server's own headers back in use
|
||||
await accts.locator(".lib-acct-pick", { hasText: w.def }).click();
|
||||
await accts.locator(".lib-acct.on", { hasText: w.def }).waitFor();
|
||||
assert.equal(calls.at(-1), "web|header|use|||{}");
|
||||
assert.equal(await accts.locator('[aria-checked="true"]').count(), 1);
|
||||
await accts.locator(".lib-acct", { hasText: "work" }).locator(".lib-x").click();
|
||||
await accts.locator(".lib-acct").first().waitFor({ state: "detached" });
|
||||
assert.equal(calls.at(-1), "web|header|remove|1||{}");
|
||||
await close();
|
||||
|
||||
// several: the one in use is marked; another is put in use in place
|
||||
await row("two").click();
|
||||
const two = page.locator("#modal .lib-hdr-accts");
|
||||
await two.locator(".lib-acct.on", { hasText: "work" }).waitFor();
|
||||
await two.locator(".lib-acct-pick", { hasText: "personal" }).click();
|
||||
await two.locator(".lib-acct.on", { hasText: "personal" }).waitFor();
|
||||
assert.equal(calls.at(-1), "two|header|use|1||{}");
|
||||
assert.equal(await two.locator(".lib-acct.on").count(), 1);
|
||||
await close();
|
||||
|
||||
// an OAuth server with one sign-in: its line as before, and the quiet button
|
||||
await row("one").click();
|
||||
const one = page.locator("#modal .lib-signin");
|
||||
await one.waitFor();
|
||||
assert.equal(await one.locator(".lib-accts").count(), 0);
|
||||
await one.getByRole("button", { name: w.add, exact: true }).click();
|
||||
await one.locator(".lib-acct-new input").fill("team");
|
||||
await one.getByRole("button", { name: w.signIn, exact: true }).click();
|
||||
await one.locator(".lib-signin-err").waitFor();
|
||||
assert.equal(calls.at(-1), 'signin {"name":"one","add":true,"label":"team"}');
|
||||
await close();
|
||||
|
||||
// several sign-ins: a list, the one in use marked
|
||||
await row("many").click();
|
||||
const many = page.locator("#modal .lib-signin");
|
||||
await many.locator(".lib-acct.on", { hasText: "me" }).waitFor();
|
||||
await many.locator(".lib-acct-pick", { hasText: "team" }).click();
|
||||
await many.locator(".lib-acct.on", { hasText: "team" }).waitFor();
|
||||
assert.equal(calls.at(-1), "many|signin|use|2||{}");
|
||||
assert.equal(await many.locator(".lib-acct.on").count(), 1);
|
||||
// the page doesn't overflow sideways at a narrow width
|
||||
await page.setViewportSize({ width: 420, height: 800 });
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -317,6 +317,11 @@ 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)
|
||||
c.Accounts = nil
|
||||
for _, a := range s.Accounts {
|
||||
a.Headers = blank(a.Headers, secret)
|
||||
c.Accounts = append(c.Accounts, a)
|
||||
}
|
||||
// an OAuth app's secret is a key too; its client ID isn't
|
||||
if s.OAuth != nil && s.OAuth.ClientSecret != "" {
|
||||
a := *s.OAuth
|
||||
@@ -355,6 +360,13 @@ 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)
|
||||
c.Accounts = nil
|
||||
for _, a := range s.Accounts {
|
||||
if j := slices.IndexFunc(have.MCP[i].Accounts, func(h Account) bool { return h.ID == a.ID }); j >= 0 {
|
||||
a.Headers = filled(a.Headers, have.MCP[i].Accounts[j].Headers, secret)
|
||||
}
|
||||
c.Accounts = append(c.Accounts, a)
|
||||
}
|
||||
// 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
|
||||
|
||||
@@ -52,6 +52,12 @@ type Server struct {
|
||||
// (GitHub's, 新v学员 on Discord). It is magpie's alone: the agents are
|
||||
// given the server as before.
|
||||
OAuth *OAuthApp `json:"oauth,omitempty"`
|
||||
// Accounts are further sets of headers for the server (Elorynth on X:
|
||||
// several keys, one in use), each laid over Headers, and Account is the
|
||||
// one the agents are given ("" for Headers as they are). magpie's own
|
||||
// OAuth sign-ins to the server have their accounts in mcpauth.
|
||||
Accounts []Account `json:"accounts,omitempty"`
|
||||
Account string `json:"account,omitempty"`
|
||||
// StartupTimeout is the seconds an agent waits for the server to start
|
||||
// and list its tools: Codex's startup_timeout_sec (#3168), the only
|
||||
// agent given it. 0 leaves it to the agent (Codex's own is 30s).
|
||||
@@ -188,7 +194,7 @@ func (s *Server) check() error {
|
||||
delete(s.Headers, k)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return s.checkAccounts()
|
||||
}
|
||||
|
||||
// spacedProgram is a program by full path that has spaces in it, typed
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
)
|
||||
|
||||
// A remote server can hold several accounts (Elorynth on X: several OAuth
|
||||
// sign-ins or Authorization headers, one in use, switched in a click). A
|
||||
// key is an Account of the server's own, headers laid over the server's
|
||||
// Headers; an OAuth sign-in is one of mcpauth's, kept with the others. The
|
||||
// one in use is what every agent is given: a key's headers are written
|
||||
// into each agent's entry by `live` before the entry is built (through),
|
||||
// and a sign-in is what the gateway's /mcp/<name> sends, so a switch is a
|
||||
// change like any other and each agent's file follows it.
|
||||
|
||||
const maxAccountName = 60
|
||||
|
||||
// Account is one set of headers a server is asked with.
|
||||
type Account struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
// live is the server as the agents are given it: with the headers of the
|
||||
// account in use laid over its own, a name either has by any case going
|
||||
// to the account's.
|
||||
func (s *Server) live() *Server {
|
||||
i := slices.IndexFunc(s.Accounts, func(a Account) bool { return a.ID == s.Account })
|
||||
if s.Account == "" || i < 0 {
|
||||
return s
|
||||
}
|
||||
c := *s
|
||||
c.Headers = maps.Clone(s.Headers)
|
||||
if c.Headers == nil {
|
||||
c.Headers = map[string]string{}
|
||||
}
|
||||
for k, v := range s.Accounts[i].Headers {
|
||||
for have := range c.Headers {
|
||||
if strings.EqualFold(have, k) {
|
||||
delete(c.Headers, have)
|
||||
}
|
||||
}
|
||||
c.Headers[k] = v
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
// checkAccounts cleans the accounts: a server by command has none, each
|
||||
// has a name (not another's, at most maxAccountName characters) and an id,
|
||||
// and the one in use is one of them.
|
||||
func (s *Server) checkAccounts() error {
|
||||
if !s.Remote() {
|
||||
s.Accounts, s.Account = nil, ""
|
||||
return nil
|
||||
}
|
||||
seenName, seenID := map[string]bool{}, map[string]bool{}
|
||||
for i := range s.Accounts {
|
||||
a := &s.Accounts[i]
|
||||
a.Name = strings.TrimSpace(a.Name)
|
||||
if a.Name == "" || len([]rune(a.Name)) > maxAccountName {
|
||||
return fmt.Errorf("%s: an account's name is from 1 to %d characters", s.Name, maxAccountName)
|
||||
}
|
||||
if key := strings.ToLower(a.Name); seenName[key] {
|
||||
return fmt.Errorf("%s: two accounts are called %s", s.Name, a.Name)
|
||||
} else {
|
||||
seenName[key] = true
|
||||
}
|
||||
if a.ID == "" || seenID[a.ID] {
|
||||
return fmt.Errorf("%s: an account has no id of its own", s.Name)
|
||||
}
|
||||
seenID[a.ID] = true
|
||||
for k := range a.Headers {
|
||||
if strings.TrimSpace(k) == "" {
|
||||
delete(a.Headers, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(s.Accounts) == 0 {
|
||||
s.Accounts = nil
|
||||
}
|
||||
if s.Account != "" && !seenID[s.Account] {
|
||||
s.Account = ""
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddServerAccount gives the server another account, a set of headers (a
|
||||
// key as Authorization), and puts it in use.
|
||||
func AddServerAccount(name, label string, headers map[string]string) (*Result, error) {
|
||||
h := map[string]string{}
|
||||
for k, v := range headers {
|
||||
if k = strings.TrimSpace(k); k != "" {
|
||||
h[k] = v
|
||||
}
|
||||
}
|
||||
if len(h) == 0 {
|
||||
return nil, fmt.Errorf("an account needs a header, as Authorization")
|
||||
}
|
||||
return change(func(l *Library) error {
|
||||
s := l.server(name)
|
||||
if s == nil {
|
||||
return fmt.Errorf("no server called %s", name)
|
||||
}
|
||||
if !s.Remote() {
|
||||
return fmt.Errorf("%s runs as a command: accounts are for a server by URL", name)
|
||||
}
|
||||
top := 0
|
||||
for _, a := range s.Accounts {
|
||||
n, _ := strconv.Atoi(a.ID)
|
||||
top = max(top, n)
|
||||
}
|
||||
s.Accounts = append(s.Accounts, Account{ID: strconv.Itoa(top + 1), Name: label, Headers: h})
|
||||
s.Account = s.Accounts[len(s.Accounts)-1].ID
|
||||
return s.checkAccounts()
|
||||
})
|
||||
}
|
||||
|
||||
// UseServerAccount puts an account of the server in use: "" is the
|
||||
// server's own headers.
|
||||
func UseServerAccount(name, id string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
s := l.server(name)
|
||||
if s == nil {
|
||||
return fmt.Errorf("no server called %s", name)
|
||||
}
|
||||
if id != "" && !slices.ContainsFunc(s.Accounts, func(a Account) bool { return a.ID == id }) {
|
||||
return fmt.Errorf("%s has no such account", name)
|
||||
}
|
||||
s.Account = id
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RemoveServerAccount takes an account away from the server; the one in
|
||||
// use going puts the server's own headers back in use.
|
||||
func RemoveServerAccount(name, id string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
s := l.server(name)
|
||||
if s == nil {
|
||||
return fmt.Errorf("no server called %s", name)
|
||||
}
|
||||
i := slices.IndexFunc(s.Accounts, func(a Account) bool { return a.ID == id })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("%s has no such account", name)
|
||||
}
|
||||
s.Accounts = slices.Delete(slices.Clone(s.Accounts), i, i+1)
|
||||
return s.checkAccounts()
|
||||
})
|
||||
}
|
||||
|
||||
// SignInServerAccount is SignInServer as another account of the server,
|
||||
// put in use once signed in.
|
||||
func SignInServerAccount(ctx context.Context, name, label string) (mcpauth.State, error) {
|
||||
return signInServer(ctx, name, &label)
|
||||
}
|
||||
|
||||
// UseSignIn puts one of magpie's sign-ins to the server in use.
|
||||
func UseSignIn(name, id string) error { return mcpauth.Use(name, id) }
|
||||
|
||||
// RemoveSignIn forgets one of magpie's sign-ins to the server.
|
||||
func RemoveSignIn(name, id string) error { return mcpauth.RemoveAccount(name, id) }
|
||||
@@ -0,0 +1,99 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A server holds several Authorization headers, one in use (Elorynth on
|
||||
// X): switching rewrites what every agent is given, adding and removing
|
||||
// keep the server's own headers, and the account stays through a save
|
||||
// from the editor, which doesn't send it.
|
||||
func TestServerAccountsSwitchEveryAgent(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
codex := filepath.Join(h, ".codex/config.toml")
|
||||
srv := Server{Name: "web", Transport: "http", URL: "https://x.example/mcp",
|
||||
Headers: map[string]string{"Authorization": "Bearer base-key", "X-Team": "a"}, Agents: []string{"codex", "claude"}}
|
||||
ok(t)(SaveServer("", srv))
|
||||
if !strings.Contains(read(t, codex), "base-key") {
|
||||
t.Fatalf("the server's own key isn't written:\n%s", read(t, codex))
|
||||
}
|
||||
|
||||
ok(t)(AddServerAccount("web", "work", map[string]string{"authorization": "Bearer work-key"}))
|
||||
cfg := read(t, codex)
|
||||
if !strings.Contains(cfg, "work-key") || strings.Contains(cfg, "base-key") {
|
||||
t.Fatalf("the new account isn't the one in use:\n%s", cfg)
|
||||
}
|
||||
if !strings.Contains(cfg, "X-Team") {
|
||||
t.Errorf("a header the account doesn't set went:\n%s", cfg)
|
||||
}
|
||||
_, err := AddServerAccount("web", "Work", map[string]string{"Authorization": "x"})
|
||||
if err == nil {
|
||||
t.Errorf("two accounts called alike")
|
||||
}
|
||||
|
||||
// an editor's save doesn't send the accounts
|
||||
got := lib(t).server("web")
|
||||
save := *got
|
||||
save.Accounts, save.Account = nil, ""
|
||||
ok(t)(SaveServer("web", save))
|
||||
if s := lib(t).server("web"); len(s.Accounts) != 1 || s.Account != s.Accounts[0].ID {
|
||||
t.Fatalf("a save lost the accounts: %+v", s)
|
||||
}
|
||||
|
||||
ok(t)(UseServerAccount("web", ""))
|
||||
if cfg := read(t, codex); !strings.Contains(cfg, "base-key") || strings.Contains(cfg, "work-key") {
|
||||
t.Fatalf("back to the server's own headers:\n%s", cfg)
|
||||
}
|
||||
_, err = UseServerAccount("web", "nope")
|
||||
if err == nil {
|
||||
t.Errorf("an account that isn't there was put in use")
|
||||
}
|
||||
id := lib(t).server("web").Accounts[0].ID
|
||||
ok(t)(UseServerAccount("web", id))
|
||||
ok(t)(RemoveServerAccount("web", id))
|
||||
if s := lib(t).server("web"); len(s.Accounts) != 0 || s.Account != "" {
|
||||
t.Errorf("not removed: %+v", s)
|
||||
}
|
||||
if cfg := read(t, codex); !strings.Contains(cfg, "base-key") || strings.Contains(cfg, "work-key") {
|
||||
t.Errorf("the account in use removed, the agents keep its key:\n%s", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerAccountsNotForACommand(t *testing.T) {
|
||||
sandbox(t)
|
||||
ok(t)(SaveServer("", Server{Name: "loc", Transport: "stdio", Command: "x", Agents: []string{"codex"}}))
|
||||
if _, err := AddServerAccount("loc", "a", map[string]string{"Authorization": "x"}); err == nil {
|
||||
t.Errorf("a command was given an account")
|
||||
}
|
||||
if _, err := AddServerAccount("loc", "a", nil); err == nil {
|
||||
t.Errorf("an account with no header")
|
||||
}
|
||||
}
|
||||
|
||||
// A backup or a sync carries no account's key, and brings it back from
|
||||
// the copy here.
|
||||
func TestServerAccountKeysAreSecrets(t *testing.T) {
|
||||
secret := func(k string) bool { return strings.EqualFold(k, "Authorization") }
|
||||
s := Server{Name: "web", Transport: "http", URL: "https://x.example/mcp",
|
||||
Accounts: []Account{{ID: "1", Name: "w", Headers: map[string]string{"Authorization": "Bearer sk-secret-123456"}}}}
|
||||
b := &Bundle{MCP: []*Server{&s}}
|
||||
b.WithoutSecrets(secret)
|
||||
if strings.Contains(mustJSON(t, b), "sk-secret-123456") {
|
||||
t.Errorf("an account's key is carried: %s", mustJSON(t, b))
|
||||
}
|
||||
back := b.WithSecrets(&Bundle{MCP: []*Server{&s}}, secret)
|
||||
if back.MCP[0].Accounts[0].Headers["Authorization"] != "Bearer sk-secret-123456" {
|
||||
t.Errorf("not brought back: %s", mustJSON(t, back))
|
||||
}
|
||||
}
|
||||
|
||||
func lib(t *testing.T) *Library {
|
||||
t.Helper()
|
||||
l, err := load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
@@ -805,6 +805,7 @@ func exitHealth(err error, errs *tail) ServerHealth {
|
||||
// remoteHeaders are the server's own headers, with magpie's token when it
|
||||
// is signed in to it: the agents reach it with that too.
|
||||
func remoteHeaders(ctx context.Context, s *Server) (http.Header, *ServerHealth) {
|
||||
s = s.live()
|
||||
h := http.Header{}
|
||||
headers, unset := expandAll(s.Headers)
|
||||
if len(unset) > 0 {
|
||||
|
||||
@@ -419,10 +419,12 @@ var hubPool = struct {
|
||||
// hubKey is the server as it is run: an edit, or a sign-in since, is
|
||||
// another to start.
|
||||
func hubKey(s *Server) string {
|
||||
c := *s
|
||||
c.Agents, c.DisabledTools = nil, nil
|
||||
c := *s.live()
|
||||
c.Agents, c.DisabledTools, c.Accounts, c.Account = nil, nil, nil, ""
|
||||
b, _ := json.Marshal(c)
|
||||
return fmt.Sprintf("%s|%v", b, s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL))
|
||||
// the sign-in in use too: another account is another to start
|
||||
in := s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL)
|
||||
return fmt.Sprintf("%s|%v|%s", b, in, map[bool]string{true: mcpauth.InUse(s.Name)}[in])
|
||||
}
|
||||
|
||||
func backendOf(s *Server) *backend {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
@@ -66,7 +67,7 @@ func TestSaveServerRenameKeepsOAuth(t *testing.T) {
|
||||
}
|
||||
assertRecord := func(name string, want mcpauth.Record) {
|
||||
t.Helper()
|
||||
if got, found := mcpauth.Get(name); !found || got != want {
|
||||
if got, found := mcpauth.Get(name); !found || !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("OAuth record for %s changed: found=%v got=%+v want=%+v", name, found, got, want)
|
||||
}
|
||||
if token, err := mcpauth.Token(t.Context(), name); err != nil || token != want.Access {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
@@ -68,7 +69,7 @@ func TestSaveServerRenameSignInWriteFailure(t *testing.T) {
|
||||
t.Errorf("file changed after failed sign-in rename: %s", p)
|
||||
}
|
||||
}
|
||||
if got, found := mcpauth.Get("alpha"); !found || got != before {
|
||||
if got, found := mcpauth.Get("alpha"); !found || !reflect.DeepEqual(got, before) {
|
||||
t.Errorf("failed rename changed the old sign-in: found=%v record=%+v", found, got)
|
||||
}
|
||||
if _, found := mcpauth.Get("gamma"); found {
|
||||
|
||||
@@ -48,6 +48,7 @@ func relaysAny() bool {
|
||||
// given it. Only a streamable HTTP server is relayed: an SSE one's stream
|
||||
// names the address to post to, which would have to be rewritten.
|
||||
func through(s *Server, base string) *Server {
|
||||
s = s.live()
|
||||
if s.Plugin != "" {
|
||||
// a plugin's tools, which the gateway serves itself
|
||||
c := *s
|
||||
@@ -99,6 +100,10 @@ var errNotHTTP = errors.New("magpie signs in only to a server reached over strea
|
||||
// SignInServer starts signing magpie in to the library's server called
|
||||
// name: the State's URL is the page to open in a browser.
|
||||
func SignInServer(ctx context.Context, name string) (mcpauth.State, error) {
|
||||
return signInServer(ctx, name, nil)
|
||||
}
|
||||
|
||||
func signInServer(ctx context.Context, name string, label *string) (mcpauth.State, error) {
|
||||
mu.Lock()
|
||||
l, err := load()
|
||||
mu.Unlock()
|
||||
@@ -116,6 +121,9 @@ func SignInServer(ctx context.Context, name string) (mcpauth.State, error) {
|
||||
if s.OAuth != nil {
|
||||
app = &mcpauth.App{ClientID: s.OAuth.ClientID, ClientSecret: s.OAuth.ClientSecret, CallbackPort: s.OAuth.CallbackPort}
|
||||
}
|
||||
if label != nil {
|
||||
return mcpauth.StartAccount(ctx, s.Name, s.URL, app, *label)
|
||||
}
|
||||
return mcpauth.StartWith(ctx, s.Name, s.URL, app)
|
||||
}
|
||||
|
||||
|
||||
@@ -812,6 +812,11 @@ func SaveServer(old string, s Server) (*Result, error) {
|
||||
if s.DisabledTools == nil {
|
||||
s.DisabledTools = l.MCP[i].DisabledTools
|
||||
}
|
||||
// so do the accounts, which have calls of their own
|
||||
if s.Accounts == nil && s.Account == "" {
|
||||
s.Accounts, s.Account = l.MCP[i].Accounts, l.MCP[i].Account
|
||||
_ = s.checkAccounts()
|
||||
}
|
||||
// a plugin's server stays the plugin's, and on this computer
|
||||
if p := l.MCP[i].Plugin; p != "" && s.Plugin == "" {
|
||||
s.Plugin, s.Local = p, true
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package mcpauth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/mcpauth"
|
||||
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
|
||||
)
|
||||
|
||||
func accountLabels(name string) []string {
|
||||
var out []string
|
||||
for _, a := range mcpauth.Accounts(name) {
|
||||
l := a.Label
|
||||
if a.Active {
|
||||
l += "*"
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A second sign-in to a server joins the first and is the one in use; the
|
||||
// first is kept, and switching back gives its token again, with every
|
||||
// reader (Get, Token) seeing only the account in use.
|
||||
func TestAccountsSwitchInPlace(t *testing.T) {
|
||||
home(t)
|
||||
f := mcpauthtest.New(t)
|
||||
f.SignIn(t, "neon")
|
||||
first, _ := mcpauth.Get("neon")
|
||||
if st := mcpauth.StatusOf("neon", f.URL); len(st.Accounts) != 0 {
|
||||
t.Fatalf("one sign-in lists accounts: %+v", st.Accounts)
|
||||
}
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "work")
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "side")
|
||||
if got := accountLabels("neon"); !slices.Equal(got, []string{"", "work", "side*"}) {
|
||||
t.Fatalf("accounts = %q", got)
|
||||
}
|
||||
cur, _ := mcpauth.Get("neon")
|
||||
if cur.Access == first.Access {
|
||||
t.Fatal("the new sign-in is not in use")
|
||||
}
|
||||
if err := mcpauth.Use("neon", "1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the list keeps its places; only the one in use moves
|
||||
if got := accountLabels("neon"); !slices.Equal(got, []string{"*", "work", "side"}) {
|
||||
t.Fatalf("after Use: %q", got)
|
||||
}
|
||||
tok, err := mcpauth.Token(context.Background(), "neon")
|
||||
if err != nil || tok != first.Access {
|
||||
t.Fatalf("Token = %q, %v; want the first account's %q", tok, err, first.Access)
|
||||
}
|
||||
if err := mcpauth.Use("neon", "nope"); err != mcpauth.ErrNoAccount {
|
||||
t.Errorf("Use of no account: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Signing in again (a sign-in that ran out) replaces the account in use and
|
||||
// leaves the others and its place in the list.
|
||||
func TestSignInAgainKeepsTheOtherAccounts(t *testing.T) {
|
||||
home(t)
|
||||
f := mcpauthtest.New(t)
|
||||
f.SignIn(t, "neon")
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "work")
|
||||
before, _ := mcpauth.Get("neon")
|
||||
f.SignIn(t, "neon")
|
||||
after, _ := mcpauth.Get("neon")
|
||||
if after.Access == before.Access {
|
||||
t.Fatal("not signed in again")
|
||||
}
|
||||
if got := accountLabels("neon"); !slices.Equal(got, []string{"", "work*"}) {
|
||||
t.Fatalf("accounts = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveAccount(t *testing.T) {
|
||||
home(t)
|
||||
f := mcpauthtest.New(t)
|
||||
f.SignIn(t, "neon")
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "work")
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "side")
|
||||
// the one in use goes: the first of the others is put in use
|
||||
if err := mcpauth.RemoveAccount("neon", "3"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := accountLabels("neon"); !slices.Equal(got, []string{"*", "work"}) {
|
||||
t.Fatalf("accounts = %q", got)
|
||||
}
|
||||
// another goes: the one in use stays
|
||||
if err := mcpauth.RemoveAccount("neon", "2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := accountLabels("neon"); !slices.Equal(got, []string{"*"}) {
|
||||
t.Fatalf("accounts = %q", got)
|
||||
}
|
||||
if err := mcpauth.RemoveAccount("neon", "1"); err != nil || mcpauth.SignedIn("neon", f.URL) {
|
||||
t.Fatalf("the last one: %v, signed in %v", err, mcpauth.SignedIn("neon", f.URL))
|
||||
}
|
||||
if err := mcpauth.RemoveAccount("neon", "1"); err != mcpauth.ErrNoAccount {
|
||||
t.Errorf("no account: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A name an account has is not given to another, and the sign-ins go with a
|
||||
// renamed server and out with a signed-out one.
|
||||
func TestAccountsFollowTheServer(t *testing.T) {
|
||||
home(t)
|
||||
f := mcpauthtest.New(t)
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "work")
|
||||
if _, err := mcpauth.StartAccount(context.Background(), "neon", f.URL, nil, " WORK "); err != mcpauth.ErrLabelUsed {
|
||||
t.Fatalf("a used label: %v", err)
|
||||
}
|
||||
mcpauthtest.SignInAccount(t, "neon", f.URL, "side")
|
||||
if err := mcpauth.Rename("neon", "lime"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := accountLabels("lime"); !slices.Equal(got, []string{"work", "side*"}) {
|
||||
t.Fatalf("renamed: %q", got)
|
||||
}
|
||||
if err := mcpauth.SignOut("lime"); err != nil || len(mcpauth.Accounts("lime")) != 0 {
|
||||
t.Fatalf("sign-out leaves %v (%v)", mcpauth.Accounts("lime"), err)
|
||||
}
|
||||
}
|
||||
+225
-5
@@ -32,6 +32,8 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -118,6 +120,18 @@ type Record struct {
|
||||
// Dead is a sign-in the server refused to renew: the page asks for it
|
||||
// again
|
||||
Dead bool `json:"dead,omitempty"`
|
||||
|
||||
// More than one sign-in to a server (Elorynth on X: several accounts,
|
||||
// one in use). This record is always the one in use, so every reader of
|
||||
// a server's sign-in (the gateway's relay, the check, a renewal) reads
|
||||
// the account in use without knowing there are others; the others wait
|
||||
// in Spare, and a switch swaps them. Seq keeps each account's place in
|
||||
// the list, which a swap doesn't move. A sign-in made before accounts
|
||||
// has none of these: it is account 1, with no label.
|
||||
ID string `json:"id,omitempty"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Seq int `json:"seq,omitempty"`
|
||||
Spare []*Record `json:"spare,omitempty"`
|
||||
}
|
||||
|
||||
// fileMu is held for a change to mcp-signins.json read afresh under it,
|
||||
@@ -200,7 +214,9 @@ func Get(name string) (Record, bool) {
|
||||
if r == nil {
|
||||
return Record{}, false
|
||||
}
|
||||
return *r, true
|
||||
c := *r
|
||||
c.Spare = nil
|
||||
return c, true
|
||||
}
|
||||
|
||||
// SignedIn says whether magpie holds a sign-in to the server by that name
|
||||
@@ -217,6 +233,8 @@ type Status struct {
|
||||
SignedIn bool `json:"signedIn"`
|
||||
Dead bool `json:"dead,omitempty"`
|
||||
At int64 `json:"at,omitempty"`
|
||||
// Accounts are the sign-ins, when there is more than one
|
||||
Accounts []Account `json:"accounts,omitempty"`
|
||||
}
|
||||
|
||||
// StatusOf is the sign-in to the server by that name at that URL.
|
||||
@@ -225,7 +243,11 @@ func StatusOf(name, serverURL string) Status {
|
||||
if !ok || r.URL != serverURL {
|
||||
return Status{}
|
||||
}
|
||||
return Status{SignedIn: true, Dead: r.Dead, At: r.At}
|
||||
st := Status{SignedIn: true, Dead: r.Dead, At: r.At}
|
||||
if l := Accounts(name); len(l) > 1 {
|
||||
st.Accounts = l
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// SignOut forgets magpie's sign-in to the server.
|
||||
@@ -252,6 +274,157 @@ func Forget(name string) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Account is one of a server's sign-ins, as the page lists it.
|
||||
type Account struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label,omitempty"` // "" for one made before labels
|
||||
Active bool `json:"active,omitempty"`
|
||||
Dead bool `json:"dead,omitempty"`
|
||||
At int64 `json:"at,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrNoAccount is an account the server has no sign-in for.
|
||||
ErrNoAccount = errors.New("magpie has no such sign-in to this server")
|
||||
// ErrLabelUsed is a label another sign-in to the server has.
|
||||
ErrLabelUsed = errors.New("another sign-in to this server has that name")
|
||||
)
|
||||
|
||||
// the record's id and place, which a sign-in made before accounts lacks
|
||||
func idOf(r *Record) string {
|
||||
if r.ID == "" {
|
||||
return "1"
|
||||
}
|
||||
return r.ID
|
||||
}
|
||||
|
||||
func seqOf(r *Record) int {
|
||||
if r.Seq == 0 {
|
||||
return 1
|
||||
}
|
||||
return r.Seq
|
||||
}
|
||||
|
||||
// all is the record with its spares, in the order they were signed in.
|
||||
func all(r *Record) []*Record {
|
||||
a := *r
|
||||
a.Spare = nil
|
||||
out := append([]*Record{&a}, r.Spare...)
|
||||
slices.SortStableFunc(out, func(x, y *Record) int { return seqOf(x) - seqOf(y) })
|
||||
return out
|
||||
}
|
||||
|
||||
// Accounts are the sign-ins to the server by that name, in the order they
|
||||
// were made; none when magpie isn't signed in to it.
|
||||
func Accounts(name string) []Account {
|
||||
fileMu.Lock()
|
||||
defer fileMu.Unlock()
|
||||
r := load()[name]
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
var out []Account
|
||||
for _, x := range all(r) {
|
||||
out = append(out, Account{ID: idOf(x), Label: x.Label, Active: x == nil || idOf(x) == idOf(r), Dead: x.Dead, At: x.At})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// InUse is the id of the sign-in in use, "" when there is none.
|
||||
func InUse(name string) string {
|
||||
for _, a := range Accounts(name) {
|
||||
if a.Active {
|
||||
return a.ID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Use puts the sign-in by that id in use: what the gateway sends the
|
||||
// server, and the check, from the next request on. The agents are told
|
||||
// through Changed as for a new sign-in.
|
||||
func Use(name, id string) error {
|
||||
found := false
|
||||
err := update(func(m map[string]*Record) bool {
|
||||
cur := m[name]
|
||||
if cur == nil {
|
||||
return false
|
||||
}
|
||||
if idOf(cur) == id {
|
||||
found = true
|
||||
return false
|
||||
}
|
||||
i := slices.IndexFunc(cur.Spare, func(x *Record) bool { return idOf(x) == id })
|
||||
if i < 0 {
|
||||
return false
|
||||
}
|
||||
found = true
|
||||
was := *cur
|
||||
was.ID, was.Seq, was.Spare = idOf(cur), seqOf(cur), nil
|
||||
next := *cur.Spare[i]
|
||||
next.ID, next.Seq = idOf(&next), seqOf(&next)
|
||||
rest := slices.Clone(cur.Spare)
|
||||
rest[i] = &was
|
||||
next.Spare = rest
|
||||
m[name] = &next
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if Changed != nil {
|
||||
Changed(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveAccount forgets one sign-in to the server. The one in use going
|
||||
// puts the first of the others in use; the last going is a sign-out.
|
||||
func RemoveAccount(name, id string) error {
|
||||
found := false
|
||||
err := update(func(m map[string]*Record) bool {
|
||||
cur := m[name]
|
||||
if cur == nil {
|
||||
return false
|
||||
}
|
||||
l := all(cur)
|
||||
i := slices.IndexFunc(l, func(x *Record) bool { return idOf(x) == id })
|
||||
if i < 0 {
|
||||
return false
|
||||
}
|
||||
found = true
|
||||
active := idOf(cur)
|
||||
l = slices.Delete(l, i, i+1)
|
||||
if len(l) == 0 {
|
||||
delete(m, name)
|
||||
return true
|
||||
}
|
||||
// the one in use stays, unless it is the one removed
|
||||
next := 0
|
||||
if id != active {
|
||||
next = slices.IndexFunc(l, func(x *Record) bool { return idOf(x) == active })
|
||||
}
|
||||
n := *l[next]
|
||||
n.ID, n.Seq = idOf(&n), seqOf(&n)
|
||||
n.Spare = slices.Delete(slices.Clone(l), next, next+1)
|
||||
m[name] = &n
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if Changed != nil {
|
||||
Changed(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rename moves a sign-in to the server's new name.
|
||||
func Rename(old, name string) error {
|
||||
return update(func(m map[string]*Record) bool {
|
||||
@@ -829,6 +1002,28 @@ func Start(ctx context.Context, name, serverURL string) (State, error) {
|
||||
// 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) {
|
||||
return start(ctx, name, serverURL, app, nil)
|
||||
}
|
||||
|
||||
// StartAccount is StartWith as another account of the server: the sign-in
|
||||
// it makes is added to the ones there are and put in use, with the label,
|
||||
// and the others are kept. With no sign-in yet it is the first.
|
||||
func StartAccount(ctx context.Context, name, serverURL string, app *App, label string) (State, error) {
|
||||
label = strings.TrimSpace(label)
|
||||
if len([]rune(label)) > 60 {
|
||||
return State{}, errors.New("the name of a sign-in is at most 60 characters")
|
||||
}
|
||||
if label != "" {
|
||||
for _, a := range Accounts(name) {
|
||||
if strings.EqualFold(a.Label, label) {
|
||||
return State{}, ErrLabelUsed
|
||||
}
|
||||
}
|
||||
}
|
||||
return start(ctx, name, serverURL, app, &label)
|
||||
}
|
||||
|
||||
func start(ctx context.Context, name, serverURL string, app *App, add *string) (State, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
m, err := discover(ctx, serverURL)
|
||||
@@ -930,7 +1125,7 @@ func StartWith(ctx context.Context, name, serverURL string, app *App) (State, er
|
||||
if t.Scope != "" {
|
||||
r2.Scope = t.Scope
|
||||
}
|
||||
if err := f.keep(name, r2); err != nil {
|
||||
if err := f.keep(name, r2, add); err != nil {
|
||||
page(w, http.StatusOK, "Magpie couldn't keep the sign-in: "+err.Error())
|
||||
return
|
||||
}
|
||||
@@ -960,13 +1155,13 @@ func (f *flow) status() State {
|
||||
// keep commits the callback only while the flow is still live. Cancel or
|
||||
// timeout and the write take the same lock, so a late token cannot save a
|
||||
// sign-in the user already ended, or replace their previous sign-in.
|
||||
func (f *flow) keep(name string, r Record) error {
|
||||
func (f *flow) keep(name string, r Record, add *string) error {
|
||||
f.mu.Lock()
|
||||
if f.finished {
|
||||
f.mu.Unlock()
|
||||
return errors.New("the sign-in has ended; start it again")
|
||||
}
|
||||
err := update(func(m map[string]*Record) bool { m[name] = &r; return true })
|
||||
err := update(func(m map[string]*Record) bool { m[name] = signedAs(m[name], r, add); return true })
|
||||
f.finished = true
|
||||
f.mu.Unlock()
|
||||
if err != nil {
|
||||
@@ -982,6 +1177,31 @@ func (f *flow) keep(name string, r Record) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// signedAs is the record a new sign-in leaves for the server: an added
|
||||
// account joins the ones there are, in use; any other replaces the one in
|
||||
// use (signing in again), and the other accounts stay.
|
||||
func signedAs(old *Record, r Record, add *string) *Record {
|
||||
if old == nil || old.URL != r.URL {
|
||||
if add != nil {
|
||||
r.Label = *add
|
||||
}
|
||||
return &r
|
||||
}
|
||||
if add == nil {
|
||||
r.ID, r.Label, r.Seq, r.Spare = old.ID, old.Label, old.Seq, old.Spare
|
||||
return &r
|
||||
}
|
||||
l := all(old)
|
||||
top := 0
|
||||
for _, x := range l {
|
||||
top = max(top, seqOf(x))
|
||||
x.ID, x.Seq = idOf(x), seqOf(x)
|
||||
}
|
||||
r.Seq, r.ID, r.Label = top+1, strconv.Itoa(top+1), *add
|
||||
r.Spare = l
|
||||
return &r
|
||||
}
|
||||
|
||||
func (f *flow) finish(st State) {
|
||||
f.mu.Lock()
|
||||
if f.finished {
|
||||
|
||||
@@ -321,6 +321,19 @@ func (f *Fake) SignIn(t *testing.T, name string) mcpauth.State {
|
||||
func SignIn(t *testing.T, name, u string) mcpauth.State {
|
||||
t.Helper()
|
||||
st, err := mcpauth.Start(t.Context(), name, u)
|
||||
return finishSignIn(t, st, err)
|
||||
}
|
||||
|
||||
// SignInAccount signs magpie in to the server at u as name as another
|
||||
// account, labelled, standing in for the browser.
|
||||
func SignInAccount(t *testing.T, name, u, label string) mcpauth.State {
|
||||
t.Helper()
|
||||
st, err := mcpauth.StartAccount(t.Context(), name, u, nil, label)
|
||||
return finishSignIn(t, st, err)
|
||||
}
|
||||
|
||||
func finishSignIn(t *testing.T, st mcpauth.State, err error) mcpauth.State {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user