370 lines
24 KiB
TypeScript
370 lines
24 KiB
TypeScript
// PEP-249 Access Hub: catalog of services, read / write modes, key check, short names for agents.
|
||
// Scenario names follow openspec/changes/pep-249-access-hub-catalog/specs/access-hub/spec.md.
|
||
import assert from "node:assert/strict";
|
||
import { createServer, type IncomingHttpHeaders, 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 { core, db, project, teardown } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
|
||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||
const { connections, connectionLog, agents, sessions } = await import("@peppa/db");
|
||
type Fetch = NonNullable<Parameters<typeof core.callConnection>[2]>["fetch"];
|
||
|
||
const KEY = "sk_test_mock_CATALOG_123456";
|
||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
// A mock service for the code-mode call (own service on 127.0.0.1).
|
||
const seen: Array<{ method: string; url: string; headers: IncomingHttpHeaders }> = [];
|
||
let mock: Server;
|
||
let base: string;
|
||
|
||
before(async () => {
|
||
mock = createServer((req, res) => {
|
||
seen.push({ method: req.method!, url: req.url!, headers: req.headers });
|
||
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));
|
||
base = `http://127.0.0.1:${(mock.address() as AddressInfo).port}/api`;
|
||
anna = await core.upsertUserFromGitea(db, { id: 2491, login: "mock-anna-249" }, { access_token: "a" });
|
||
});
|
||
after(async () => {
|
||
await new Promise<void>((r) => mock.close(() => r()));
|
||
await teardown();
|
||
});
|
||
|
||
async function ownedProject() {
|
||
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]!;
|
||
return { proj, task };
|
||
}
|
||
|
||
let seq = 0;
|
||
async function agentSession(projectId: number, taskId: number) {
|
||
const s = await core.createSession(db, { projectId, taskId });
|
||
const [a] = await db.insert(agents).values({ name: `Мок-249 ${++seq}-${Date.now()}` }).returning();
|
||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
|
||
return s.id;
|
||
}
|
||
|
||
/** Records the outbound request and answers like the service would. */
|
||
function mockFetch(answer: { status?: number; body?: string } = {}) {
|
||
const calls: Array<{ url: URL; method: string; headers: Record<string, string> }> = [];
|
||
const fetch: Fetch = async ({ url, method, headers }) => {
|
||
calls.push({ url, method, headers });
|
||
return { status: answer.status ?? 200, contentType: "application/json", body: Buffer.from(answer.body ?? JSON.stringify({ ok: true, url: url.href })), truncated: false };
|
||
};
|
||
return { fetch, calls };
|
||
}
|
||
|
||
describe("Каталог сервисов", () => {
|
||
test("Каждая карточка: адрес, способ ключа, правило чтения, проверка", () => {
|
||
const was = process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
|
||
delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
|
||
try {
|
||
const ids = new Set<string>();
|
||
assert.ok(core.CONNECTION_CATALOG.length >= 20, "about 20 services");
|
||
for (const s of core.CONNECTION_CATALOG) {
|
||
assert.ok(!ids.has(s.id), `unique id ${s.id}`);
|
||
ids.add(s.id);
|
||
assert.match(s.id, /^[a-z0-9-]+$/, `${s.id}: short name is latin`);
|
||
assert.equal(core.parseBaseUrl(s.baseUrl), s.baseUrl.replace(/\/$/, ""), `${s.id}: base address is public https`);
|
||
assert.ok(["bearer", "header", "basic", "query", "path"].includes(s.auth), `${s.id}: auth`);
|
||
if (s.auth === "header" || s.auth === "query") assert.match(s.authParam ?? "", /^[A-Za-z][A-Za-z0-9_-]+$/, `${s.id}: header/param name`);
|
||
assert.match(s.docsUrl, /^https:\/\//, `${s.id}: docs`);
|
||
assert.match(s.keyUrl, /^https:\/\//, `${s.id}: where to get the key`);
|
||
assert.ok(s.keyHint.length > 10, `${s.id}: key hint`);
|
||
assert.ok(core.CATALOG_KINDS.includes(s.kind), `${s.id}: kind`);
|
||
assert.ok(s.read.length > 0, `${s.id}: read rule`);
|
||
for (const r of s.read) assert.match(r, /^(GET|POST) \/[A-Za-z0-9._*/-]*$/, `${s.id}: read rule «${r}»`);
|
||
assert.ok(core.cleanPath(s.check.path), `${s.id}: check path is clean`);
|
||
assert.equal(core.classifyRequest(s.id, "DELETE", "/anything"), "write", `${s.id}: DELETE is never read`);
|
||
for (const k of Object.keys(s.headers ?? {})) assert.ok(!["authorization", "host", "cookie", "content-length"].includes(k.toLowerCase()), `${s.id}: fixed header ${k}`);
|
||
}
|
||
for (const id of ["github", "gitea", "stripe", "google-sheets", "google-drive", "google-calendar", "telegram", "resend", "sendgrid", "openai", "anthropic", "cloudflare", "sentry", "bugsink", "supabase", "notion", "airtable", "slack", "twilio", "kaspi", "2gis"]) assert.ok(ids.has(id), `catalog has ${id}`);
|
||
} finally {
|
||
if (was != null) process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = was;
|
||
}
|
||
});
|
||
|
||
test("Поиск по каталогу", () => {
|
||
const mail = core.searchCatalog("почта").map((s) => s.id);
|
||
assert.ok(mail.includes("resend") && mail.includes("sendgrid"));
|
||
assert.ok(!mail.includes("stripe"));
|
||
assert.deepEqual(core.searchCatalog("", { kind: "payments" }).map((s) => s.id), ["stripe"]);
|
||
assert.ok(core.searchCatalog("каспи").some((s) => s.id === "kaspi"));
|
||
assert.equal(core.searchCatalog("").length, core.CONNECTION_CATALOG.length);
|
||
});
|
||
|
||
test("Правило чтения: методы-изменения через GET и поиск через POST", () => {
|
||
assert.equal(core.classifyRequest("slack", "GET", "/conversations.history"), "read");
|
||
assert.equal(core.classifyRequest("slack", "GET", "/chat.postMessage"), "write");
|
||
assert.equal(core.classifyRequest("telegram", "GET", "/getMe"), "read");
|
||
assert.equal(core.classifyRequest("telegram", "GET", "/sendMessage"), "write");
|
||
assert.equal(core.classifyRequest("notion", "POST", "/v1/databases/abc123/query"), "read");
|
||
assert.equal(core.classifyRequest("notion", "POST", "/v1/databases//query"), "write");
|
||
assert.equal(core.classifyRequest("notion", "POST", "/v1/pages"), "write");
|
||
assert.equal(core.classifyRequest("stripe", "GET", "/v1/customers"), "read");
|
||
assert.equal(core.classifyRequest("stripe", "POST", "/v1/refunds"), "write");
|
||
assert.equal(core.classifyRequest(null, "GET", "/items"), "read");
|
||
assert.equal(core.classifyRequest(null, "POST", "/items"), "write");
|
||
});
|
||
|
||
test("Подключение Stripe из каталога", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "stripe", secret: KEY });
|
||
assert.equal(c.name, "Stripe");
|
||
assert.equal(c.baseUrl, "https://api.stripe.com");
|
||
assert.equal(c.slug, "stripe");
|
||
assert.equal(c.catalogId, "stripe");
|
||
assert.equal(c.authKind, "bearer");
|
||
const second = await core.createConnection(db, anna.id, { catalogId: "stripe", name: "Stripe — магазин", secret: KEY });
|
||
assert.equal(second.slug, "stripe-2");
|
||
const own = await core.createConnection(db, anna.id, { name: "Мой магазин", baseUrl: "https://shop.example.com/api", secret: KEY });
|
||
assert.equal(own.slug, "moi-magazin");
|
||
assert.ok(!JSON.stringify(await core.listConnections(db, anna.id)).includes(KEY));
|
||
});
|
||
|
||
test("Сервис со своим адресом требует адрес", async () => {
|
||
await assert.rejects(core.createConnection(db, anna.id, { catalogId: "gitea", secret: KEY }), /адрес/i);
|
||
await assert.rejects(core.createConnection(db, anna.id, { catalogId: "gitea", baseUrl: "https://gitea.example.com/api/v1", secret: KEY }), /образца/);
|
||
const g = await core.createConnection(db, anna.id, { catalogId: "gitea", baseUrl: "https://git.example.org/api/v1", secret: KEY });
|
||
assert.equal(g.baseUrl, "https://git.example.org/api/v1");
|
||
await assert.rejects(core.createConnection(db, anna.id, { catalogId: "nope", secret: KEY }), /каталоге/);
|
||
await assert.rejects(core.createConnection(db, anna.id, { catalogId: "twilio", secret: "no-colon" }), /логин:пароль/);
|
||
});
|
||
});
|
||
|
||
describe("Права «чтение» и «запись»", () => {
|
||
test("Чтение выполняется, запись отклоняется", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "stripe", name: "Stripe-rw", secret: KEY });
|
||
const { proj, task } = await ownedProject();
|
||
const g = await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: "auto" });
|
||
assert.equal(g.readMode, "auto");
|
||
assert.equal(g.writeMode, "off");
|
||
assert.deepEqual(g.operations, []);
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
const m = mockFetch();
|
||
const ok = await core.callConnection(db, { sessionId, connection: "Stripe-rw", method: "GET", path: "/v1/customers?limit=3" }, { fetch: m.fetch });
|
||
assert.equal(ok.ok, true);
|
||
assert.equal(m.calls[0]!.url.href, "https://api.stripe.com/v1/customers?limit=3");
|
||
assert.equal(m.calls[0]!.headers.authorization, `Bearer ${KEY}`);
|
||
const w = await core.callConnection(db, { sessionId, connection: "Stripe-rw", method: "POST", path: "/v1/refunds", body: "{}" }, { fetch: m.fetch });
|
||
assert.deepEqual(w, { ok: false, reason: "write_denied" });
|
||
assert.equal(core.CONNECTION_REASON_TEXT.write_denied, "запись не разрешена");
|
||
assert.equal(m.calls.length, 1, "the write never left FORGE");
|
||
});
|
||
|
||
test("«Спрашивать меня» до подтверждений", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "stripe", name: "Stripe-ask", secret: KEY });
|
||
const { proj, task } = await ownedProject();
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: "ask", writeMode: "ask" });
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
const m = mockFetch();
|
||
assert.deepEqual(await core.callConnection(db, { sessionId, connection: "Stripe-ask", method: "POST", path: "/v1/refunds", body: "{}" }, { fetch: m.fetch }), { ok: false, reason: "needs_approval" });
|
||
assert.deepEqual(await core.callConnection(db, { sessionId, connection: "Stripe-ask", method: "GET", path: "/v1/balance" }, { fetch: m.fetch }), { ok: false, reason: "needs_approval" });
|
||
assert.equal(m.calls.length, 0);
|
||
const [row] = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||
assert.equal(row!.reason, "needs_approval");
|
||
});
|
||
|
||
test("Изменение через GET у Slack — не чтение", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "slack", secret: "xoxb-mock-123456" });
|
||
const { proj, task } = await ownedProject();
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: "auto" });
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
const m = mockFetch();
|
||
assert.deepEqual(await core.callConnection(db, { sessionId, connection: "slack", method: "GET", path: "/chat.postMessage?channel=C1&text=hi" }, { fetch: m.fetch }), { ok: false, reason: "write_denied" });
|
||
assert.equal((await core.callConnection(db, { sessionId, connection: "slack", method: "GET", path: "/conversations.list" }, { fetch: m.fetch })).ok, true);
|
||
});
|
||
|
||
test("Запись без чтения, тонкая настройка поверх режимов, пустое разрешение отклоняется", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "github", secret: KEY });
|
||
const { proj, task } = await ownedProject();
|
||
await assert.rejects(core.grantConnection(db, anna.id, c.id, { projectId: proj.id }), /чтение, запись/);
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, writeMode: "auto", operations: "GET /user" });
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
const m = mockFetch();
|
||
assert.equal((await core.callConnection(db, { sessionId, connection: "github", method: "POST", path: "/repos/a/b/issues", body: "{}" }, { fetch: m.fetch })).ok, true);
|
||
assert.equal((await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/user" }, { fetch: m.fetch })).ok, true, "fine-grained line");
|
||
assert.deepEqual(await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/repos/a/b" }, { fetch: m.fetch }), { ok: false, reason: "read_denied" });
|
||
assert.equal(m.calls[0]!.headers["x-github-api-version"], "2022-11-28", "fixed header of the card");
|
||
});
|
||
});
|
||
|
||
describe("Способы передачи ключа", () => {
|
||
async function granted(catalogId: string, secret: string, extra: { baseUrl?: string } = {}) {
|
||
const c = await core.createConnection(db, anna.id, { catalogId, secret, ...extra });
|
||
const { proj, task } = await ownedProject();
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: "auto" });
|
||
return { c, sessionId: await agentSession(proj.id, task.id) };
|
||
}
|
||
|
||
test("basic: «логин:пароль» кодируется", async () => {
|
||
const { c, sessionId } = await granted("twilio", "ACmock123:authmock456");
|
||
const m = mockFetch();
|
||
assert.equal((await core.callConnection(db, { sessionId, connection: c.slug, method: "GET", path: "/Accounts.json" }, { fetch: m.fetch })).ok, true);
|
||
assert.equal(m.calls[0]!.headers.authorization, `Basic ${Buffer.from("ACmock123:authmock456").toString("base64")}`);
|
||
assert.equal(m.calls[0]!.url.href, "https://api.twilio.com/2010-04-01/Accounts.json");
|
||
});
|
||
|
||
test("query: ключ добавляет FORGE, ключ агента выбрасывается, в журнале его нет", async () => {
|
||
const secret = "AIzaMockGoogleKey123456";
|
||
const { c, sessionId } = await granted("google-sheets", secret);
|
||
const m = mockFetch({ body: JSON.stringify({ echo: secret }) });
|
||
const r = await core.callConnection(db, { sessionId, connection: c.slug, method: "GET", path: "/v4/spreadsheets/abc?key=agent-own&ranges=A1" }, { fetch: m.fetch });
|
||
assert.equal(r.ok, true);
|
||
assert.equal(m.calls[0]!.url.searchParams.getAll("key").join(), secret);
|
||
assert.equal(m.calls[0]!.url.searchParams.get("ranges"), "A1");
|
||
assert.equal(m.calls[0]!.headers.authorization, undefined);
|
||
assert.ok(r.ok && !r.body.includes(secret), "masked in the answer");
|
||
const rows = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||
assert.ok(!JSON.stringify(rows).includes(secret));
|
||
});
|
||
|
||
test("path: ключ Telegram в пути, наружу не выходит", async () => {
|
||
const secret = "123456:AAmockTelegramKey";
|
||
const { c, sessionId } = await granted("telegram", secret);
|
||
const m = mockFetch({ body: JSON.stringify({ ok: true, echo: `https://api.telegram.org/bot${secret}/getMe` }) });
|
||
const r = await core.callConnection(db, { sessionId, connection: "telegram", method: "GET", path: "/getMe" }, { fetch: m.fetch });
|
||
assert.equal(r.ok, true);
|
||
assert.equal(m.calls[0]!.url.pathname, `/bot${secret}/getMe`);
|
||
assert.ok(r.ok && !r.body.includes(secret));
|
||
assert.deepEqual(await core.callConnection(db, { sessionId, connection: "telegram", method: "GET", path: "/sendMessage?chat_id=1&text=hi" }, { fetch: m.fetch }), { ok: false, reason: "write_denied" });
|
||
await assert.rejects(core.createConnection(db, anna.id, { catalogId: "telegram", name: "TG bad", secret: "a/b?c" }), /недопустимые/);
|
||
const rows = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||
assert.ok(!JSON.stringify(rows).includes(secret));
|
||
});
|
||
|
||
test("header + постоянный заголовок: Anthropic", async () => {
|
||
const { c, sessionId } = await granted("anthropic", "sk-ant-mock-123456");
|
||
const m = mockFetch();
|
||
assert.equal((await core.callConnection(db, { sessionId, connection: c.slug, method: "GET", path: "/v1/models" }, { fetch: m.fetch })).ok, true);
|
||
assert.equal(m.calls[0]!.headers["x-api-key"], "sk-ant-mock-123456");
|
||
assert.equal(m.calls[0]!.headers["anthropic-version"], "2023-06-01");
|
||
assert.equal(m.calls[0]!.headers.authorization, undefined);
|
||
});
|
||
});
|
||
|
||
describe("Проверка подключения", () => {
|
||
test("Ключ работает / не подходит / сервис не отвечает", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "github", name: "GitHub-check", secret: KEY });
|
||
const ok = mockFetch({ status: 200 });
|
||
const r = await core.checkConnection(db, anna.id, c.id, { fetch: ok.fetch });
|
||
assert.equal(r.status, "ok");
|
||
assert.equal(ok.calls[0]!.url.href, "https://api.github.com/user");
|
||
assert.equal(ok.calls[0]!.headers.authorization, `Bearer ${KEY}`);
|
||
const view = (await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!;
|
||
assert.equal(view.checkStatus, "ok");
|
||
assert.ok(view.checkedAt);
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id, { fetch: mockFetch({ status: 401 }).fetch })).status, "bad_key");
|
||
const down: Fetch = async () => {
|
||
throw new Error("ECONNREFUSED");
|
||
};
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id, { fetch: down })).status, "down");
|
||
assert.equal((await core.checkConnection(db, anna.id, c.id, { fetch: mockFetch({ status: 503 }).fetch })).status, "down");
|
||
const log = await db.select().from(connectionLog).where(eq(connectionLog.connectionId, c.id));
|
||
assert.ok(log.length >= 4 && log.every((l) => l.reason === "owner_check" && !JSON.stringify(l).includes(KEY)));
|
||
// Someone else can't check it.
|
||
const boris = await core.upsertUserFromGitea(db, { id: 2492, login: "mock-boris-249" }, { access_token: "b" });
|
||
await assert.rejects(core.checkConnection(db, boris.id, c.id, { fetch: ok.fetch }), core.PeppaError);
|
||
// A new key forgets the old result.
|
||
await core.replaceConnectionSecret(db, anna.id, c.id, "sk_new_mock_999999");
|
||
assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.checkStatus, null);
|
||
});
|
||
|
||
test("Правила каталога: Slack 200 с ok:false, Google 404 — ключ принят", () => {
|
||
const card = (id: string) => core.catalogService(id)!.check;
|
||
assert.equal(core.judgeCheck(card("slack"), { status: 200, body: '{"ok":false,"error":"invalid_auth"}' }).status, "bad_key");
|
||
assert.equal(core.judgeCheck(card("slack"), { status: 200, body: '{"ok": true, "user":"x"}' }).status, "ok");
|
||
assert.equal(core.judgeCheck(card("google-sheets"), { status: 404, body: "" }).status, "ok");
|
||
assert.equal(core.judgeCheck(card("google-sheets"), { status: 400, body: "API key not valid" }).status, "bad_key");
|
||
assert.equal(core.judgeCheck(card("kaspi"), { status: 400, body: "" }).status, "ok");
|
||
assert.equal(core.judgeCheck(null, { status: 404, body: "" }).status, "ok");
|
||
assert.equal(core.judgeCheck(null, { status: 403, body: "" }).status, "bad_key");
|
||
assert.equal(core.judgeCheck(null, null).status, "down");
|
||
});
|
||
|
||
test("Ключ перестал работать — одно сообщение", async () => {
|
||
const was = process.env.PEPPA_CONNECTION_CHECK;
|
||
process.env.PEPPA_CONNECTION_CHECK = "on";
|
||
try {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "stripe", name: "Stripe-daily", secret: KEY });
|
||
// Only this connection is due: the others were checked «now».
|
||
await db.update(connections).set({ checkedAt: new Date(Date.now() + 365 * 86400_000) });
|
||
await db.update(connections).set({ checkedAt: null }).where(eq(connections.id, c.id));
|
||
const told: number[] = [];
|
||
const notify = async (_db: unknown, x: { id: number }) => void told.push(x.id);
|
||
const t0 = Date.now();
|
||
await core.connectionCheckTick(db, { fetch: mockFetch({ status: 200 }).fetch, now: new Date(t0), notify });
|
||
assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.checkStatus, "ok");
|
||
// Not due again within a day.
|
||
assert.equal(await core.connectionCheckTick(db, { fetch: mockFetch({ status: 401 }).fetch, now: new Date(t0 + 3600_000), notify }), 0);
|
||
await core.connectionCheckTick(db, { fetch: mockFetch({ status: 401 }).fetch, now: new Date(t0 + 25 * 3600_000), notify });
|
||
await core.connectionCheckTick(db, { fetch: mockFetch({ status: 401 }).fetch, now: new Date(t0 + 50 * 3600_000), notify });
|
||
assert.deepEqual(told, [c.id], "one message");
|
||
assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === c.id)!.checkStatus, "bad_key");
|
||
// Off by the switch.
|
||
process.env.PEPPA_CONNECTION_CHECK = "off";
|
||
assert.equal(await core.connectionCheckTick(db, { now: new Date(t0 + 100 * 3600_000), notify }), 0);
|
||
} finally {
|
||
process.env.PEPPA_CONNECTION_CHECK = was;
|
||
}
|
||
});
|
||
|
||
test("Сообщение владельцу о ключе уходит в мастер-чат", async () => {
|
||
const c = await core.createConnection(db, anna.id, { catalogId: "resend", secret: "re_mock_123456" });
|
||
await core.tellKeyStopped(db, { id: c.id, ownerId: anna.id, name: c.name });
|
||
const feed = await core.masterFeed(db, anna);
|
||
assert.ok(feed.some((m) => stripAsIs(m.text).includes("Ключ доступа подключения «Resend» перестал работать")));
|
||
});
|
||
});
|
||
|
||
describe("Короткое имя подключения для агента", () => {
|
||
test("Вызов по короткому имени в режиме «код»", async () => {
|
||
const was = process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
|
||
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1";
|
||
try {
|
||
const c = await core.createConnection(db, anna.id, { name: "CRM код", baseUrl: base, secret: KEY });
|
||
assert.equal(c.slug, "crm-kod");
|
||
const { proj, task } = await ownedProject();
|
||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, readMode: "auto", writeMode: "ask" });
|
||
const sessionId = await agentSession(proj.id, task.id);
|
||
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 callTool = 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 };
|
||
};
|
||
const list = await callTool("list_connections");
|
||
assert.match(list.text, /- crm-kod \(#\d+ «CRM код», own service\)/);
|
||
assert.match(list.text, /read: at once; write: asks the owner/);
|
||
assert.match(list.text, /key: not checked yet/);
|
||
const sig = await callTool("search_api", { query: "connections call" });
|
||
assert.match(sig.text, /peppa\.connections\.call\(connection: [^,]+, args: \{/);
|
||
const r = await callTool("execute", { code: 'return await peppa.connections.call("crm-kod", {method: "GET", path: "/items/7"});' });
|
||
assert.equal(r.isError, false, r.text);
|
||
assert.match(r.text, /HTTP 200/);
|
||
assert.equal(seen.at(-1)!.url, "/api/items/7");
|
||
assert.equal(seen.at(-1)!.headers.authorization, `Bearer ${KEY}`);
|
||
const w = await callTool("execute", { code: 'return await peppa.connections.call("crm-kod", {method: "POST", path: "/items", body: "{}"});' });
|
||
assert.equal(w.isError, true);
|
||
assert.match(w.text, /needs_approval/);
|
||
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
|
||
assert.ok(log.some((l) => l.method === "GET" && l.path === "/items/7" && l.decision === "allowed"));
|
||
assert.ok(!JSON.stringify(log).includes(KEY));
|
||
} finally {
|
||
if (was == null) delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
|
||
else process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = was;
|
||
}
|
||
});
|
||
});
|