peppa/packages/testkit/test/oauth.test.ts
Асель 4e20f76767 PEP-11: update_task in the remote MCP
- edit a task's title and/or description by key through the owner-scoped
  manager tools; goal, status and other fields kept, no agent started;
  uses core updateTask (event log, NOTIFY) and returns the updated card
- test: title only, description only, both; goal/status/sessions intact;
  empty call and another user's task refused (54 e2e total, green)
- verified on prod: tools/list over HTTPS includes update_task
- OpenSpec: pep-11 archived into spec remote-mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:52:46 +05:00

170 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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"] } }], [{ 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(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "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/);
});
});
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");
});
});