All checks were successful
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
188 lines
11 KiB
TypeScript
188 lines
11 KiB
TypeScript
// PEP-261 Access Hub: the owner answers an agent's access request with buttons — «Дать: чтение» /
|
|
// «Дать: полные права» → term (1 h · 1 day · 7 days · until revoked) or «Отказать» — in Telegram
|
|
// and in «Агенты просят доступ». Scenario names follow
|
|
// openspec/changes/archive/2026-11-27-pep-261-access-request-buttons/specs/access-hub/spec.md.
|
|
import assert from "node:assert/strict";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
import { after, before, describe, test } from "node:test";
|
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
import { eq } from "drizzle-orm";
|
|
import { stripAsIs } from "@peppa/shared/i18n";
|
|
import type { Bot } from "@peppa/bot";
|
|
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
|
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
|
|
|
|
process.env.PEPPA_SECRET ??= "mock-access-buttons-secret";
|
|
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
|
|
process.env.PEPPA_WEB_URL = "https://forge.mock.test";
|
|
const { createBot } = await import("@peppa/bot");
|
|
const { TelegramApi } = await import("@peppa/bot/telegram");
|
|
const { createAgentServer } = await import("@peppa/mcp/agent");
|
|
const { agents, connectionGrants, sessions } = await import("@peppa/db");
|
|
|
|
const H = 3600_000;
|
|
const tg = await new MockTelegram().start();
|
|
const ANNA = { id: 2611, chatId: 2611, username: "anna261" };
|
|
const BORIS = { id: 2612, chatId: 2612, username: "boris261" };
|
|
let bot: Bot;
|
|
let mock: Server;
|
|
let origin: string;
|
|
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
|
|
const said = (who: typeof ANNA, re: RegExp) => waitFor(`bot message ${re}`, async () => tg.botMessages(who.chatId).filter((m) => re.test(stripAsIs(m.text))).at(-1));
|
|
const datas = (m: MockTgMessage) => (m.reply_markup?.inline_keyboard.flat() ?? []).map((b) => b.callback_data ?? (b as { url?: string }).url ?? "");
|
|
const toast = (id: string) => waitFor(`answer to ${id}`, async () => tg.callbackAnswers.find((a) => a.id === id)?.text);
|
|
const pair = async (who: typeof ANNA, userId: number) => {
|
|
tg.userSends(who, `/start ${await core.createPairingCode(db, tg.token, userId)}`);
|
|
await said(who, /Привязано/);
|
|
};
|
|
|
|
before(async () => {
|
|
mock = createServer((req, res) => {
|
|
res.writeHead(200, { "content-type": "application/json" });
|
|
res.end(JSON.stringify({ ok: true, path: req.url }));
|
|
});
|
|
await new Promise<void>((r) => mock.listen(0, "127.0.0.1", r));
|
|
origin = `http://127.0.0.1:${(mock.address() as AddressInfo).port}`;
|
|
anna = await core.upsertUserFromGitea(db, { id: 2611, login: "mock-anna-261" }, { access_token: "a" });
|
|
boris = await core.upsertUserFromGitea(db, { id: 2612, login: "mock-boris-261" }, { access_token: "b" });
|
|
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "https://forge.mock.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 400 });
|
|
await bot.start();
|
|
await pair(ANNA, anna.id);
|
|
await pair(BORIS, boris.id);
|
|
});
|
|
after(async () => {
|
|
await bot.stop();
|
|
await tg.stop();
|
|
await new Promise<void>((r) => mock.close(() => r()));
|
|
await teardown();
|
|
});
|
|
|
|
let seq = 0;
|
|
/** Anna's project with an isolated agent session (no live process: the decision is only logged). */
|
|
async function setup() {
|
|
const p = await project({ turns: [] });
|
|
const proj = await core.getProject(db, p.key);
|
|
await core.setProjectOwner(db, proj.id, anna.id);
|
|
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
|
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
|
const [a] = await db.insert(agents).values({ name: `Мок-агент 261-${++seq}-${Date.now()}` }).returning();
|
|
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}`, status: "done" }).where(eq(sessions.id, s.id));
|
|
return { proj, sessionId: s.id };
|
|
}
|
|
const crm = (n: string) => core.createConnection(db, anna.id, { name: `CRM ${n}`, baseUrl: `${origin}/api`, secret: `sk_mock_261_${n}_abcdef` });
|
|
const ask = (sessionId: number, o: { host?: string; service?: string; mode?: "read" | "write" }) => core.requestAccess(db, { sessionId, purpose: "посмотреть заказы клиента", ...o });
|
|
const grantsOf = async (connectionId: number, projectId: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId))).filter((g) => g.projectId === projectId);
|
|
const message = (id: number) => waitFor(`message about request #${id}`, async () => tg.botMessages(ANNA.chatId).find((m) => datas(m).includes(`ar:${id}:no`)));
|
|
|
|
describe("Кнопки выдачи под запросом доступа", () => {
|
|
test("Чтение на 1 день кнопкой в Telegram", async () => {
|
|
const { proj, sessionId } = await setup();
|
|
const c = await crm("tg");
|
|
const { request } = await ask(sessionId, { host: origin, mode: "read" });
|
|
const m = await message(request.id);
|
|
assert.match(stripAsIs(m.text), /на какой срок/, "the text says to choose rights and term");
|
|
assert.ok(datas(m).includes(`ar:${request.id}:r`) && datas(m).includes(`ar:${request.id}:f`), JSON.stringify(m.reply_markup));
|
|
|
|
// «Дать: чтение» → the keyboard turns into terms, 1 day first.
|
|
assert.match((await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r`)))!, /срок/);
|
|
const terms = await waitFor("term buttons", async () => (datas(tg.messages.get(m.message_id)!).includes(`ar:${request.id}:r:7d`) ? tg.messages.get(m.message_id)! : null));
|
|
assert.deepEqual(datas(terms).slice(1, 5), ["1d", "1h", "7d", "forever"].map((t) => `ar:${request.id}:r:${t}`));
|
|
// «Назад» brings the rights back; then read + 1 day.
|
|
await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:back`));
|
|
await waitFor("rights again", async () => datas(tg.messages.get(m.message_id)!).includes(`ar:${request.id}:f`) || null);
|
|
const done = await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r:1d`));
|
|
assert.match(stripAsIs(done!), /Готово: чтение, 1 день/);
|
|
await waitFor("buttons removed", async () => (datas(tg.messages.get(m.message_id)!).length === 0) || null);
|
|
|
|
assert.equal((await core.getAccessRequest(db, request.id))!.status, "granted");
|
|
const [g] = await grantsOf(c.id, proj.id);
|
|
assert.equal(g!.term, "1d");
|
|
assert.equal(g!.readMode, "auto");
|
|
assert.equal(g!.writeMode, "off");
|
|
assert.ok(Math.abs(g!.expiresAt!.getTime() - (Date.now() + 24 * H)) < 60_000, "expires in a day");
|
|
|
|
// The agent calls now — and gets «истёк» a day later.
|
|
const now = await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" });
|
|
assert.ok(now.ok, JSON.stringify(now));
|
|
const later = await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { now: new Date(Date.now() + 25 * H) });
|
|
assert.deepEqual(later, { ok: false, reason: "expired" });
|
|
});
|
|
|
|
test("Чужой не может нажать «Дать»", async () => {
|
|
const { proj, sessionId } = await setup();
|
|
const c = await crm("boris");
|
|
const { request } = await ask(sessionId, { host: origin, mode: "write" });
|
|
const m = await message(request.id);
|
|
await assert.rejects(runner.grantAccessRequestByButton(db, boris.id, request.id, { rights: "full", term: "forever" }), /Запрос не найден/);
|
|
const answer = await toast(tg.userClicks(BORIS, m.message_id, `ar:${request.id}:f:forever`));
|
|
assert.doesNotMatch(stripAsIs(answer ?? ""), /Готово/);
|
|
assert.equal((await core.getAccessRequest(db, request.id))!.status, "open");
|
|
assert.equal((await grantsOf(c.id, proj.id)).length, 0, "no grant");
|
|
});
|
|
|
|
test("Подключения ещё нет", async () => {
|
|
const { sessionId } = await setup();
|
|
const { request } = await ask(sessionId, { service: "stripe" });
|
|
const m = await message(request.id);
|
|
assert.ok(!datas(m).includes(`ar:${request.id}:r`), "no «Дать» without a connection");
|
|
assert.ok(datas(m).includes(`https://forge.mock.test/connections/requests/${request.id}`), "«Подключить» — the request's card");
|
|
assert.match(stripAsIs(m.text), /Откройте запрос/);
|
|
await assert.rejects(runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read" }), /Подключения ещё нет/);
|
|
const answer = await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r`));
|
|
assert.match(stripAsIs(answer!), /Подключения ещё нет/);
|
|
assert.equal((await core.getAccessRequest(db, request.id))!.status, "open");
|
|
});
|
|
|
|
test("Срок на карточке запроса", async () => {
|
|
const { proj, sessionId } = await setup();
|
|
const { request } = await ask(sessionId, { service: "stripe", mode: "read" });
|
|
const out = await runner.connectAndGrantAccessRequest(db, anna.id, request.id, { secret: "sk_test_mock_STRIPE_261_123456" }, { rights: "full", term: "7d" });
|
|
assert.equal(out.request.status, "granted");
|
|
const [g] = await grantsOf(out.connection.id, proj.id);
|
|
assert.equal(g!.term, "7d");
|
|
assert.equal(g!.readMode, "auto");
|
|
assert.equal(g!.writeMode, "auto", "full rights");
|
|
assert.equal(out.request.term, "7d");
|
|
assert.match(runner.accessDecisionText(out.request), /чтение и запись на 7 дней/);
|
|
});
|
|
|
|
test("Без выбора — срок 1 день и права по запросу", async () => {
|
|
const { proj, sessionId } = await setup();
|
|
const c = await crm("default");
|
|
const { request } = await ask(sessionId, { host: origin, mode: "write" });
|
|
await runner.grantAccessRequestFromExisting(db, anna.id, request.id, c.id);
|
|
const [g] = await grantsOf(c.id, proj.id);
|
|
assert.equal(g!.term, "1d");
|
|
assert.equal(g!.writeMode, "auto");
|
|
});
|
|
|
|
test("Разбор кнопок", () => {
|
|
assert.deepEqual(core.parseAccessCallback("ar:5:r"), { id: 5, action: "rights", rights: "read" });
|
|
assert.deepEqual(core.parseAccessCallback("ar:5:f:7d"), { id: 5, action: "grant", rights: "full", term: "7d" });
|
|
assert.deepEqual(core.parseAccessCallback("ar:5:no"), { id: 5, action: "no" });
|
|
assert.equal(core.parseAccessCallback("ar:5:r:2d"), null);
|
|
assert.equal(core.parseAccessCallback("ar:5:no:1d"), null);
|
|
});
|
|
});
|
|
|
|
describe("Истёкший доступ — новый запрос", () => {
|
|
test("Отказ после истечения", async () => {
|
|
const { proj, sessionId } = await setup();
|
|
const c = await crm("expired");
|
|
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "read", term: "1h", now: new Date(Date.now() - 2 * H) });
|
|
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
await createAgentServer(db, { defaultKey: proj.key, sessionId, lockProject: true }).connect(a);
|
|
const client = new Client({ name: "mock-agent", version: "0" });
|
|
await client.connect(b);
|
|
const r = await client.callTool({ name: "call_connection", arguments: { connection: c.id, method: "GET", path: "/items" } });
|
|
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
|
assert.equal(r.isError, true);
|
|
assert.match(text, /expired/);
|
|
assert.ok(text.includes(`request_access(host: "${origin}/api"`), text);
|
|
});
|
|
});
|