// PEP-259 Access Hub: a grant lives for a term (1 h · 1 day · 7 days · until revoked) and is // after the connection's threshold (72 h) without calls its owner is asked «снять?» — revoked // only by the owner's answer (PM, PEP-259 review). Scenario names // follow openspec/changes/archive/2026-11-24-pep-259-grant-terms/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 { and, eq } from "drizzle-orm"; import { core, db, project, teardown } from "./helpers.ts"; process.env.PEPPA_SECRET ??= "mock-access-hub-secret"; process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1 const { createAgentServer } = await import("@peppa/mcp/agent"); const { connectionGrants, connectionLog, agents, sessions, events } = await import("@peppa/db"); const H = 3600_000; let mock: Server; let base: string; let anna: Awaited>; let boris: Awaited>; 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((r) => mock.listen(0, "127.0.0.1", r)); base = `http://127.0.0.1:${(mock.address() as AddressInfo).port}/api`; anna = await core.upsertUserFromGitea(db, { id: 2591, login: "mock-anna-259" }, { access_token: "a" }); boris = await core.upsertUserFromGitea(db, { id: 2592, login: "mock-boris-259" }, { access_token: "b" }); }); after(async () => { await new Promise((r) => mock.close(() => r())); await teardown(); }); let seq = 0; /** Anna's project, an isolated agent session in it and a fresh connection «CRM» granted read on `term`. */ async function setup(o: { term?: "1h" | "1d" | "7d" | "forever"; at: Date; idleHours?: number | null }) { 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: `Мок-агент 259-${++seq}-${Date.now()}` }).returning(); await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id)); const c = await core.createConnection(db, anna.id, { name: `CRM ${seq}`, baseUrl: base, secret: `sk_mock_259_${seq}_abcdef` }); if (o.idleHours !== undefined) await core.setConnectionIdleHours(db, anna.id, c.id, o.idleHours); const g = await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "read", term: o.term, now: o.at }); return { proj, sessionId: s.id, c, g }; } const call = (sessionId: number, c: { id: number }, now: Date) => core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { now }); const grantRow = async (id: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.id, id)))[0]; const silent = async () => {}; describe("Срок разрешения", () => { test("Вызов по живому разрешению на 1 день", async () => { const t0 = new Date(Date.now() - 2 * H); const { sessionId, c, g } = await setup({ term: "1d", at: t0 }); assert.equal(g.term, "1d"); assert.equal(g.expiresAt!.getTime(), t0.getTime() + 24 * H); const r = await call(sessionId, c, new Date()); assert.ok(r.ok, JSON.stringify(r)); const [view] = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants; assert.ok(view!.lastUsedAt, "the grant shows its last call"); assert.equal(view!.state, "active"); assert.ok(view!.idleAskAt && view!.idleAskAt.getTime() > Date.now() + 70 * H, "72 h from the last call"); }); test("Вызов после истечения срока", async () => { const t0 = new Date(Date.now() - 25 * H); const { sessionId, c } = await setup({ term: "1d", at: t0 }); const r = await call(sessionId, c, new Date()); assert.deepEqual(r, { ok: false, reason: "expired" }); const [row] = await db.select().from(connectionLog).where(and(eq(connectionLog.connectionId, c.id), eq(connectionLog.kind, "call"))); assert.equal(row!.decision, "denied"); assert.equal(row!.reason, "expired"); const view = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.grants[0]!; assert.equal(view.state, "expired"); assert.equal(view.idleAskAt, null); }); test("Агенту — понятная причина через MCP", async () => { const { proj, sessionId, c } = await setup({ term: "1h", at: 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.ok(r.isError); assert.match(text, /\(expired\)/); assert.match(text, /extend/); const list = await client.callTool({ name: "list_connections", arguments: {} }); assert.match((list.content as Array<{ text: string }>)[0]!.text, /No connections/, "an expired grant is not offered"); }); test("Продление истёкшего разрешения", async () => { const { sessionId, c, g } = await setup({ term: "1d", at: new Date(Date.now() - 30 * H) }); assert.equal((await call(sessionId, c, new Date())).ok, false); const now = new Date(); const ext = await core.extendGrant(db, anna.id, g.id, { now }); assert.equal(ext.state, "active"); assert.equal(ext.expiresAt!.getTime(), now.getTime() + 24 * H); assert.ok((await call(sessionId, c, new Date())).ok); const ev = await db.select().from(events).where(eq(events.type, "connection_grant_extended")); assert.ok(ev.length >= 1); }); test("Чужой пользователь не продлевает", async () => { const { g } = await setup({ term: "1h", at: new Date(Date.now() - 2 * H) }); await assert.rejects(core.extendGrant(db, boris.id, g.id), /Подключение не найдено/); await assert.rejects(core.setConnectionIdleHours(db, boris.id, (await grantRow(g.id))!.connectionId, 0), core.PeppaError); assert.equal((await grantRow(g.id))!.expiresAt!.getTime() < Date.now(), true, "unchanged"); }); test("Без срока — до отзыва (как раньше)", async () => { const { g } = await setup({ at: new Date() }); assert.equal(g.term, "forever"); assert.equal(g.expiresAt, null); }); }); describe("Снятие разрешения без дела — только по решению владельца", () => { test("Разрешение без вызовов 72 часа — запрос владельцу, доступ остаётся", async () => { const now = new Date(); const { sessionId, c, g } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) }); const sent: Array<{ ownerId: number; ids: number[] }> = []; const n = await core.grantExpiryTick(db, { now, notify: async (_db, ownerId, items) => void sent.push({ ownerId, ids: items.map((i) => i.grantId) }) }); assert.ok(n >= 1); assert.equal((await grantRow(g.id))!.endedAt, null, "not revoked by itself"); assert.ok(sent.some((x) => x.ownerId === anna.id && x.ids.includes(g.id)), "the owner is asked"); const view = (await core.listConnections(db, anna.id, { now })).find((x) => x.id === c.id)!.grants[0]!; assert.equal(view.state, "active"); assert.ok(view.idleAskedAt, "«не используется 72 ч — снять?» on the page"); assert.ok((await call(sessionId, c, new Date())).ok, "the agent keeps working while nobody answered"); // The call restarted the countdown: no second request. const again: number[] = []; await core.grantExpiryTick(db, { now: new Date(now.getTime() + 25 * H), notify: async () => void again.push(1) }); assert.equal(again.length, 0); }); test("Владелец нажимает «Снять»", async () => { const now = new Date(); const { sessionId, c, g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) }); await core.grantExpiryTick(db, { now, notify: silent }); await assert.rejects(core.decideIdleGrant(db, boris.id, g.id, "revoke"), /Разрешение не найдено/, "only the owner decides"); assert.equal((await grantRow(g.id))!.endedAt, null); assert.equal(await core.decideIdleGrant(db, anna.id, g.id, "revoke", { now }), "Разрешение снято"); const row = await grantRow(g.id); assert.equal(row!.endReason, "idle"); const view = (await core.listConnections(db, anna.id, { now })).find((x) => x.id === c.id)!.grants[0]!; assert.equal(view.state, "idle"); assert.equal(view.idleHours, 72); const journal = await core.connectionJournal(db, anna.id, { connectionId: c.id }); assert.ok(journal.some((j) => j.method === "REVOKE" && j.reason === "idle_revoked" && j.projectKey === proj.key)); assert.equal((await core.verifyConnectionJournal(db, anna.id)).ok, true, "the revoke row is in the hash chain"); assert.deepEqual(await call(sessionId, c, new Date()), { ok: false, reason: "idle_revoked" }); // Telegram button data round-trips. assert.deepEqual(core.parseIdleGrantCallback(core.idleGrantCallback(g.id, "revoke")), { grantId: g.id, decision: "revoke" }); // Extending brings it back. await core.extendGrant(db, anna.id, g.id); assert.ok((await call(sessionId, c, new Date())).ok); }); test("Владелец нажимает «Оставить»", async () => { const now = new Date(); const { c, g } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) }); await core.grantExpiryTick(db, { now, notify: silent }); await core.decideIdleGrant(db, anna.id, g.id, "keep", { now }); assert.equal((await grantRow(g.id))!.endedAt, null); const view = (await core.listConnections(db, anna.id, { now })).find((x) => x.id === c.id)!.grants[0]!; assert.equal(view.idleAskedAt, null); assert.ok(view.idleAskAt && view.idleAskAt.getTime() >= now.getTime() + 71 * H, "next request a threshold later"); const asked: number[][] = []; const ask = async (_db: unknown, _o: number, items: Array<{ grantId: number }>) => void asked.push(items.map((i) => i.grantId)); await core.grantExpiryTick(db, { now: new Date(now.getTime() + 25 * H), notify: ask }); assert.ok(!asked.flat().includes(g.id)); await core.grantExpiryTick(db, { now: new Date(now.getTime() + 73 * H), notify: ask }); assert.ok(asked.flat().includes(g.id), "still unused three days later — asked again"); }); test("Не больше одного запроса в сутки", async () => { const now = new Date(Date.now() + 1000 * H); await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) }); const first: number[] = []; await core.grantExpiryTick(db, { now, notify: async () => void first.push(1) }); assert.equal(first.length, 1); await setup({ term: "forever", at: new Date(now.getTime() - 80 * H) }); const again: number[] = []; await core.grantExpiryTick(db, { now: new Date(now.getTime() + H), notify: async () => void again.push(1) }); assert.equal(again.length, 0); await core.grantExpiryTick(db, { now: new Date(now.getTime() + 25 * H), notify: async () => void again.push(1) }); assert.equal(again.length, 1, "the next day — one request"); }); test("Недавний вызов продлевает жизнь", async () => { const now = new Date(); const { sessionId, c, g } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) }); assert.ok((await call(sessionId, c, new Date(now.getTime() - 10 * H))).ok); await core.grantExpiryTick(db, { now, notify: silent }); assert.equal((await grantRow(g.id))!.endedAt, null); }); test("Порог 0 — не спрашивать", async () => { const now = new Date(); const { g } = await setup({ term: "forever", at: new Date(now.getTime() - 500 * H), idleHours: 0 }); await core.grantExpiryTick(db, { now, notify: silent }); assert.equal((await grantRow(g.id))!.endedAt, null); const view = (await core.listConnections(db, anna.id, { now })).flatMap((x) => x.grants).find((x) => x.id === g.id)!; assert.equal(view.idleAskAt, null); assert.equal(view.idleAskedAt, null); }); test("Проект на паузе", async () => { const now = new Date(); const { g, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 100 * H) }); await core.setSetting(db, `project.paused:${proj.id}`, { since: now.toISOString(), by: anna.id, sessions: [] }); await core.grantExpiryTick(db, { now, notify: silent }); assert.equal((await grantRow(g.id))!.endedAt, null); }); test("Снятые давно разрешения убираются", async () => { const now = new Date(); const { g } = await setup({ term: "1h", at: new Date(now.getTime() - 40 * 24 * H) }); await core.grantExpiryTick(db, { now, notify: silent }); assert.equal(await grantRow(g.id), undefined); }); }); describe("Агент видит срок разрешения", () => { test("Список подключений агента", async () => { const { proj, sessionId } = await setup({ term: "7d", at: new Date() }); const list = await core.agentConnections(db, sessionId); assert.equal(list.length, 1); assert.ok(list[0]!.expiresAt && list[0]!.expiresAt.getTime() > Date.now() + 6 * 24 * 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: "list_connections", arguments: {} }); const text = (r.content as Array<{ text: string }>)[0]!.text; assert.match(text, /access: until \d{4}-/); assert.match(text, /the owner is asked whether to revoke it/); }); });