280 lines
19 KiB
TypeScript
280 lines
19 KiB
TypeScript
// PEP-8: OAuth 2.1 server and the PM MCP tools served to remote clients (ChatGPT).
|
||
import assert from "node:assert/strict";
|
||
import { createHash, randomBytes } from "node:crypto";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||
import { eq } from "drizzle-orm";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const { createManagerServer } = await import("@peppa/mcp/manager");
|
||
|
||
const REDIRECT = "https://chatgpt.com/connector_platform_oauth_redirect";
|
||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let stranger: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
owner = await core.upsertUserFromGitea(db, { id: 21, login: "mock-owner" }, { access_token: "x" });
|
||
stranger = await core.upsertUserFromGitea(db, { id: 22, login: "mock-stranger" }, { access_token: "y" });
|
||
});
|
||
after(teardown);
|
||
|
||
const pkce = () => {
|
||
const verifier = randomBytes(32).toString("base64url");
|
||
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
||
};
|
||
|
||
async function authorize(clientId: string, userId: number, challenge: string) {
|
||
return core.issueCode(db, { clientId, redirectUri: REDIRECT, codeChallenge: challenge, codeChallengeMethod: "S256", responseType: "code" }, userId);
|
||
}
|
||
|
||
describe("OAuth server", () => {
|
||
test("dynamic registration accepts https/localhost redirects only", async () => {
|
||
await assert.rejects(core.registerClient(db, "bad", ["http://evil.example/cb"]), /redirect_uris/);
|
||
await assert.rejects(core.registerClient(db, "bad", []), /redirect_uris/);
|
||
const c = await core.registerClient(db, "ChatGPT", [REDIRECT, "http://localhost:8765/cb"]);
|
||
assert.match(c.id, /^peppa-/);
|
||
});
|
||
|
||
test("authorize request validation", async () => {
|
||
const c = await core.registerClient(db, "ChatGPT", [REDIRECT]);
|
||
const ok = { clientId: c.id, redirectUri: REDIRECT, codeChallenge: pkce().challenge, codeChallengeMethod: "S256", responseType: "code" };
|
||
await core.checkAuthorizeRequest(db, ok);
|
||
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, clientId: "nope" }), /Неизвестное приложение/);
|
||
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, redirectUri: "https://other.example/cb" }), /не зарегистрирован/);
|
||
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, codeChallengeMethod: "plain" }), /PKCE/);
|
||
});
|
||
|
||
test("code + PKCE → tokens; replay, wrong verifier and wrong redirect are refused", async () => {
|
||
const c = await core.registerClient(db, "ChatGPT", [REDIRECT]);
|
||
const { verifier, challenge } = pkce();
|
||
const code = await authorize(c.id, owner.id, challenge);
|
||
const base = { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT };
|
||
const t = await core.exchangeToken(db, { ...base, code, code_verifier: verifier });
|
||
assert.equal(t.token_type, "Bearer");
|
||
assert.deepEqual(await core.verifyAccessToken(db, t.access_token), { userId: owner.id, clientId: c.id });
|
||
await assert.rejects(core.exchangeToken(db, { ...base, code, code_verifier: verifier }), /already used/);
|
||
|
||
const p2 = pkce();
|
||
const code2 = await authorize(c.id, owner.id, p2.challenge);
|
||
await assert.rejects(core.exchangeToken(db, { ...base, code: code2, code_verifier: pkce().verifier }), /PKCE/);
|
||
const p3 = pkce();
|
||
const code3 = await authorize(c.id, owner.id, p3.challenge);
|
||
await assert.rejects(core.exchangeToken(db, { ...base, redirect_uri: "https://other.example/cb", code: code3, code_verifier: p3.verifier }), /mismatch/);
|
||
assert.equal(await core.verifyAccessToken(db, "garbage"), null);
|
||
});
|
||
|
||
test("refresh tokens rotate; revoking the app kills its tokens", async () => {
|
||
const c = await core.registerClient(db, "ChatGPT revoke", [REDIRECT]);
|
||
const { verifier, challenge } = pkce();
|
||
const t1 = await core.exchangeToken(db, { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT, code: await authorize(c.id, owner.id, challenge), code_verifier: verifier });
|
||
const t2 = await core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token, client_id: c.id });
|
||
await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token }), /invalid/, "old refresh token is single use");
|
||
assert.ok(await core.verifyAccessToken(db, t2.access_token));
|
||
assert.ok((await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id));
|
||
assert.ok((await core.revokeApp(db, owner.id, c.id)) > 0);
|
||
assert.equal(await core.verifyAccessToken(db, t2.access_token), null);
|
||
await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t2.refresh_token }), /invalid/);
|
||
assert.ok(!(await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id));
|
||
});
|
||
});
|
||
|
||
async function mcpAs(user: typeof owner) {
|
||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||
await createManagerServer(db, user, "https://peppa.test").connect(a);
|
||
const client = new Client({ name: "mock-chatgpt", version: "0" });
|
||
await client.connect(b);
|
||
const call = async (name: string, args: Record<string, unknown> = {}) => {
|
||
const r = await client.callTool({ name, arguments: args });
|
||
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||
};
|
||
return { client, call };
|
||
}
|
||
|
||
describe("PM tools over MCP", () => {
|
||
test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => {
|
||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, owner.id);
|
||
const { client, call } = await mcpAs(owner);
|
||
const tools = (await client.listTools()).tools;
|
||
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "apply_plan", "archive_task", "create_epic", "create_goal", "create_project", "create_task", "decide_incident", "deploy", "get_incident", "get_incident_policy", "get_metrics", "get_project_settings", "get_task", "get_usage", "list_epics", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_releases", "list_secrets", "list_tasks", "move_task", "plan_epic", "remove_member", "reorder_task", "resolve_incident", "set_dependencies", "set_incident_policy", "set_project_visibility", "update_epic", "update_goal", "update_project_settings", "update_task"]);
|
||
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
|
||
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);
|
||
|
||
assert.match((await call("list_projects")).text, new RegExp(`${p.key} — `));
|
||
const created = await call("create_task", { project: p.key, title: "Из ChatGPT: порт сервиса" });
|
||
assert.match(created.text, new RegExp(`Created ${p.key}-2`));
|
||
assert.match((await call("list_tasks", { project: p.key, column: "backlog" })).text, /Из ChatGPT/);
|
||
|
||
const moved = await call("move_task", { task: `${p.key}-2`, to: "in_progress" });
|
||
assert.match(moved.text, /agent session #\d+ started/);
|
||
const sid = Number(/#(\d+)/.exec(moved.text)![1]);
|
||
const q = await p.waitQuestion(sid, "question");
|
||
assert.match((await call("list_inbox")).text, new RegExp(`#${q.id} ${p.key}-2 · question`));
|
||
assert.match((await call("answer_question", { question_id: q.id, answer: "3000" })).text, /Delivered/);
|
||
await p.waitLog("answer reached the agent", (e) => e.ev === "prompt" && String(e.prompt).includes(": 3000"));
|
||
|
||
const s = await mcpAs(stranger);
|
||
assert.match((await s.call("list_projects")).text, /No projects/);
|
||
const denied = await s.call("move_task", { task: `${p.key}-2`, to: "backlog" });
|
||
assert.ok(denied.isError);
|
||
assert.match(denied.text, /Не найдено/);
|
||
assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError);
|
||
|
||
assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/);
|
||
// PEP-23: autonomy settings of the project; strangers can't touch them.
|
||
assert.match((await call("get_project_settings", { project: p.key })).text, /Уровень: Ручной/);
|
||
assert.match((await call("update_project_settings", { project: p.key, level: "auto", proposal: "pm" })).text, /Уровень: Свой[\s\S]*каждый одобряет PM/);
|
||
assert.ok((await s.call("update_project_settings", { project: p.key, level: "manual" })).isError);
|
||
await call("update_project_settings", { project: p.key, level: "manual" });
|
||
});
|
||
});
|
||
|
||
describe("update_task over MCP", () => {
|
||
test("title only, description only, both — goal, status and sessions untouched", async () => {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, owner.id);
|
||
const goal = await core.createGoal(db, proj.id, "Цель для правки");
|
||
const ref = await core.createTask(db, { projectId: proj.id, goalId: goal.id, title: "Начать делать", description: "старое описание" });
|
||
const { client, call } = await mcpAs(owner);
|
||
assert.equal((await client.listTools()).tools.find((t) => t.name === "update_task")?.annotations?.readOnlyHint, false);
|
||
const snapshot = async () => {
|
||
const t = (await core.resolveTask(db, ref.key)).task;
|
||
return { title: t.title, description: t.description, goalId: t.goalId, status: t.status, sessions: (await core.listSessions(db, { taskId: t.id })).length };
|
||
};
|
||
|
||
const r1 = await call("update_task", { task: ref.key, title: "Новое название" });
|
||
assert.ok(!r1.isError, r1.text);
|
||
assert.match(r1.text, new RegExp(`# ${ref.key}: Новое название`));
|
||
assert.deepEqual(await snapshot(), { title: "Новое название", description: "старое описание", goalId: goal.id, status: "backlog", sessions: 0 });
|
||
|
||
const desc = "Сделать доску.\n\nУсловия готовности:\n- пункт 1\n- пункт 2";
|
||
const r2 = await call("update_task", { task: ref.key, description: desc });
|
||
assert.match(r2.text, /Условия готовности/);
|
||
assert.deepEqual(await snapshot(), { title: "Новое название", description: desc, goalId: goal.id, status: "backlog", sessions: 0 });
|
||
|
||
const r3 = await call("update_task", { task: ref.key, title: "Оба поля", description: "оба описания" });
|
||
assert.match(r3.text, /Оба поля/);
|
||
assert.match(r3.text, /оба описания/);
|
||
assert.match(r3.text, /Эпик: #\d+ Цель для правки/);
|
||
assert.deepEqual(await snapshot(), { title: "Оба поля", description: "оба описания", goalId: goal.id, status: "backlog", sessions: 0 });
|
||
|
||
assert.ok((await call("update_task", { task: ref.key })).isError, "nothing to update");
|
||
const s = await mcpAs(stranger);
|
||
const denied = await s.call("update_task", { task: ref.key, title: "чужое" });
|
||
assert.ok(denied.isError);
|
||
assert.match(denied.text, /Не найдено/);
|
||
assert.equal((await snapshot()).title, "Оба поля");
|
||
const evs = await db.select().from((await import("@peppa/db")).events).where(eq((await import("@peppa/db")).events.taskId, ref.task.id));
|
||
assert.equal(evs.filter((e) => e.type === "task_updated").length, 3, "each edit is in the task's event log");
|
||
});
|
||
});
|
||
|
||
describe("goals, task goal and project creation over MCP", () => {
|
||
test("server instructions explain the model", async () => {
|
||
const { client } = await mcpAs(owner);
|
||
assert.match(client.getInstructions() ?? "", /project .*epics .*stories/s);
|
||
});
|
||
|
||
test("create/update goals; move a task between goals and detach; foreign goal refused", async () => {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, owner.id);
|
||
const { call } = await mcpAs(owner);
|
||
const g1 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
|
||
const g2 = Number(/epic #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
|
||
assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/);
|
||
assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/);
|
||
|
||
const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 });
|
||
const key = /Created (\S+):/.exec(t.text)![1]!;
|
||
assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Эпик: #\d+ Цель два/);
|
||
const moved = (await core.resolveTask(db, key)).task;
|
||
assert.equal(moved.goalId, g2);
|
||
assert.equal(moved.title, "Задача в цели");
|
||
assert.equal(moved.status, "backlog");
|
||
await call("update_task", { task: key, goal_id: null });
|
||
assert.equal((await core.resolveTask(db, key)).task.goalId, null);
|
||
|
||
const other = await project({ turns: [] });
|
||
const foreignGoal = await core.createGoal(db, (await core.getProject(db, other.key)).id, "Чужая цель");
|
||
assert.ok((await call("update_task", { task: key, goal_id: foreignGoal.id })).isError, "goal of another project");
|
||
assert.ok((await call("update_goal", { project: p.key, goal_id: foreignGoal.id, title: "взлом" })).isError);
|
||
|
||
assert.match((await call("update_goal", { project: p.key, goal_id: g1, status: "done" })).text, /\[done\]/);
|
||
assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/);
|
||
});
|
||
|
||
test("Scenario: Новый эпик и стори в нём; Эпик завершён; Алиас цели; Перенос в другой эпик; Эпик чужого проекта", async () => {
|
||
const p = await project({ turns: [] });
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, owner.id);
|
||
const { call, client } = await mcpAs(owner);
|
||
const createTask = (await client.listTools()).tools.find((t) => t.name === "create_task");
|
||
assert.match(createTask?.description ?? "", /story/i, "tool name stays, the text speaks of stories");
|
||
|
||
const a = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Оплата картой", description: "Приём оплат" })).text)![1]);
|
||
assert.ok((await call("create_epic", { project: p.key, title: "Б" })).isError, "title of at least 3 chars");
|
||
const b = Number(/epic #(\d+)/.exec((await call("create_epic", { project: p.key, title: "Эпик Б" })).text)![1]);
|
||
const t = await call("create_task", { project: p.key, title: "Форма оплаты", epic_id: a });
|
||
const key = /Created (\S+):/.exec(t.text)![1]!;
|
||
assert.equal((await core.resolveTask(db, key)).task.goalId, a);
|
||
const listed = (await call("list_epics", { project: p.key })).text;
|
||
assert.match(listed, /Оплата картой \(done 0\/1\) — Приём оплат/);
|
||
assert.equal((await call("list_goals", { project: p.key })).text, listed, "list_goals is an alias");
|
||
assert.match((await call("list_tasks", { project: p.key })).text, new RegExp(`${key} \\[backlog\\] \\(epic #${a}\\)`));
|
||
|
||
const r = await call("update_task", { task: key, epic_id: b });
|
||
assert.match(r.text, /Эпик: #\d+ Эпик Б/);
|
||
assert.equal((await core.resolveTask(db, key)).task.status, "backlog");
|
||
assert.match((await call("get_task", { task: key })).text, /Эпик: #\d+ Эпик Б/);
|
||
|
||
const other = await project({ turns: [] });
|
||
const foreign = await core.createEpic(db, (await core.getProject(db, other.key)).id, "Чужой эпик");
|
||
assert.ok((await call("update_task", { task: key, epic_id: foreign.id })).isError);
|
||
assert.ok((await call("create_task", { project: p.key, title: "С чужим эпиком", epic_id: foreign.id })).isError);
|
||
assert.equal((await core.resolveTask(db, key)).task.goalId, b);
|
||
|
||
assert.match((await call("update_epic", { project: p.key, epic_id: a, status: "done" })).text, /\[done\]/);
|
||
assert.doesNotMatch((await call("list_epics", { project: p.key })).text, /Оплата картой/);
|
||
assert.ok((await call("update_epic", { project: p.key, epic_id: a })).isError, "nothing to update");
|
||
});
|
||
|
||
test("create_project through MCP, owned by the user", async () => {
|
||
const { MockGitea } = await import("../src/mock-gitea.ts");
|
||
const { mkdtempSync } = await import("node:fs");
|
||
const { tmpdir } = await import("node:os");
|
||
const { join, resolve } = await import("node:path");
|
||
const { fileURLToPath } = await import("node:url");
|
||
const { execFileSync } = await import("node:child_process");
|
||
const tmp = mkdtempSync(join(tmpdir(), "peppa-mcp-proj-"));
|
||
const gitea = await new MockGitea(join(tmp, "gitea")).start();
|
||
const prevUrl = process.env.GITEA_URL;
|
||
try {
|
||
process.env.GITEA_URL = gitea.url;
|
||
process.env.PEPPA_WORKSPACES = join(tmp, "ws");
|
||
gitea.addUser({ id: 41, login: "mock-mcp-owner", token: "mock-token-mcp" });
|
||
const tpl = gitea.addRepo("peppa-bot", "template");
|
||
const root = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(root, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
|
||
process.env.PEPPA_TEMPLATE_URL = tpl.path;
|
||
const u = await core.upsertUserFromGitea(db, { id: 41, login: "mock-mcp-owner" }, { access_token: "mock-token-mcp" });
|
||
const { call } = await mcpAs(u);
|
||
const r = await call("create_project", { name: "Mock MCP project", slug: "mock-mcp-proj", key: "MMCP" });
|
||
assert.ok(!r.isError, r.text);
|
||
assert.match(r.text, /Created project MMCP/);
|
||
assert.equal((await core.getProject(db, "MMCP")).ownerId, u.id);
|
||
assert.ok(gitea.files("mock-mcp-owner", "mock-mcp-proj").includes("AGENTS.md"));
|
||
assert.match((await call("list_projects")).text, /MMCP — Mock MCP project/);
|
||
assert.ok((await call("create_project", { name: "dup", slug: "mock-mcp-proj", key: "MMCP2" })).isError, "duplicate refused");
|
||
} finally {
|
||
process.env.GITEA_URL = prevUrl;
|
||
delete process.env.PEPPA_TEMPLATE_URL;
|
||
await gitea.stop();
|
||
}
|
||
});
|
||
});
|