Merge pull request 'PEP-261: «Дать: чтение / полные права» и срок кнопками под запросом доступа агента' (#297) from task/pep-261 into main
Заход приёмки 27.11: PEP-261 перед исправлением PEP-315 [skip ci]
This commit is contained in:
commit
7e84bfd9eb
4
.peppa/memory/pep-261.md
Normal file
4
.peppa/memory/pep-261.md
Normal file
@ -0,0 +1,4 @@
|
||||
# Память: PEP-261
|
||||
|
||||
## Грабли
|
||||
- Тесты с агентом-моком (access-requests, bot) в песочнице молча висят по 25 с на Node 22 — нужен Node 26 из tarball и tmux из .deb в PATH/LD_LIBRARY_PATH (PEP-261).
|
||||
@ -80,8 +80,8 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner";
|
||||
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
||||
import { delayAction, denyAccessRequestAndTell, grantAccessRequestByButton, resolveTaskById } from "@peppa/runner";
|
||||
import { accessButtonTarget, accessRequestKeyboard, decideIdleGrant, GRANT_TERM_TEXT, NO_CONNECTION_TEXT, parseAccessCallback, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
||||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||||
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
@ -978,6 +978,39 @@ export function createBot(o: BotOptions) {
|
||||
return "done";
|
||||
}
|
||||
|
||||
/** PEP-261: «Дать: чтение / полные права» → term → grant; «Назад»; «Отказать». The owner only (core: accessRequestForUser). */
|
||||
async function onAccessButton(user: User, c: TgCallbackQuery): Promise<string> {
|
||||
const b = parseAccessCallback(c.data ?? "");
|
||||
if (!b) return tr("Неизвестная кнопка");
|
||||
const keyboard = (inline_keyboard: unknown[]) =>
|
||||
c.message ? api.call("editMessageReplyMarkup", { chat_id: c.message.chat.id, message_id: c.message.message_id, reply_markup: { inline_keyboard } }).catch(() => {}) : Promise.resolve();
|
||||
if (b.action === "no") {
|
||||
await denyAccessRequestAndTell(db, user.id, b.id, null);
|
||||
await keyboard([]);
|
||||
return tr("Отказано. Агент узнает об этом.");
|
||||
}
|
||||
if (b.action === "back") {
|
||||
const canGrant = await accessButtonTarget(db, user.id, b.id).then(
|
||||
() => true,
|
||||
(e) => {
|
||||
if (e instanceof PeppaError && e.message === NO_CONNECTION_TEXT) return false;
|
||||
throw e;
|
||||
},
|
||||
);
|
||||
await keyboard(accessRequestKeyboard(b.id, { step: "rights", canGrant }));
|
||||
return tr("Выберите, что дать агенту");
|
||||
}
|
||||
if (b.action === "rights") {
|
||||
await accessButtonTarget(db, user.id, b.id); // not the owner, decided already or no connection → the refusal is the toast
|
||||
await keyboard(accessRequestKeyboard(b.id, { step: "term", rights: b.rights }));
|
||||
return tr("Выберите срок");
|
||||
}
|
||||
await grantAccessRequestByButton(db, user.id, b.id, { rights: b.rights, term: b.term });
|
||||
await keyboard([]);
|
||||
const what = b.rights === "full" ? tr("полные права") : tr("чтение");
|
||||
return tr("Готово: {what}, {term}. Агент узнает об этом.", { what, term: GRANT_TERM_TEXT[b.term] });
|
||||
}
|
||||
|
||||
async function onDelayButton(user: User, data: string): Promise<string> {
|
||||
const b = parseDelayCallback(data);
|
||||
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
||||
@ -1019,12 +1052,10 @@ export function createBot(o: BotOptions) {
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
// PEP-250: «Отказать» under an agent's access request: `ar:<id>:no` — only the project's owner (core checks).
|
||||
// PEP-250/261: buttons under an agent's access request — `ar:<id>:no` (refuse), `ar:<id>:r|f` (rights →
|
||||
// term buttons), `ar:<id>:r|f:<term>` (grant), `ar:<id>:back`. Only the project's owner (core checks).
|
||||
if (parts[0] === "ar") {
|
||||
const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then(
|
||||
() => tr("Отказано. Агент узнает об этом."),
|
||||
(e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
|
||||
);
|
||||
const toast = await onAccessButton(user, c).catch((e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
|
||||
@ -71,7 +71,7 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
||||
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||
@ -1141,6 +1141,12 @@ export async function setConnectionIdleAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
// PEP-261: rights and term chosen by the owner («Дать: чтение / полные права», срок — 1 день по умолчанию).
|
||||
function grantChoice(f: FormData): { rights?: "read" | "full"; term: GrantTerm } {
|
||||
const rights = str(f, "rights");
|
||||
return { rights: rights === "full" || rights === "read" ? rights : undefined, term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM };
|
||||
}
|
||||
|
||||
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
||||
export async function connectAccessRequestAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
@ -1153,7 +1159,7 @@ export async function connectAccessRequestAction(f: FormData) {
|
||||
secret: String(f.get("secret") ?? "").trim(),
|
||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||
authHeader: str(f, "authHeader") || null,
|
||||
});
|
||||
}, grantChoice(f));
|
||||
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
||||
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
||||
});
|
||||
@ -1163,7 +1169,17 @@ export async function grantAccessRequestAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")));
|
||||
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")), grantChoice(f));
|
||||
return `/connections/requests/${id}?done=granted`;
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-261: «Дать: чтение / полные права» with a term in «Агенты просят доступ». */
|
||||
export async function grantAccessButtonAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const id = Number(str(f, "requestId"));
|
||||
await grantAccessRequestByButton(db, user.id, id, grantChoice(f));
|
||||
return `/connections/requests/${id}?done=granted`;
|
||||
});
|
||||
}
|
||||
|
||||
@ -18,6 +18,7 @@ import {
|
||||
listConnections,
|
||||
listUserProjects,
|
||||
ownerAccessRequests,
|
||||
connectionsForRequest,
|
||||
oauthOffer,
|
||||
scopeLabel,
|
||||
searchCatalog,
|
||||
@ -652,6 +653,8 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
||||
const t = await getT();
|
||||
const engineer = (await uiMode()) === "engineer";
|
||||
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
|
||||
// PEP-261: «Дать» right in the list — only where a fitting connection exists.
|
||||
const grantable = new Set((await Promise.all(requests.map(async (r) => ((await connectionsForRequest(db, user.id, r)).fit.length ? r.id : 0)))).filter(Boolean));
|
||||
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
|
||||
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
||||
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
||||
@ -668,7 +671,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
||||
|
||||
{requests.length > 0 && (
|
||||
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
||||
<AccessRequestList list={requests} t={t} />
|
||||
<AccessRequestList list={requests} grantable={grantable} t={t} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ import { notFound } from "next/navigation";
|
||||
import { ExternalLink, KeyRound } from "lucide-react";
|
||||
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
||||
import type { Translator } from "@peppa/shared/i18n";
|
||||
import { AccessStatus, accessModeText } from "@/components/AccessRequests";
|
||||
import { AccessStatus, accessModeText, GrantRightsSelect, GrantTermSelect } from "@/components/AccessRequests";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -42,6 +42,17 @@ function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Tran
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-261: rights and term of the grant (1 day by default). */
|
||||
function GrantFields({ r, t }: { r: AccessRequestView; t: Translator }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<GrantRightsSelect r={r} t={t} />
|
||||
<span className="text-muted-foreground">{t("на срок")}</span>
|
||||
<GrantTermSelect t={t} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
||||
const back = `/connections/requests/${r.id}`;
|
||||
return (
|
||||
@ -76,6 +87,7 @@ function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogServic
|
||||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||
</div>
|
||||
)}
|
||||
<GrantFields r={r} t={t} />
|
||||
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
||||
</form>
|
||||
</li>
|
||||
@ -97,6 +109,7 @@ function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: Connect
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<GrantFields r={r} t={t} />
|
||||
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
||||
</form>
|
||||
);
|
||||
@ -155,9 +168,7 @@ export default async function AccessRequestPage({ params, searchParams }: { para
|
||||
<Card className="p-4">
|
||||
<ConnectForm r={r} card={card} t={t} />
|
||||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||||
{r.mode === "write"
|
||||
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
||||
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
||||
{t("Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
@ -1,11 +1,16 @@
|
||||
import Link from "@/components/Link";
|
||||
import { KeyRound } from "lucide-react";
|
||||
import type { AccessRequestView } from "@peppa/core";
|
||||
import { DEFAULT_GRANT_TERM, GRANT_TERM_TEXT, GRANT_TERMS, type AccessRequestView } from "@peppa/core";
|
||||
import type { Translator } from "@peppa/shared/i18n";
|
||||
import { denyAccessRequestAction, grantAccessButtonAction } from "@/app/(app)/actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { ago } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
||||
|
||||
/** «читать» / «читать и менять». */
|
||||
export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string {
|
||||
return mode === "write" ? t("читать и менять") : t("только читать");
|
||||
@ -18,8 +23,31 @@ export function AccessStatus({ r, t }: { r: AccessRequestView; t: Translator })
|
||||
return <Badge variant="outline">{t("агент отменил запрос")}</Badge>;
|
||||
}
|
||||
|
||||
/** PEP-250: «Агенты просят доступ» on «Подключения» — the owner's open requests. */
|
||||
export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: Translator }) {
|
||||
/** PEP-261: the term of a grant — 1 day by default. */
|
||||
export function GrantTermSelect({ t }: { t: Translator }) {
|
||||
return (
|
||||
<select name="term" defaultValue={DEFAULT_GRANT_TERM} aria-label={t("Срок")} className={SELECT}>
|
||||
{GRANT_TERMS.map((term) => (
|
||||
<option key={term} value={term}>
|
||||
{t.text(GRANT_TERM_TEXT[term])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-261: «чтение» / «полные права» — by default what the agent asked for. */
|
||||
export function GrantRightsSelect({ r, t }: { r: AccessRequestView; t: Translator }) {
|
||||
return (
|
||||
<select name="rights" defaultValue={r.mode === "write" ? "full" : "read"} aria-label={t("Что можно")} className={SELECT}>
|
||||
<option value="read">{t("Чтение")}</option>
|
||||
<option value="full">{t("Полные права: чтение и изменения")}</option>
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-250/261: «Агенты просят доступ» on «Подключения» — the owner's open requests with «Дать» buttons. `grantable` — requests with a fitting connection. */
|
||||
export function AccessRequestList({ list, grantable, t }: { list: AccessRequestView[]; grantable: Set<number>; t: Translator }) {
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{list.map((r) => (
|
||||
@ -36,6 +64,31 @@ export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: T
|
||||
<Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline">
|
||||
{t("Посмотреть и решить")}
|
||||
</Link>
|
||||
<div className="flex basis-full flex-wrap items-center gap-2 pt-1">
|
||||
{grantable.has(r.id) ? (
|
||||
<form action={grantAccessButtonAction} className="flex flex-wrap items-center gap-2">
|
||||
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
|
||||
<Button size="sm" name="rights" value="read" data-access-grant="read">
|
||||
{t("Дать: чтение")}
|
||||
</Button>
|
||||
<Button size="sm" variant="secondary" name="rights" value="full" data-access-grant="full">
|
||||
{t("Дать: полные права")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground">{t("на срок")}</span>
|
||||
<GrantTermSelect t={t} />
|
||||
</form>
|
||||
) : (
|
||||
<Button asChild size="sm">
|
||||
<Link href={`/connections/requests/${r.id}`}>{t("Подключить")}</Link>
|
||||
</Button>
|
||||
)}
|
||||
<form action={denyAccessRequestAction}>
|
||||
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
|
||||
<Button size="sm" variant="outline">
|
||||
{t("Отказать")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@ -0,0 +1,10 @@
|
||||
## Решения
|
||||
|
||||
- **Какое подключение выдаётся кнопкой.** Подходящие — активные подключения владельца с ключом той же карточки каталога или того же адреса (`connectionsForRequest().fit`). Кнопка берёт первое из них (последнее созданное идёт первым в `listConnections`). Выбрать другое можно на карточке запроса — там прежняя форма со списком.
|
||||
- **Права.** «Дать: чтение» = `GRANT_RIGHTS.read`, «полные права» = `GRANT_RIGHTS.full`. Если у проекта уже было разрешение этого подключения, режимы только расширяются (как в PEP-250): кнопка «чтение» не отнимает у других агентов запись. Срок заменяется выбранным — это сознательное решение владельца.
|
||||
- **Срок по умолчанию** — `DEFAULT_GRANT_TERM` (1 день): в вебе он выбран в списке, в Telegram — первая строка кнопок срока и подсказка в тексте.
|
||||
- **Telegram, два шага.** `ar:<id>:r|f` — меняем клавиатуру сообщения (`editMessageReplyMarkup`) на сроки `ar:<id>:r|f:<1h|1d|7d|forever>` и «Назад» (`ar:<id>:back` возвращает исходные кнопки). `ar:<id>:no` — прежний отказ. Нажатие проверяет владельца в ядре (`ownOpen` → `accessRequestForUser`): чужой получает «Запрос не найден», клавиатура не меняется. Проверка подключения делается уже на первом шаге, чтобы владелец без подключения сразу получил подсказку. После выдачи клавиатура убирается.
|
||||
- **Кнопки «Дать» в сообщении** показываются, только если подходящее подключение есть на момент сообщения; иначе — «Подключить» (ссылка на карточку) и «Отказать». Ссылка — только при https `PEPPA_WEB_URL` (как раньше).
|
||||
- **Ночная тишина и пауза** — не трогаем: сообщение идёт через `deliverToUser`/outbox, ответ на нажатие — прямой ответ человеку; агента проекта на паузе `tellAgentAboutAccess` не будит.
|
||||
- **Агенту** текст решения говорит срок: «чтение на 1 день».
|
||||
- **Отказ по сроку** (`expired`, `idle_revoked`): подсказка `request_access(service: …, purpose: …)` вместо «через ask_pm»; запрос сам не создаётся — агент сам объясняет, зачем ему доступ снова.
|
||||
@ -0,0 +1,14 @@
|
||||
## Why
|
||||
Агент просит доступ к сервису (PEP-250), а у разрешения есть срок (PEP-259), но владелец пока решает только на карточке запроса и без выбора срока: разрешение из запроса выдаётся «до отзыва». Нужно, чтобы владелец ответил прямо под сообщением о запросе — в Telegram и в вебе — кнопками «Дать: чтение», «Дать: полные права», «Отказать» и выбрал срок.
|
||||
|
||||
## What Changes
|
||||
- Сообщение о запросе доступа в Telegram: кнопки «Дать: чтение» · «Дать: полные права» (если у владельца уже есть подходящее подключение), «Отказать», ссылка на карточку. После выбора прав кнопки меняются на срок: «1 час» · «1 день» · «7 дней» · «до отзыва» и «Назад».
|
||||
- Подключения ещё нет — вместо «Дать» ссылка «Подключить» на карточку запроса (шаги каталога PEP-249), там же выбираются права и срок; нажатие «Дать» без подключения отвечает подсказкой открыть запрос.
|
||||
- Веб «Агенты просят доступ» (`/connections`): у запроса с подходящим подключением — «Дать: чтение» / «Дать: полные права» со сроком (по умолчанию 1 день) и «Отказать»; без подключения — «Подключить». Карточка запроса: в формах «Подключить и разрешить» и «Разрешить уже подключённое» — права и срок.
|
||||
- Ядро: `grantAccessByButton(db, userId, id, { rights, term })` и `rights`/`term` в `grantAccessFromExisting`/`connectAndGrantAccess`; выдача — `grantConnection` с `term`, права — `GRANT_RIGHTS` (прежнее разрешение проекта только расширяется). По умолчанию срок — `DEFAULT_GRANT_TERM` (1 день).
|
||||
- Решает только владелец проекта (и подключения — `grantConnection` проверяет); ночная тишина и пауза — как у прежнего сообщения (`deliverToUser`, агента на паузе не будим).
|
||||
- Отказ шлюза `expired` / `idle_revoked` подсказывает агенту `request_access` с названием сервиса.
|
||||
- «Полные права» = чтение и запись сразу; отдельный режим записи с согласованием — PEP-235, когда появится.
|
||||
|
||||
## Impact
|
||||
- `packages/core/src/access-requests.ts`, `packages/runner/src/access-requests.ts`, `apps/bot/src/bot.ts`, веб `/connections` и `/connections/requests/[id]`, `components/AccessRequests.tsx`, действия, `packages/mcp/src/agent.ts`, переводы en/kk, тесты `access-request-buttons.test.ts`.
|
||||
@ -0,0 +1,36 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Кнопки выдачи под запросом доступа
|
||||
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, прежнее разрешение проекта SHALL только расширяться по правам. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
|
||||
|
||||
#### Scenario: Чтение на 1 день кнопкой в Telegram
|
||||
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
|
||||
- **WHEN** «anna» нажимает «Дать: чтение», затем «1 день»
|
||||
- **THEN** проекту «SHOP» выдано чтение «CRM» на 1 день
|
||||
- **AND** запрос закрыт как выданный, агент получает «доступ выдан: чтение на 1 день»
|
||||
- **AND** агент читает `GET /items`, а через 25 часов получает отказ «срок доступа истёк»
|
||||
|
||||
#### Scenario: Чужой не может нажать «Дать»
|
||||
- **GIVEN** открытый запрос проекта «SHOP» владельца «anna»
|
||||
- **WHEN** пользователь «boris» нажимает «Дать: полные права» и «до отзыва»
|
||||
- **THEN** он получает «Запрос не найден»
|
||||
- **AND** разрешение не выдано, запрос остаётся открытым
|
||||
|
||||
#### Scenario: Подключения ещё нет
|
||||
- **GIVEN** открытый запрос «SHOP» к «stripe», у «anna» нет подключения Stripe
|
||||
- **WHEN** приходит сообщение о запросе
|
||||
- **THEN** в нём ссылка «Подключить» и «Отказать», без «Дать»
|
||||
- **AND** нажатие «Дать: чтение» в старом сообщении отвечает «Подключения ещё нет — откройте запрос и подключите сервис»
|
||||
|
||||
#### Scenario: Срок на карточке запроса
|
||||
- **GIVEN** открытый запрос «SHOP» к «stripe» без подключения
|
||||
- **WHEN** «anna» вставляет ключ, выбирает «полные права» и «7 дней» и нажимает «Подключить и разрешить»
|
||||
- **THEN** проекту выдано чтение и запись «Stripe» на 7 дней
|
||||
|
||||
### Requirement: Истёкший доступ — новый запрос
|
||||
Отказ шлюза из-за истёкшего срока или снятого без дела разрешения SHALL подсказывать агенту попросить доступ снова через `request_access` с названием сервиса.
|
||||
|
||||
#### Scenario: Отказ после истечения
|
||||
- **GIVEN** разрешение «CRM» на 1 час выдано 2 часа назад
|
||||
- **WHEN** агент вызывает «crm»
|
||||
- **THEN** отказ «срок доступа истёк» и подсказка `request_access`
|
||||
@ -0,0 +1,11 @@
|
||||
## 1. Ядро
|
||||
- [x] 1.1 `rights`/`term` в выдаче по запросу (`grantFor`, `grantAccessFromExisting`, `connectAndGrantAccess`), `grantAccessByButton`, кнопки в `announceAccessRequest` и `accessRequestKeyboard`
|
||||
- [x] 1.2 Текст агенту о решении — со сроком; подсказка `request_access` при `expired`/`idle_revoked`
|
||||
|
||||
## 2. Каналы
|
||||
- [x] 2.1 Бот: `ar:<id>:r|f`, `ar:<id>:r|f:<срок>`, `ar:<id>:back`
|
||||
- [x] 2.2 Веб: кнопки в «Агенты просят доступ», права и срок на карточке запроса; переводы en/kk
|
||||
|
||||
## 3. Проверка
|
||||
- [x] 3.1 Тест `access-request-buttons.test.ts` (Telegram: чтение на 1 день → вызов → истёк; чужой; нет подключения; веб-карточка)
|
||||
- [x] 3.2 lint, typecheck, затронутые тесты
|
||||
@ -313,6 +313,7 @@ SHALL отправить владельцу одно сообщение.
|
||||
- **WHEN** агент «SHOP» делает запись через «stripe»
|
||||
- **THEN** вызов отклонён
|
||||
- **AND** создан запрос доступа «SHOP» к «stripe» на запись, агенту сказано, что доступ запрошен
|
||||
|
||||
### Requirement: Базы данных, серверы, хранилища и почта через FORGE
|
||||
Пользователь SHALL подключать базу данных PostgreSQL или MySQL, сервер по SSH, хранилище S3 и почтовый ящик: адрес, пользователь и пароль (или ключ). Агент SHALL работать с ними только операциями FORGE и никогда не получать пароль или ключ. Каждая операция SHALL быть чтением или записью и разрешаться режимами владельца («сразу», «спрашивать меня», «нет»).
|
||||
|
||||
@ -577,3 +578,38 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
|
||||
- **GIVEN** сервис отзыва недоступен
|
||||
- **WHEN** владелец отзывает подключение
|
||||
- **THEN** подключение в FORGE отозвано и токены стёрты
|
||||
|
||||
### Requirement: Кнопки выдачи под запросом доступа
|
||||
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, прежнее разрешение проекта SHALL только расширяться по правам. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
|
||||
|
||||
#### Scenario: Чтение на 1 день кнопкой в Telegram
|
||||
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
|
||||
- **WHEN** «anna» нажимает «Дать: чтение», затем «1 день»
|
||||
- **THEN** проекту «SHOP» выдано чтение «CRM» на 1 день
|
||||
- **AND** запрос закрыт как выданный, агент получает «доступ выдан: чтение на 1 день»
|
||||
- **AND** агент читает `GET /items`, а через 25 часов получает отказ «срок доступа истёк»
|
||||
|
||||
#### Scenario: Чужой не может нажать «Дать»
|
||||
- **GIVEN** открытый запрос проекта «SHOP» владельца «anna»
|
||||
- **WHEN** пользователь «boris» нажимает «Дать: полные права» и «до отзыва»
|
||||
- **THEN** он получает «Запрос не найден»
|
||||
- **AND** разрешение не выдано, запрос остаётся открытым
|
||||
|
||||
#### Scenario: Подключения ещё нет
|
||||
- **GIVEN** открытый запрос «SHOP» к «stripe», у «anna» нет подключения Stripe
|
||||
- **WHEN** приходит сообщение о запросе
|
||||
- **THEN** в нём ссылка «Подключить» и «Отказать», без «Дать»
|
||||
- **AND** нажатие «Дать: чтение» в старом сообщении отвечает «Подключения ещё нет — откройте запрос и подключите сервис»
|
||||
|
||||
#### Scenario: Срок на карточке запроса
|
||||
- **GIVEN** открытый запрос «SHOP» к «stripe» без подключения
|
||||
- **WHEN** «anna» вставляет ключ, выбирает «полные права» и «7 дней» и нажимает «Подключить и разрешить»
|
||||
- **THEN** проекту выдано чтение и запись «Stripe» на 7 дней
|
||||
|
||||
### Requirement: Истёкший доступ — новый запрос
|
||||
Отказ шлюза из-за истёкшего срока или снятого без дела разрешения SHALL подсказывать агенту попросить доступ снова через `request_access` с названием сервиса.
|
||||
|
||||
#### Scenario: Отказ после истечения
|
||||
- **GIVEN** разрешение «CRM» на 1 час выдано 2 часа назад
|
||||
- **WHEN** агент вызывает «crm»
|
||||
- **THEN** отказ «срок доступа истёк» и подсказка `request_access`
|
||||
|
||||
@ -10,7 +10,7 @@ import { lookup as dnsLookup } from "node:dns/promises";
|
||||
import { logEvent } from "./audit.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
|
||||
import { agentConnections, createConnection, grantConnection, isBlockedAddress, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode } from "./connections.ts";
|
||||
import { agentConnections, createConnection, DEFAULT_GRANT_TERM, GRANT_RIGHTS, GRANT_TERM_TEXT, GRANT_TERMS, grantConnection, isBlockedAddress, isGrantTerm, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode, type GrantRights, type GrantTerm } from "./connections.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { deliverToUser } from "./notifications.ts";
|
||||
import { guardUntrusted } from "./untrusted.ts";
|
||||
@ -46,6 +46,9 @@ export interface AccessRequestView {
|
||||
decidedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
/** PEP-261: what was given, right after a grant (not stored on the request; the event has it). */
|
||||
rights?: GrantRights;
|
||||
term?: GrantTerm;
|
||||
}
|
||||
|
||||
export type HostLookup = (host: string) => Promise<string[]>;
|
||||
@ -230,23 +233,71 @@ export async function requestAccess(db: Db, i: AccessRequestInput, o: { lookup?:
|
||||
|
||||
export const accessRequestUrl = (id: number) => `/connections/requests/${id}`;
|
||||
|
||||
/** The text of the owner's message (master chat, Telegram, push). */
|
||||
export function accessRequestText(r: AccessRequestView): string {
|
||||
/** The text of the owner's message (master chat, Telegram, push). `canGrant` — the owner already has a fitting connection (PEP-261 buttons). */
|
||||
export function accessRequestText(r: AccessRequestView, o: { canGrant?: boolean } = {}): string {
|
||||
const who = r.agentName ? tr("Агент {name}", { name: asIs(r.agentName) }) : tr("Агент");
|
||||
const where = r.taskKey ? tr("{project}, задача {task}", { project: asIs(r.projectName), task: r.taskKey }) : asIs(r.projectName);
|
||||
const what = r.mode === "write" ? tr("{service} — читать и менять", { service: asIs(r.service) }) : tr("{service} — только читать", { service: asIs(r.service) });
|
||||
return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
||||
return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), o.canGrant ? tr("Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.") : tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
||||
}
|
||||
|
||||
type InlineButton = { text: string; url?: string; callback_data?: string };
|
||||
|
||||
/** PEP-261: the step of the Telegram keyboard under an access request. */
|
||||
export type AccessKeyboardStep = { step: "rights"; canGrant: boolean } | { step: "term"; rights: GrantRights };
|
||||
|
||||
/**
|
||||
* Buttons under the owner's message: «Дать: чтение» · «Дать: полные права» (only with a fitting
|
||||
* connection, otherwise «Подключить» — the request's card with the catalog's steps) · «Отказать»;
|
||||
* after rights — the term (1 day first, the default) and «Назад».
|
||||
* Callback data: `ar:<id>:r|f`, `ar:<id>:r|f:<term>`, `ar:<id>:back`, `ar:<id>:no`.
|
||||
*/
|
||||
export function accessRequestKeyboard(id: number, k: AccessKeyboardStep, o: { webUrl?: string } = {}): InlineButton[][] {
|
||||
const base = (o.webUrl ?? process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
||||
const link = base.startsWith("https://") ? `${base}${accessRequestUrl(id)}` : null;
|
||||
if (k.step === "term") {
|
||||
const code = k.rights === "full" ? "f" : "r";
|
||||
const terms = [DEFAULT_GRANT_TERM, ...GRANT_TERMS.filter((t) => t !== DEFAULT_GRANT_TERM)];
|
||||
const label = k.rights === "full" ? tr("Полные права — на какой срок?") : tr("Чтение — на какой срок?");
|
||||
return [
|
||||
[{ text: label, callback_data: `ar:${id}:${code}:${DEFAULT_GRANT_TERM}` }],
|
||||
terms.map((t) => ({ text: GRANT_TERM_TEXT[t], callback_data: `ar:${id}:${code}:${t}` })),
|
||||
[{ text: tr("Назад"), callback_data: `ar:${id}:back` }],
|
||||
];
|
||||
}
|
||||
return [
|
||||
...(k.canGrant
|
||||
? [[{ text: tr("Дать: чтение"), callback_data: `ar:${id}:r` }, { text: tr("Дать: полные права"), callback_data: `ar:${id}:f` }]]
|
||||
: link
|
||||
? [[{ text: tr("Подключить"), url: link }]]
|
||||
: []),
|
||||
[{ text: tr("Отказать"), callback_data: `ar:${id}:no` }],
|
||||
...(k.canGrant && link ? [[{ text: tr("Посмотреть и решить"), url: link }]] : []),
|
||||
];
|
||||
}
|
||||
|
||||
export type AccessCallback = { id: number } & ({ action: "no" } | { action: "back" } | { action: "rights"; rights: GrantRights } | { action: "grant"; rights: GrantRights; term: GrantTerm });
|
||||
|
||||
/** `ar:…` → what was pressed; null — not ours or malformed. */
|
||||
export function parseAccessCallback(data: string): AccessCallback | null {
|
||||
const m = /^ar:(\d+):(no|back|r|f)(?::([a-z0-9]+))?$/.exec(String(data ?? ""));
|
||||
if (!m) return null;
|
||||
const id = Number(m[1]);
|
||||
if (m[2] === "no" || m[2] === "back") return m[3] ? null : { id, action: m[2] };
|
||||
const rights: GrantRights = m[2] === "f" ? "full" : "read";
|
||||
if (!m[3]) return { id, action: "rights", rights };
|
||||
return isGrantTerm(m[3]) ? { id, action: "grant", rights, term: m[3] } : null;
|
||||
}
|
||||
|
||||
/** One message to the project's owner. Night quiet and the project's pause apply (outbox, deliverToUser). */
|
||||
export async function announceAccessRequest(db: Db, r: AccessRequestView): Promise<void> {
|
||||
const text = accessRequestText(r);
|
||||
const canGrant = (await connectionsForRequest(db, r.ownerId, r).catch(() => ({ fit: [] }))).fit.length > 0;
|
||||
const text = accessRequestText(r, { canGrant });
|
||||
const url = accessRequestUrl(r.id);
|
||||
await addMasterMessage(db, r.ownerId, { kind: "event", important: true, text, dedupeKey: `master:access-request:${r.id}`, url }).catch(() => null);
|
||||
const [u] = await db.select().from(users).where(eq(users.id, r.ownerId));
|
||||
if (!u) return;
|
||||
const base = (process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
||||
const buttons = [...(base.startsWith("https://") ? [[{ text: tr("Посмотреть и решить"), url: `${base}${url}` }]] : []), [{ text: tr("Отказать"), callback_data: `ar:${r.id}:no` }]];
|
||||
const buttons = accessRequestKeyboard(r.id, { step: "rights", canGrant });
|
||||
await deliverToUser(db, u, {
|
||||
event: "questions",
|
||||
projectId: r.projectId,
|
||||
@ -313,35 +364,62 @@ export async function connectionsForRequest(db: Db, userId: number, r: AccessReq
|
||||
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
||||
const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
|
||||
|
||||
/** Grant to the request's project (any of its agents): read at once, write at once only if asked. An existing grant only widens. */
|
||||
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<void> {
|
||||
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((g) => g.agentId == null);
|
||||
/** PEP-261: what the owner gives — rights (default: what the agent asked for) and a term (default 1 day). */
|
||||
export interface AccessGrantChoice {
|
||||
rights?: GrantRights;
|
||||
term?: GrantTerm;
|
||||
}
|
||||
type Given = { rights: GrantRights; term: GrantTerm };
|
||||
const given = (r: AccessRequestView, c: AccessGrantChoice = {}): Given => ({ rights: c.rights === "full" || c.rights === "read" ? c.rights : r.mode === "write" ? "full" : "read", term: isGrantTerm(c.term) ? c.term : DEFAULT_GRANT_TERM });
|
||||
|
||||
/** Grant to the request's project (any of its agents) on the chosen term. An existing grant only widens its modes. */
|
||||
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<void> {
|
||||
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
|
||||
await grantConnection(db, userId, connectionId, {
|
||||
projectId: r.projectId,
|
||||
agentId: null,
|
||||
operations: prev?.operations ?? [],
|
||||
readMode: widest(prev?.readMode ?? "off", "auto"),
|
||||
writeMode: widest(prev?.writeMode ?? "off", r.mode === "write" ? "auto" : "off"),
|
||||
readMode: widest(prev?.readMode ?? "off", GRANT_RIGHTS[g.rights].readMode),
|
||||
writeMode: widest(prev?.writeMode ?? "off", GRANT_RIGHTS[g.rights].writeMode),
|
||||
term: g.term,
|
||||
});
|
||||
}
|
||||
|
||||
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<AccessRequestView> {
|
||||
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<AccessRequestView> {
|
||||
const now = new Date();
|
||||
await db.update(accessRequests).set({ status: "granted", connectionId, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, r.id));
|
||||
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId } });
|
||||
return (await getAccessRequest(db, r.id))!;
|
||||
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId, rights: g.rights, term: g.term } });
|
||||
return { ...(await getAccessRequest(db, r.id))!, ...g };
|
||||
}
|
||||
|
||||
/** «Разрешить из уже подключённого». */
|
||||
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise<AccessRequestView> {
|
||||
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
||||
const r = await ownOpen(db, userId, id);
|
||||
await grantFor(db, userId, r, connectionId); // grantConnection checks that the connection is the user's and active
|
||||
return closeGranted(db, userId, r, connectionId);
|
||||
const g = given(r, choice);
|
||||
await grantFor(db, userId, r, connectionId, g); // grantConnection checks that the connection is the user's and active
|
||||
return closeGranted(db, userId, r, connectionId, g);
|
||||
}
|
||||
|
||||
export const NO_CONNECTION_TEXT = tr("Подключения ещё нет — откройте запрос и подключите сервис");
|
||||
|
||||
/** PEP-261: the owner's open request and the connection a button would give (the first fitting one). */
|
||||
export async function accessButtonTarget(db: Db, userId: number, id: number): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||||
const r = await ownOpen(db, userId, id);
|
||||
const [connection] = (await connectionsForRequest(db, userId, r)).fit;
|
||||
if (!connection) throw new PeppaError(NO_CONNECTION_TEXT);
|
||||
return { request: r, connection };
|
||||
}
|
||||
|
||||
/** PEP-261 «Дать: чтение / полные права» + term — under the message (Telegram) or in «Агенты просят доступ». */
|
||||
export async function grantAccessByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||||
const { connection } = await accessButtonTarget(db, userId, id);
|
||||
return { request: await grantAccessFromExisting(db, userId, id, connection.id, choice), connection };
|
||||
}
|
||||
|
||||
/** «Подключить и разрешить»: the key is entered once — a new connection by the catalog card (or the requested address) and the grant. */
|
||||
export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||||
export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }, choice: AccessGrantChoice = {}): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||||
const r = await ownOpen(db, userId, id);
|
||||
const g = given(r, choice);
|
||||
const card = catalogService(r.catalogId);
|
||||
const input: ConnectionInput = card
|
||||
? { name: i.name, secret: i.secret, catalogId: card.id, baseUrl: card.baseEditable ? i.baseUrl : undefined }
|
||||
@ -352,8 +430,8 @@ export async function connectAndGrantAccess(db: Db, userId: number, id: number,
|
||||
let name = base;
|
||||
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
|
||||
const connection = await createConnection(db, userId, { ...input, name });
|
||||
await grantFor(db, userId, r, connection.id);
|
||||
return { request: await closeGranted(db, userId, r, connection.id), connection };
|
||||
await grantFor(db, userId, r, connection.id, g);
|
||||
return { request: await closeGranted(db, userId, r, connection.id, g), connection };
|
||||
}
|
||||
|
||||
/** «Отказать»: the reason (optional) reaches the agent. */
|
||||
|
||||
@ -498,7 +498,11 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
|
||||
if (!r.ok) {
|
||||
// PEP-259: a term that ran out / a grant revoked for no use — the owner extends it with one click.
|
||||
const again = r.reason === "expired" || r.reason === "idle_revoked" ? `. Access to «${String(connection)}» ended — ask the owner to extend it (one click in «Подключения»; tell them through ask_pm which service and what for), or continue without it.` : "";
|
||||
// PEP-261: ask again through request_access — the owner answers with buttons (rights and term).
|
||||
const ended = r.reason === "expired" || r.reason === "idle_revoked";
|
||||
const svc = ended && sessionId ? await refusedCallService(db, sessionId, connection, method, path).catch(() => null) : null;
|
||||
const ask = svc?.catalogId ? `service: "${svc.catalogId}"` : svc?.baseUrl ? `host: "${svc.baseUrl}"` : `service: "${String(connection)}"`;
|
||||
const again = ended ? `. Access to «${String(connection)}» ended — if you still need it, call request_access(${ask}, purpose: "<what for, in plain words>", mode: ${svc?.kind ?? "read"}); the owner gives it again with one button. Otherwise continue without it.` : "";
|
||||
const refused = `Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}${again}`;
|
||||
// PEP-250: no grant for this service → the refusal becomes an access request by itself.
|
||||
const asked = await autoRequest(r, String(connection), method, path).catch(() => null);
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
// to a question: the live agent of the story gets a message; with nobody alive a story still in
|
||||
// work goes back to work with that message. A project on pause wakes nobody (the decision is in
|
||||
// list_requests). Owner checks are in core (accessRequestForUser).
|
||||
import { connectAndGrantAccess, denyAccessRequest, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessRequestView, type ConnectionInput } from "@peppa/core";
|
||||
import { connectAndGrantAccess, denyAccessRequest, grantAccessByButton, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessGrantChoice, type AccessRequestView, type ConnectionInput, type GrantTerm } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
import { moveTask } from "./flow.ts";
|
||||
import { resolveTaskById, sendToSession } from "./sessions.ts";
|
||||
@ -10,13 +10,17 @@ import { resolveTaskById, sendToSession } from "./sessions.ts";
|
||||
/** A story in these states gets a new agent with the decision; review/done/backlog are left alone. */
|
||||
const WAKE = ["proposing", "in_progress", "blocked"];
|
||||
|
||||
// i18n-ignore: text for the agent
|
||||
const TERM_FOR_AGENT: Record<GrantTerm, string> = { "1h": "на 1 час", "1d": "на 1 день", "7d": "на 7 дней", forever: "до отзыва" };
|
||||
|
||||
export type AccessDelivery = "agent" | "restarted" | "none";
|
||||
|
||||
/** Text for the agent (agents read English/Russian prompts — not translated). */
|
||||
export function accessDecisionText(r: AccessRequestView, slug?: string | null): string {
|
||||
if (r.status === "granted") {
|
||||
const what = r.mode === "write" ? "чтение и запись" : "чтение";
|
||||
return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}. Посмотри list_connections и вызывай call_connection${slug ? `("${slug}", …)` : ""}; ключ подставит FORGE. Продолжай задачу.`;
|
||||
const what = (r.rights ?? (r.mode === "write" ? "full" : "read")) === "full" ? "чтение и запись" : "чтение";
|
||||
const term = r.term ? ` ${TERM_FOR_AGENT[r.term]}` : "";
|
||||
return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}${term}. Посмотри list_connections и вызывай call_connection${slug ? `("${slug}", …)` : ""}; ключ подставит FORGE. Продолжай задачу.`;
|
||||
}
|
||||
return `Владелец отказал в доступе к ${r.service} (запрос #${r.id}).${r.reason ? ` Причина: ${r.reason}` : " Причину не указал."} Продолжай без этого сервиса (мок, другой путь) и не проси этот доступ снова без новой причины.`;
|
||||
}
|
||||
@ -44,15 +48,15 @@ export async function tellAgentAboutAccess(db: Db, r: AccessRequestView, slug?:
|
||||
return action;
|
||||
}
|
||||
|
||||
export async function grantAccessRequestFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise<AccessRequestView> {
|
||||
const r = await grantAccessFromExisting(db, userId, id, connectionId);
|
||||
export async function grantAccessRequestFromExisting(db: Db, userId: number, id: number, connectionId: number, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
||||
const r = await grantAccessFromExisting(db, userId, id, connectionId, choice);
|
||||
const slug = (await listConnections(db, userId)).find((c) => c.id === connectionId)?.slug ?? null;
|
||||
await tellAgentAboutAccess(db, r, slug);
|
||||
return r;
|
||||
}
|
||||
|
||||
export async function connectAndGrantAccessRequest(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }) {
|
||||
const out = await connectAndGrantAccess(db, userId, id, i);
|
||||
export async function connectAndGrantAccessRequest(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }, choice: AccessGrantChoice = {}) {
|
||||
const out = await connectAndGrantAccess(db, userId, id, i, choice);
|
||||
await tellAgentAboutAccess(db, out.request, out.connection.slug);
|
||||
return out;
|
||||
}
|
||||
@ -62,3 +66,10 @@ export async function denyAccessRequestAndTell(db: Db, userId: number, id: numbe
|
||||
await tellAgentAboutAccess(db, r);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** PEP-261: «Дать: чтение / полные права» + term by a button (Telegram, «Агенты просят доступ»). */
|
||||
export async function grantAccessRequestByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<AccessRequestView> {
|
||||
const { request, connection } = await grantAccessByButton(db, userId, id, choice);
|
||||
await tellAgentAboutAccess(db, request, connection.slug);
|
||||
return request;
|
||||
}
|
||||
|
||||
@ -183,8 +183,6 @@ export const accessHub: Record<string, string> = {
|
||||
"Зачем": "What for",
|
||||
"Причина отказа": "Reason for refusal",
|
||||
"без причины": "no reason",
|
||||
"Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will be able to read and change data in this service. You can change or revoke the access in «Connections».",
|
||||
"Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will only be able to read data in this service. You can change or revoke the access in «Connections».",
|
||||
"Или разрешить из уже подключённого": "Or allow from what's already connected",
|
||||
"Причина — агент её получит, например «используйте тестовые данные»": "Reason — the agent will get it, e.g. «use test data»",
|
||||
"читать и менять": "read and change",
|
||||
@ -369,4 +367,18 @@ export const accessHub: Record<string, string> = {
|
||||
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "The ID goes to `PEPPA_OAUTH_GITHUB_CLIENT_ID`, the new secret to `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}",
|
||||
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Delete the old secret in GitHub; tokens already given to users keep working.",
|
||||
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Mark it: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
||||
// PEP-261: «Дать» buttons under an agent's access request
|
||||
"на срок": "for",
|
||||
"Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».": "The project's agents get the chosen access for the chosen term. You can change, extend or revoke it in «Connections».",
|
||||
"Полные права: чтение и изменения": "Full rights: read and change",
|
||||
"Дать: чтение": "Give: read",
|
||||
"Дать: полные права": "Give: full rights",
|
||||
"Выберите, что дать агенту": "Choose what to give the agent",
|
||||
"Выберите срок": "Choose the term",
|
||||
"полные права": "full rights",
|
||||
"Готово: {what}, {term}. Агент узнает об этом.": "Done: {what}, {term}. The agent will be told.",
|
||||
"Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.": "Choose what to give the agent and for how long (usually 1 day), or refuse.",
|
||||
"Полные права — на какой срок?": "Full rights — for how long?",
|
||||
"Чтение — на какой срок?": "Read — for how long?",
|
||||
"Подключения ещё нет — откройте запрос и подключите сервис": "No connection yet — open the request and connect the service",
|
||||
};
|
||||
|
||||
@ -183,8 +183,6 @@ export const accessHub: Record<string, string> = {
|
||||
"Зачем": "Не үшін",
|
||||
"Причина отказа": "Бас тарту себебі",
|
||||
"без причины": "себепсіз",
|
||||
"Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді оқып, өзгерте алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
|
||||
"Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді тек оқи алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
|
||||
"Или разрешить из уже подключённого": "Немесе бұрыннан қосылғаннан рұқсат беру",
|
||||
"Причина — агент её получит, например «используйте тестовые данные»": "Себеп — агент оны алады, мысалы «сынақ деректерін пайдаланыңыз»",
|
||||
"читать и менять": "оқу және өзгерту",
|
||||
@ -369,4 +367,18 @@ export const accessHub: Record<string, string> = {
|
||||
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "Идентификатор — `PEPPA_OAUTH_GITHUB_CLIENT_ID`-ге, жаңа құпия — `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`-ке, {restart}",
|
||||
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Ескі құпияны GitHub-та өшіріңіз; пайдаланушыларға берілген токендер жұмыс істей береді.",
|
||||
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Белгілеу: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
||||
// PEP-261: «Дать» buttons under an agent's access request
|
||||
"на срок": "мерзімге",
|
||||
"Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері таңдалған қолжетімділікті таңдалған мерзімге алады. Оны «Қосылымдар» бөлімінде өзгертуге, ұзартуға немесе қайтарып алуға болады.",
|
||||
"Полные права: чтение и изменения": "Толық құқық: оқу және өзгерту",
|
||||
"Дать: чтение": "Беру: оқу",
|
||||
"Дать: полные права": "Беру: толық құқық",
|
||||
"Выберите, что дать агенту": "Агентке не беретініңізді таңдаңыз",
|
||||
"Выберите срок": "Мерзімді таңдаңыз",
|
||||
"полные права": "толық құқық",
|
||||
"Готово: {what}, {term}. Агент узнает об этом.": "Дайын: {what}, {term}. Агент бұл туралы біледі.",
|
||||
"Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.": "Агентке не және қанша мерзімге беретініңізді таңдаңыз (әдетте 1 күн) немесе бас тартыңыз.",
|
||||
"Полные права — на какой срок?": "Толық құқық — қанша мерзімге?",
|
||||
"Чтение — на какой срок?": "Оқу — қанша мерзімге?",
|
||||
"Подключения ещё нет — откройте запрос и подключите сервис": "Қосылым әлі жоқ — сұрауды ашып, сервисті қосыңыз",
|
||||
};
|
||||
|
||||
@ -93,7 +93,7 @@ describe("Срок разрешения", () => {
|
||||
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
||||
assert.ok(r.isError);
|
||||
assert.match(text, /\(expired\)/);
|
||||
assert.match(text, /extend/);
|
||||
assert.match(text, /request_access/);
|
||||
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");
|
||||
});
|
||||
|
||||
187
packages/testkit/test/access-request-buttons.test.ts
Normal file
187
packages/testkit/test/access-request-buttons.test.ts
Normal file
@ -0,0 +1,187 @@
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user