Merge pull request 'PEP-259: срок у разрешения Access Hub и автоснятие после 72 ч без дела' (#245) from task/pep-259 into main
This commit is contained in:
commit
d81a767d2b
@ -17,8 +17,8 @@
|
||||
- localizeText выбирает вариант по числу НЕпереведённых русских букв, не по кириллице: казахский тоже кириллица.
|
||||
- mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`.
|
||||
- git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент.
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (база — после `peppa db migrate`); N+1 — `workLineIndex`. Правишь live.ts — перезапусти server.ts. Не `pkill -f next-server`.
|
||||
- Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
|
||||
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`.
|
||||
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
|
||||
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
@ -28,6 +28,7 @@
|
||||
- Смержено ≠ на сайте: сверь `/api/health` commit с main.
|
||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||
- Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать.
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
- Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
|
||||
@ -65,6 +65,7 @@
|
||||
- **Чужой текст — данные (PEP-187)**: `core/untrusted.ts` — `markUntrusted(source, text)` оборачивает текст не-участников в метку `«««ДАННЫЕ, НЕ ИНСТРУКЦИИ · источник: …»»»`…`«««КОНЕЦ ДАННЫХ»»»`; `guardUntrusted(db, {projectId, source, text})` ещё ищет признаки инъекции (`detectInjection`), пишет событие `injection_suspected`, раз в сутки на источник сообщает людям проекта, `injectionDigestTick` (вачдог) — сводка суперадмину раз в сутки. Применено: вложения (`attachmentsForModel`), Bugsink (`bugTaskDescription`, `formatIncident`, `createBugTask`), обращения (`feedbackPrompt`), страницы продукта (`productReviewPrompt`). Новый канал, где текст пишут не участники, — только через них. Сеть агента: `core/egress.ts` (`egressAllowed`, адреса владельца `project.egress:<id>`, `checkAgentEgress` пишет `egress_blocked`), релей `POST /api/agent/egress`; запрет на уровне docker-сети (шлюз в образе раннера) — отдельная стори. Правило агентам — в `template/RULES.md` и `agentPrompt`. Список каналов — `openspec/specs/untrusted-text` / design change. Тест `prompt-injection.test.ts`
|
||||
- **Подключения / Access Hub (PEP-234)**: `/connections` (любой пользователь, пункт меню «Подключения»): свой внешний HTTP-сервис — название, адрес (`parseBaseUrl`: только https, без логина/`?`/`#`, не внутренний адрес), ключ доступа (`bearer` или свой заголовок). Таблицы `connections` (`secret_enc` — `encrypt`, в `encryptedColumns`), `connection_grants` (проект × агент или любой × операции `МЕТОД /префикс`), `connection_log` (миграция 0027). Всё в `core/connections.ts`: управление только владельцем (обхода для суперадмина нет), разрешение — только в проект с доступом владельца; отзыв (`revokeConnection`) стирает ключ, разрешения остаются и оживают с новым ключом. Шлюз `callConnection`: сессия → контейнер (`sessions.container`, иначе `not_isolated`; `PEPPA_CONNECTIONS_UNISOLATED=on` — тесты/стенд) → подключение среди разрешённых проекту → активно → разрешение агенту → операция (граница сегмента) → `cleanPath` → 60/мин на сессию → запрос с ключом от шлюза (`http(s).request`, `agent: false`, `lookup` проверяет IP — `isBlockedAddress`, без перенаправлений, 15 с, ответ ≤256 КБ, ключ маскируется); журнал — путь без query, решение, причина (`CONNECTION_REASON_TEXT`). Внутренние адреса и http — только `PEPPA_CONNECTIONS_ALLOW_PRIVATE=1`. MCP агента `list_connections` / `call_connection` (ответ через `guardUntrusted`). Тест `access-hub.test.ts`
|
||||
- **Access Hub: базы, серверы, хранилища, почта (PEP-251)**: `connections.protocol` (`http` | `postgres` | `mysql` | `ssh` | `s3` | `mail`) + `connections.config` (JSON без секрета; миграция 0031). `core/connection-protocols.ts` — чистое: `normalizeProtocolConfig`, `PROTOCOL_OPERATIONS` (операция = read | write → режимы PEP-249), `checkHost`/`isBlockedAddress`, `singleStatement`/`isReadQuery`, `sftpPath`, `s3Key`, `signS3` (SigV4 path-style, сверена с `@smithy/signature-v4`), `formatRows` (≤ 1000 строк, страница 100 / 64 КБ). `core/connection-drivers.ts` — `pg`/`mysql2`/`ssh2`/`imapflow`/`nodemailer` через `import()`, соединение на проверенный IP (имя — только для сертификата). `core/connection-gateway.ts` — `useConnection` (порядок как у `callConnection`: сессия в контейнере → разрешение → режим операции → аргументы → 60/мин → адрес → журнал до и после, без текста SQL/команды/файла/письма), `protocolCheck`, ключ SSH закрепляется при первом подключении (`config.hostKey`), смена — `host_key_changed` + `tellHostKeyChanged` (одно сообщение на отпечаток), `resetHostKey` («Принять новый ключ сервера»); `setGatewayDefaults` — моки для тестов/стенда. Внутренние адреса — только хосты из `settings` `connections.internal_hosts` (`setInternalHosts` — суперадмин, CLI `peppa connections internal-hosts`). MCP агента `use_connection` (`peppa.connections.use`), операции видны в `list_connections`; `call_connection` для них — `wrong_protocol`. Веб: плитки видов в каталоге «Подключений» (`?service=proto:<вид>`), запись в базу и почта по умолчанию «спрашивать меня». Драйверы — в `serverExternalPackages` и зависимостях apps/web. Моки — `packages/testkit/src/mock-access.ts`; тест `access-hub-protocols.test.ts`
|
||||
- **Срок разрешения и запрос «снять?» (PEP-259)**: `connection_grants.term` (`1h|1d|7d|forever`; без `term` ядро выдаёт «до отзыва», веб-форма — `DEFAULT_GRANT_TERM` 1 день), `expires_at`, `granted_at` (выдача/продление; миграция 0034 поставила старым время выкатки), `last_used_at` (шлюз при разрешённом вызове), `ended_at`/`end_reason` (`idle`; строка остаётся — агенту причина, владельцу «Продлить»). Шлюз решает только по живым разрешениям, иначе `expired`/`idle_revoked`. **Сам не снимает (решение PM)**: `grantExpiryTick` (вачдог) при простое ≥ `connections.idle_revoke_hours` (null — `PEPPA_CONNECTION_IDLE_HOURS`, 72; 0 — не спрашивать; проекты на паузе пропускаются) ставит запрос `settings` `connections.idle.ask:<grantId>` `{at, kept?}` и копит его в `connections.idle.digest:<userId>` → раз в сутки владельцу `tellIdleGrants` (мастер-чат, Telegram с кнопками `cg:<grantId>:r|k`, push); ответ — `decideIdleGrant` (только владелец подключения; «Снять» → `ended_at` + строка журнала `REVOKE` через `appendJournal`; «Оставить» → следующий запрос через порог; без ответа — тоже через порог), веб — «Снять»/«Оставить» в строке разрешения (`idleAskedAt`). Снятые/истёкшие старше 30 дней удаляются; `PEPPA_CONNECTION_IDLE=off`. `extendGrant` — тот же срок заново; `GRANT_RIGHTS` read/full — для кнопок «Дать» (PEP-261). Тест `access-hub-terms.test.ts`
|
||||
- **Вход в сервисы через OAuth (PEP-252)**: карточки каталога с `oauth` (Google Sheets/Drive/Calendar, GitHub; права «чтение»/«запись» в карточке) подключаются входом: `/connections/oauth/start` (POST, `startConnectionOAuth`) → сервис → `/connections/oauth/callback` (`completeConnectionOAuth`: state = cookie `peppa_conn_oauth`, поток `settings` `conn.oauth.flow:<hash>` одноразовый 10 мин, тот же пользователь). Провайдеры, клиенты (`PEPPA_OAUTH_GOOGLE_*` ← `GOOGLE_CLIENT_*`, `PEPPA_OAUTH_GITHUB_*`; без них способ скрыт — `oauthOffer`), обмен/обновление/отзыв — `core/connection-oauth.ts`; поток — `connection-oauth-flow.ts`. Подключение: `auth_kind = oauth`, токены JSON в конверте `secret_enc` (PEP-254), открыто — `oauth_provider`, `oauth_scopes`, `token_expires_at` (миграция 0031). Шлюз и проверка берут учётные данные через `connectionCredential` (обновление за минуту до срока и один раз после 401; гонка процессов — перечитать строку); сервис отказал → статус `relogin`, токены стёрты, одно сообщение (`tellReloginNeeded`), причина `needs_login`; «Войти заново» = поток с `connectionId`. `revokeConnection` отзывает и в сервисе (`remote`). Новый провайдер — запись в `OAUTH_PROVIDERS` + `oauth` в карточке. Мок `mock-oauth-service` (google|github); тест `access-hub-oauth.test.ts`
|
||||
- **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:<id>` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:<id>` и `duringPause` (что появилось во время паузы, не рассылается потом). `runner/pause.ts`: `pauseProject` (сначала отметка, потом `stopSession` живых агентов, событие `project_paused`), `resumeProject` (событие `project_resumed` «Пауза: с … по …», `activateRunnerTask` + `resumeSession` остановленных паузой). Узкие места: запуск агента — `startSession`/`startRunner`/`resumeSession`/`relaunchFresh`/`moveTask → in_progress` (отказ `PROJECT_PAUSED_TEXT`), ИИ-роли — `claudePrint`, уведомления — `deliverToUser`, `notifyPm`, `mirrorTargets`, бот `reconcile`; тики пропускают проект без потери состояния (автономность, перезапуски, напоминания, intake, уточнение, чат с аналитиком, приёмка продукта, ссылка на продукт, перезапуск из-за секретов, ревьюер, «готово к ревью», отложенное «Принять», ошибки из прода — `open` без сообщения), вебхуки (красные проверки, комментарии Gitea) записываются без запуска агента; живой агент проекта на паузе вачдог останавливает сам и дописывает в `sessions`. Веб: `components/ProjectPause.tsx` (кнопка с подтверждением, плашка, метка «На паузе»), «⋯ Настройки проекта → Пауза», «Ждут вашего ответа»/счётчики/дайджест без проектов на паузе. CLI `peppa project pause|resume <KEY>`. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts`
|
||||
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
|
||||
|
||||
@ -81,7 +81,7 @@ import {
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||
import { delayAction, resolveTaskById } from "@peppa/runner";
|
||||
import { parseDelayCallback } from "@peppa/core";
|
||||
import { decideIdleGrant, 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";
|
||||
@ -1019,6 +1019,13 @@ export function createBot(o: BotOptions) {
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
// PEP-259: the owner's answer to «агенты давно не пользуются разрешением — снять?»: `cg:<grantId>:r|k`.
|
||||
if (parts[0] === "cg") {
|
||||
const b = parseIdleGrantCallback(c.data ?? "");
|
||||
const toast = b ? await decideIdleGrant(db, user.id, b.grantId, b.decision).catch((e) => (e instanceof PeppaError ? e.message : (log(`idle grant: ${(e as Error).stack ?? e}`), tr("Ошибка")))) : tr("Неизвестная кнопка");
|
||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||
return "done";
|
||||
}
|
||||
if (parts[0] === "f") {
|
||||
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
|
||||
wakeOutbox?.();
|
||||
|
||||
@ -67,7 +67,7 @@ import {
|
||||
checkGiteaBotToken,
|
||||
setUiMode,
|
||||
} from "@peppa/core";
|
||||
import { checkConnection, createConnection, deleteConnection, grantConnection, isGatewayProtocol, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, type CatalogAuth, type ConnectionCheckResult, type GrantMode } 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 } from "@peppa/runner";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
@ -1089,7 +1089,32 @@ export async function grantConnectionAction(f: FormData) {
|
||||
await attempt(f, async () => {
|
||||
const agent = str(f, "agentId");
|
||||
const mode = (k: string): GrantMode => (["auto", "ask"].includes(str(f, k)) ? (str(f, k) as GrantMode) : "off");
|
||||
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? "") });
|
||||
await grantConnection(db, user.id, Number(str(f, "connectionId")), { projectId: Number(str(f, "projectId")), agentId: agent ? Number(agent) : null, readMode: mode("readMode"), writeMode: mode("writeMode"), operations: String(f.get("operations") ?? ""), term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM });
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259 «Продлить»: the same term again from now. */
|
||||
export async function extendGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await extendGrant(db, user.id, Number(str(f, "grantId")));
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: the owner's answer to «агенты давно не пользуются — снять?»: «Снять» / «Оставить». */
|
||||
export async function decideIdleGrantAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
await decideIdleGrant(db, user.id, Number(str(f, "grantId")), str(f, "decision") === "revoke" ? "revoke" : "keep");
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-259: «Спрашивать о разрешении без дела через …» of one connection ("" — platform default). */
|
||||
export async function setConnectionIdleAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const v = str(f, "idleHours");
|
||||
await setConnectionIdleHours(db, user.id, Number(str(f, "connectionId")), v === "" ? null : Number(v));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -7,6 +7,12 @@ import {
|
||||
CONNECTION_CHECK_TEXT,
|
||||
CONNECTION_REASON_TEXT,
|
||||
connectionJournal,
|
||||
DEFAULT_GRANT_TERM,
|
||||
defaultIdleRevokeHours,
|
||||
GRANT_TERM_TEXT,
|
||||
GRANT_TERMS,
|
||||
IDLE_HOURS_CHOICES,
|
||||
serverTimezone,
|
||||
JOURNAL_VERIFY_SCRIPT,
|
||||
grantableAgents,
|
||||
listConnections,
|
||||
@ -25,6 +31,7 @@ import {
|
||||
GATEWAY_PROTOCOLS,
|
||||
} from "@peppa/core";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { intlLocale } from "@peppa/shared/i18n";
|
||||
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -35,7 +42,7 @@ import { requireUser, uiMode } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { m, type Translator } from "@peppa/shared/i18n";
|
||||
import { checkConnectionAction, createConnectionAction, deleteConnectionAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction } from "../actions";
|
||||
import { checkConnectionAction, createConnectionAction, decideIdleGrantAction, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
@ -77,23 +84,110 @@ function modeText(m: GrantMode, t: Translator): string {
|
||||
return m === "auto" ? t("сразу") : m === "ask" ? t("спрашивать меня") : t("нет");
|
||||
}
|
||||
|
||||
/** «14:05 25.11» in the platform's time zone. */
|
||||
function when(d: Date, t: Translator): string {
|
||||
const loc = intlLocale(t.locale);
|
||||
const tz = serverTimezone();
|
||||
return `${d.toLocaleTimeString(loc, { hour: "2-digit", minute: "2-digit", timeZone: tz })} ${d.toLocaleDateString(loc, { day: "2-digit", month: "2-digit", timeZone: tz })}`;
|
||||
}
|
||||
|
||||
/** «5 ч» / «2 дн» — how soon the owner is asked about a grant without calls. */
|
||||
function hoursLeft(d: Date, t: Translator): string {
|
||||
const h = Math.max(0, Math.ceil((d.getTime() - Date.now()) / 3600_000));
|
||||
return h < 48 ? t("{n} ч", { n: h }) : t("{n} дн", { n: Math.round(h / 24) });
|
||||
}
|
||||
|
||||
function GrantLine({ g, engineer, t }: { g: ConnectionGrantView; engineer: boolean; t: Translator }) {
|
||||
const ended = g.state !== "active";
|
||||
return (
|
||||
<li className="flex flex-wrap items-center gap-2 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||
<span className="font-medium">{g.projectKey}</span>
|
||||
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
· {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })}
|
||||
</span>
|
||||
{engineer && g.operations.length > 0 && <span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>}
|
||||
<form action={revokeGrantAction} className="ml-auto">
|
||||
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||
<Button variant="ghost" size="sm">{t("Убрать")}</Button>
|
||||
</form>
|
||||
<li className="flex flex-col gap-1 rounded-md border bg-background/40 px-2.5 py-1.5">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{g.projectKey}</span>
|
||||
<span>· {g.agentName ? t("агент {name}", { name: g.agentName }) : t("любой агент проекта")}</span>
|
||||
<span className="text-muted-foreground">
|
||||
· {t("чтение: {mode}", { mode: modeText(g.readMode, t) })} · {t("запись: {mode}", { mode: modeText(g.writeMode, t) })}
|
||||
</span>
|
||||
{g.state === "expired" && <Badge variant="warn">{t("срок истёк")}</Badge>}
|
||||
{g.state === "idle" && <Badge variant="warn">{t("снято: {n} ч без дела", { n: g.idleHours })}</Badge>}
|
||||
{g.idleAskedAt && <Badge variant="warn">{t("не используется {n} ч — снять?", { n: g.idleHours })}</Badge>}
|
||||
{engineer && g.operations.length > 0 && <span className="font-mono text-xs text-muted-foreground">{g.operations.join(", ")}</span>}
|
||||
<div className="ml-auto flex gap-1">
|
||||
{g.idleAskedAt && (
|
||||
<>
|
||||
<form action={decideIdleGrantAction}>
|
||||
<Hidden fields={{ grantId: g.id, decision: "revoke", back: BACK }} />
|
||||
<Button variant="default" size="sm">{t("Снять")}</Button>
|
||||
</form>
|
||||
<form action={decideIdleGrantAction}>
|
||||
<Hidden fields={{ grantId: g.id, decision: "keep", back: BACK }} />
|
||||
<Button variant="ghost" size="sm">{t("Оставить")}</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{(ended || g.term !== "forever") && (
|
||||
<form action={extendGrantAction}>
|
||||
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||
<Button variant={ended ? "default" : "ghost"} size="sm">
|
||||
{g.term === "forever" ? t("Вернуть") : t("Продлить на {term}", { term: t.text(GRANT_TERM_TEXT[g.term]) })}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<form action={revokeGrantAction}>
|
||||
<Hidden fields={{ grantId: g.id, back: BACK }} />
|
||||
<Button variant="ghost" size="sm">{t("Убрать")}</Button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-x-3 text-xs text-muted-foreground">
|
||||
{!ended && <span>{g.expiresAt ? t("до {when}", { when: when(g.expiresAt, t) }) : t("до отзыва")}</span>}
|
||||
{g.state === "expired" && g.expiresAt && <span>{t("действовало до {when}", { when: when(g.expiresAt, t) })}</span>}
|
||||
{g.state === "idle" && g.endedAt && <span>{t("снято {ago}", { ago: ago(g.endedAt, t) })}</span>}
|
||||
<span>{g.lastUsedAt ? t("последний вызов {ago}", { ago: ago(g.lastUsedAt, t) }) : t("вызовов ещё не было")}</span>
|
||||
{g.idleAskAt && <span>{t("спросим вас о снятии через {left} без дела", { left: hoursLeft(g.idleAskAt, t) })}</span>}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function TermSelect({ t }: { t: Translator }) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
<span className="text-muted-foreground">{t("Срок")}</span>
|
||||
<select name="term" defaultValue={DEFAULT_GRANT_TERM} className={SELECT}>
|
||||
{GRANT_TERMS.map((term) => (
|
||||
<option key={term} value={term}>
|
||||
{t.text(GRANT_TERM_TEXT[term])}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function idleText(h: number, t: Translator): string {
|
||||
return h === 0 ? t("не спрашивать") : h % 24 === 0 && h >= 48 ? t("{n} дн без дела", { n: h / 24 }) : t("{n} ч без дела", { n: h });
|
||||
}
|
||||
|
||||
/** PEP-259: «Спрашивать, снять ли разрешение без дела, через …» of one connection. */
|
||||
function IdleForm({ c, t }: { c: ConnectionView; t: Translator }) {
|
||||
const def = defaultIdleRevokeHours();
|
||||
return (
|
||||
<form action={setConnectionIdleAction} className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<Hidden fields={{ connectionId: c.id, back: BACK }} />
|
||||
<span>{t("Спрашивать, снять ли разрешение, которым не пользуются:")}</span>
|
||||
<select name="idleHours" defaultValue={c.idleRevokeHours == null ? "" : String(c.idleRevokeHours)} className="h-7 rounded-md border border-input bg-background px-1.5 text-xs" aria-label={t("Спрашивать о разрешении без дела")}>
|
||||
<option value="">{t("как обычно — {text}", { text: idleText(def, t) })}</option>
|
||||
{IDLE_HOURS_CHOICES.filter((h) => h !== def).map((h) => (
|
||||
<option key={h} value={h}>
|
||||
{idleText(h, t)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button variant="ghost" size="sm">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ModeSelect({ name, label, def, t }: { name: string; label: string; def: GrantMode; t: Translator }) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1 text-sm">
|
||||
@ -136,6 +230,7 @@ function GrantForm({ c, projects, agents, engineer, t }: { c: ConnectionView; pr
|
||||
<ModeSelect name="readMode" label={t("Чтение")} def="auto" t={t} />
|
||||
{/* PEP-251: changing a database and sending letters ask the owner by default. */}
|
||||
<ModeSelect name="writeMode" label={t("Запись")} def={c.protocol === "postgres" || c.protocol === "mysql" || c.protocol === "mail" ? "ask" : "off"} t={t} />
|
||||
<TermSelect t={t} />
|
||||
</div>
|
||||
<p className="m-0 text-xs text-muted-foreground">
|
||||
{c.protocol === "http" ? t("Чтение — смотреть данные, ничего не меняя. Запись — создавать, менять, удалять и отправлять. «Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.") : t.text(PROTOCOL_TEXT[c.protocol as GatewayProtocol].modes)}
|
||||
@ -205,6 +300,7 @@ function ConnectionCard({ c, projects, agents, engineer, t }: { c: ConnectionVie
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{c.grants.length > 0 && <IdleForm c={c} t={t} />}
|
||||
{active && projects.length > 0 && <GrantForm c={c} projects={projects} agents={agents} engineer={engineer} t={t} />}
|
||||
</div>
|
||||
|
||||
@ -601,9 +697,13 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
||||
{r.projectKey ?? "—"}
|
||||
{r.agentName ? ` · ${r.agentName}` : ""}
|
||||
</td>
|
||||
<td className="py-1.5 pr-3 font-mono text-xs">
|
||||
{r.method} {r.path}
|
||||
</td>
|
||||
{r.method === "REVOKE" ? (
|
||||
<td className="py-1.5 pr-3 text-xs">{t("разрешение снято")}</td>
|
||||
) : (
|
||||
<td className="py-1.5 pr-3 font-mono text-xs">
|
||||
{r.method} {r.path}
|
||||
</td>
|
||||
)}
|
||||
<td className="py-1.5">
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
<Decision row={r} t={t} />
|
||||
|
||||
@ -0,0 +1,27 @@
|
||||
## Context
|
||||
Access Hub (PEP-234/249/254): подключения владельца, разрешения проекту/агенту (`connection_grants`), шлюз `callConnection`, журнал с цепочкой хэшей (`appendJournal`). Запросы доступа агента (PEP-250) — в ревью, не в main.
|
||||
|
||||
## Decisions
|
||||
- **Срок хранится двумя полями**: `term` (`1h|1d|7d|forever`) — чтобы «Продлить» выдавало тот же срок, и `expires_at` (null — до отзыва). Ядро без `term` выдаёт «до отзыва» (обратная совместимость: прежние вызовы и тесты); веб-форма по умолчанию — 1 день (минимум привилегий).
|
||||
- **Простой**: `granted_at` (выдача/продление) и `last_used_at` (шлюз, при разрешённом вызове). Якорь = `max(last_used_at, granted_at)`. Миграция ставит `granted_at` = время миграции всем старым строкам — отсчёт с выкатки, ничего не снимется сразу.
|
||||
- **Снятие не удаляет строку**: `ended_at` + `end_reason` (`idle`). Так шлюз отличает «нет разрешения» от «снято/истекло» и говорит агенту правильную причину, а владелец видит строку «снято: 72 ч без дела» и может продлить. Истечение — вычисляемое (`expires_at <= now`), тик его не пишет. Снятые и истёкшие строки старше 30 дней тик удаляет.
|
||||
- **Порог** — `connections.idle_revoke_hours` (null — умолчание платформы `PEPPA_CONNECTION_IDLE_HOURS`, 72; 0 — не снимать).
|
||||
- **Причины шлюза**: `expired`, `idle_revoked`. Если у агента есть живое разрешение — решает оно; иначе, если подходящее разрешение было, но истекло/снято — эта причина, иначе `no_grant`.
|
||||
- **Журнал**: снятие — строка `connection_log` через `appendJournal` (метод `REVOKE`, путь `/`, `denied`, причина `idle_revoked`, проект и агент разрешения) — попадает в цепочку хэшей и в журнал на экране.
|
||||
- **Сводка владельцу**: снятые за прошедшие сутки копятся в `settings` `connections.idle.digest:<userId>`; тик раз в сутки шлёт одно сообщение (мастер-чат + `deliverToUser` событием `failures`, ночная тишина — у очередей сама). Живому агенту ничего не шлётся.
|
||||
- **Пауза проекта**: разрешения проектов на паузе (`pausedProjectIds`) по простою не снимаются.
|
||||
- **Права для будущих кнопок «Дать»**: `GRANT_RIGHTS` — `read` (чтение сразу, запись нет) и `full` (чтение сразу, запись — `auto`). Когда появится режим подключения PEP-235, `full` возьмёт его.
|
||||
- Вынесено в отдельную задачу PEP-261 (ждёт PEP-250): кнопки под запросом доступа. Telegram-кнопок без запроса нет — нечему их показывать.
|
||||
|
||||
## Risks
|
||||
- Миграция может столкнуться с параллельными задачами Access Hub (PEP-250…253) — при rebase перенумеровать.
|
||||
|
||||
## Правка после ревью PM (2026-11-24)
|
||||
|
||||
PM: «автоснятие только по запросу, запрос админу после 72 часов без дела». Разрешение больше не
|
||||
снимается само. После порога (72 ч) владелец подключения — он и есть администратор своих
|
||||
подключений; суперадмин чужих подключений не видит — получает раз в сутки запрос с кнопками
|
||||
«Снять» / «Оставить» (Telegram, мастер-чат, «Подключения»). Пока ответа нет, доступ работает;
|
||||
без ответа и после «Оставить» следующий запрос — через порог. Состояние запроса — `settings`
|
||||
`connections.idle.ask:<grantId>` (без новой миграции). Кнопки — свои `cg:<grantId>:r|k`, а не
|
||||
вопрос проекта: вопрос проекта видят все участники, а решать должен только владелец.
|
||||
@ -0,0 +1,15 @@
|
||||
## Why
|
||||
Разрешение агенту в Access Hub (`connection_grants`) сейчас вечное: выдали — живёт, пока владелец не вспомнит и не отзовёт. По образцу брокеров доступа (Sallyport) у разрешения должен быть срок, а разрешение, которым долго никто не пользуется, должно сниматься само.
|
||||
|
||||
## What Changes
|
||||
- У разрешения появляется срок: 1 час · 1 день · 7 дней · до отзыва (`connection_grants.term`, `expires_at`). Истёкшее разрешение шлюз не принимает: агенту — «доступ истёк», в журнал — `denied` с причиной `expired`.
|
||||
- Шлюз отмечает `last_used_at` разрешения при разрешённом вызове.
|
||||
- Автоснятие без дела: разрешение, которым не пользовались `idleRevokeHours` (у подключения; по умолчанию платформы 72 ч, `PEPPA_CONNECTION_IDLE_HOURS`; 0 — выкл), снимается в тике вачдога (`grantExpiryTick`). Отсчёт — от последнего вызова, иначе от выдачи. Запись в журнал подключений («снято: 72 ч без дела»), владельцу — одна сводка в сутки, если что-то снято. Проекты на паузе не считаются.
|
||||
- «Продлить» — тот же срок заново одной кнопкой; снятое и истёкшее разрешение можно продлить.
|
||||
- Веб «Подключения»: срок в форме выдачи (по умолчанию 1 день), у разрешения — «до ЧЧ:ММ ДД.ММ» / «до отзыва», последний вызов, «снимется через N ч без дела», «истекло» / «снято», кнопка «Продлить»; у подключения — «Снимать разрешение без дела через …».
|
||||
- MCP агента `list_connections` (и `peppa.connections.list()`) показывает срок и когда разрешение снимется; отказ шлюза по сроку объясняет, что делать.
|
||||
- Миграция: новые колонки, старые разрешения — «до отзыва», отсчёт простоя с момента выкатки (`granted_at` = время миграции).
|
||||
- **Не входит** (отдельная задача после PEP-250): кнопки «Дать: чтение / полные права / Отказать» и выбор срока под запросом доступа агента в вебе и Telegram — запросов доступа (PEP-250) ещё нет в основной ветке. Для них готова функция выдачи с правами и сроком (`grantConnection` с `term`, `GRANT_RIGHTS`).
|
||||
|
||||
## Impact
|
||||
- `packages/db` (схема, миграция 0032), `packages/core/src/connections.ts`, `packages/runner/src/watchdog.ts`, `packages/mcp/src/agent.ts`, веб `/connections` и действия, переводы en/kk, тесты `access-hub-terms.test.ts`.
|
||||
@ -0,0 +1,67 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Срок разрешения
|
||||
Владелец SHALL выдавать разрешение агенту на срок: 1 час, 1 день, 7 дней или до отзыва. Шлюз SHALL отклонять вызов по истёкшему разрешению с причиной `expired` и записью `denied` в журнале. Владелец SHALL продлевать разрешение на тот же срок одной кнопкой, в том числе истёкшее или снятое.
|
||||
|
||||
#### Scenario: Вызов по живому разрешению на 1 день
|
||||
- **GIVEN** владелец «anna» выдала агенту проекта «чтение» подключения «CRM» на 1 день
|
||||
- **WHEN** агент через 2 часа читает `GET /items`
|
||||
- **THEN** сервис отвечает агенту
|
||||
- **AND** у разрешения виден последний вызов
|
||||
|
||||
#### Scenario: Вызов после истечения срока
|
||||
- **GIVEN** разрешение на 1 день выдано 25 часов назад
|
||||
- **WHEN** агент читает `GET /items`
|
||||
- **THEN** вызов отклонён с причиной «доступ истёк»
|
||||
- **AND** в журнале владельца строка `denied` с причиной `expired`
|
||||
|
||||
#### Scenario: Продление истёкшего разрешения
|
||||
- **GIVEN** разрешение на 1 день истекло
|
||||
- **WHEN** владелец нажимает «Продлить»
|
||||
- **THEN** разрешение действует ещё сутки от нажатия
|
||||
- **AND** агент снова читает `GET /items`
|
||||
|
||||
#### Scenario: Чужой пользователь не продлевает
|
||||
- **GIVEN** разрешение подключения «anna»
|
||||
- **WHEN** пользователь «boris» пытается его продлить
|
||||
- **THEN** отказ «Подключение не найдено»
|
||||
|
||||
### Requirement: Автоснятие разрешения без дела
|
||||
Разрешение, которым не пользовались дольше порога подключения (по умолчанию 72 ч; 0 — не снимать), SHALL сниматься само в тике вачдога. Отсчёт SHALL идти от последнего вызова, а без вызовов — от выдачи или продления. Снятие SHALL записываться в журнал подключений; владелец SHALL получать не больше одной сводки в сутки. Разрешения проектов на паузе SHALL не сниматься по простою.
|
||||
|
||||
#### Scenario: Разрешение без вызовов 72 часа
|
||||
- **GIVEN** разрешение выдано 73 часа назад, вызовов не было
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение снято с отметкой «72 ч без дела»
|
||||
- **AND** в журнале подключений строка «снято»
|
||||
- **AND** вызов агента отклонён с причиной `idle_revoked`
|
||||
|
||||
#### Scenario: Недавний вызов продлевает жизнь
|
||||
- **GIVEN** разрешение выдано 100 часов назад, последний вызов был 10 часов назад
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся
|
||||
|
||||
#### Scenario: Порог 0 — не снимать
|
||||
- **GIVEN** у подключения «Снимать без дела» = никогда
|
||||
- **AND** разрешением не пользовались 500 часов
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся
|
||||
|
||||
#### Scenario: Проект на паузе
|
||||
- **GIVEN** проект на паузе, разрешение без вызовов 100 часов
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся
|
||||
|
||||
#### Scenario: Старые разрешения после выкатки
|
||||
- **GIVEN** разрешение выдано до выкатки
|
||||
- **WHEN** выкатка применила миграцию
|
||||
- **THEN** разрешение действует до отзыва
|
||||
- **AND** простой считается с момента выкатки
|
||||
|
||||
### Requirement: Агент видит срок разрешения
|
||||
`list_connections` SHALL показывать агенту, до какого времени действует доступ и когда он снимется без дела.
|
||||
|
||||
#### Scenario: Список подключений агента
|
||||
- **GIVEN** агенту выдано «чтение» CRM на 7 дней
|
||||
- **WHEN** агент вызывает `list_connections`
|
||||
- **THEN** в ответе есть время окончания доступа и время снятия без дела
|
||||
@ -0,0 +1,16 @@
|
||||
## 1. Данные
|
||||
- [x] 1.1 Схема: `connection_grants.term|expires_at|granted_at|last_used_at|ended_at|end_reason`, `connections.idle_revoke_hours`; миграция 0034 (старым — `granted_at` = время миграции)
|
||||
|
||||
## 2. Ядро
|
||||
- [x] 2.1 `grantConnection` с `term`, `GRANT_TERMS`, `GRANT_RIGHTS`; `extendGrant`; `setConnectionIdleHours`; вид разрешения (срок, последний вызов, когда снимется, состояние)
|
||||
- [x] 2.2 Шлюз: только живые разрешения, причины `expired` / `idle_revoked`, `last_used_at` разрешения
|
||||
- [x] 2.3 `grantExpiryTick`: снятие без дела (пауза проекта, журнал, событие), уборка старых, суточная сводка владельцу; вачдог
|
||||
- [x] 2.4 `agentConnections`: срок и когда снимется
|
||||
|
||||
## 3. Поверхности
|
||||
- [x] 3.1 MCP `list_connections` и подсказка в отказе `call_connection`
|
||||
- [x] 3.2 Веб `/connections`: срок в форме, строка разрешения, «Продлить», порог у подключения; переводы en/kk; словарь
|
||||
|
||||
## 4. Проверка
|
||||
- [x] 4.1 Тесты `access-hub-terms.test.ts` (истечение, автоснятие с `now`, продление, чужой пользователь, пауза) + регрессия access-hub*
|
||||
- [x] 4.2 Проверки (lint, typecheck, test), память, задача на кнопки «Дать» после PEP-250
|
||||
@ -345,6 +345,90 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
|
||||
- **THEN** ответ — «нет такого подключения»
|
||||
- **AND** «boris» и суперадмин не видят его в списке и не могут выдать разрешение
|
||||
|
||||
### Requirement: Срок разрешения
|
||||
Владелец SHALL выдавать разрешение агенту на срок: 1 час, 1 день, 7 дней или до отзыва. Шлюз SHALL отклонять вызов по истёкшему разрешению с причиной `expired` и записью `denied` в журнале. Владелец SHALL продлевать разрешение на тот же срок одной кнопкой, в том числе истёкшее или снятое.
|
||||
|
||||
#### Scenario: Вызов по живому разрешению на 1 день
|
||||
- **GIVEN** владелец «anna» выдала агенту проекта «чтение» подключения «CRM» на 1 день
|
||||
- **WHEN** агент через 2 часа читает `GET /items`
|
||||
- **THEN** сервис отвечает агенту
|
||||
- **AND** у разрешения виден последний вызов
|
||||
|
||||
#### Scenario: Вызов после истечения срока
|
||||
- **GIVEN** разрешение на 1 день выдано 25 часов назад
|
||||
- **WHEN** агент читает `GET /items`
|
||||
- **THEN** вызов отклонён с причиной «доступ истёк»
|
||||
- **AND** в журнале владельца строка `denied` с причиной `expired`
|
||||
|
||||
#### Scenario: Продление истёкшего разрешения
|
||||
- **GIVEN** разрешение на 1 день истекло
|
||||
- **WHEN** владелец нажимает «Продлить»
|
||||
- **THEN** разрешение действует ещё сутки от нажатия
|
||||
- **AND** агент снова читает `GET /items`
|
||||
|
||||
#### Scenario: Чужой пользователь не продлевает
|
||||
- **GIVEN** разрешение подключения «anna»
|
||||
- **WHEN** пользователь «boris» пытается его продлить
|
||||
- **THEN** отказ «Подключение не найдено»
|
||||
|
||||
### Requirement: Запрос владельцу о разрешении без дела
|
||||
Разрешение, которым не пользовались дольше порога подключения (по умолчанию 72 ч; 0 — не спрашивать), SHALL NOT сниматься само: владелец подключения SHALL получать запрос «снять?» с кнопками «Снять» и «Оставить» (в Telegram и в «Подключениях»), а снимать разрешение SHALL только его ответ. Пока владелец не ответил, доступ SHALL оставаться. Отсчёт SHALL идти от последнего вызова, а без вызовов — от выдачи или продления; после «Оставить» или без ответа следующий запрос SHALL приходить не раньше чем через порог. Владелец SHALL получать не больше одного такого сообщения в сутки. Снятие SHALL записываться в журнал подключений. Решать SHALL только владелец подключения. О разрешениях проектов на паузе SHALL NOT спрашивать.
|
||||
|
||||
#### Scenario: Разрешение без вызовов 72 часа
|
||||
- **GIVEN** разрешение выдано 73 часа назад, вызовов не было
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** владелец получает запрос «Агенты давно не пользуются разрешениями: 1. Снять их?» с кнопками «Снять» и «Оставить»
|
||||
- **AND** в «Подключениях» у разрешения отметка «не используется 72 ч — снять?»
|
||||
- **AND** разрешение действует, вызов агента проходит
|
||||
|
||||
#### Scenario: Владелец нажимает «Снять»
|
||||
- **GIVEN** владельцу пришёл запрос о разрешении без дела
|
||||
- **WHEN** он нажимает «Снять»
|
||||
- **THEN** разрешение снято с отметкой «72 ч без дела»
|
||||
- **AND** в журнале подключений строка «снято»
|
||||
- **AND** вызов агента отклонён с причиной `idle_revoked`
|
||||
|
||||
#### Scenario: Владелец нажимает «Оставить»
|
||||
- **GIVEN** владельцу пришёл запрос о разрешении без дела
|
||||
- **WHEN** он нажимает «Оставить»
|
||||
- **THEN** разрешение остаётся
|
||||
- **AND** следующий запрос о нём придёт не раньше чем через 72 часа
|
||||
|
||||
#### Scenario: Решает только владелец
|
||||
- **GIVEN** запрос о разрешении подключения «anna»
|
||||
- **WHEN** «boris» пытается его снять
|
||||
- **THEN** отказ «Разрешение не найдено», разрешение остаётся
|
||||
|
||||
#### Scenario: Недавний вызов продлевает жизнь
|
||||
- **GIVEN** разрешение выдано 100 часов назад, последний вызов был 10 часов назад
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся
|
||||
|
||||
#### Scenario: Порог 0 — не спрашивать
|
||||
- **GIVEN** у подключения «Спрашивать о разрешении без дела» = никогда
|
||||
- **AND** разрешением не пользовались 500 часов
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся, запроса нет
|
||||
|
||||
#### Scenario: Проект на паузе
|
||||
- **GIVEN** проект на паузе, разрешение без вызовов 100 часов
|
||||
- **WHEN** проходит тик вачдога
|
||||
- **THEN** разрешение остаётся, запроса нет
|
||||
|
||||
#### Scenario: Старые разрешения после выкатки
|
||||
- **GIVEN** разрешение выдано до выкатки
|
||||
- **WHEN** выкатка применила миграцию
|
||||
- **THEN** разрешение действует до отзыва
|
||||
- **AND** простой считается с момента выкатки
|
||||
|
||||
### Requirement: Агент видит срок разрешения
|
||||
`list_connections` SHALL показывать агенту, до какого времени действует доступ, и что о долго неиспользуемом доступе спросят владельца.
|
||||
|
||||
#### Scenario: Список подключений агента
|
||||
- **GIVEN** агенту выдано «чтение» CRM на 7 дней
|
||||
- **WHEN** агент вызывает `list_connections`
|
||||
- **THEN** в ответе есть время окончания доступа
|
||||
|
||||
### Requirement: Подключение входом через сервис
|
||||
Карточки Google Sheets, Google Drive, Google Calendar и GitHub SHALL предлагать подключение
|
||||
входом через сервис (OAuth 2.0 code + PKCE S256), когда у FORGE настроен клиент этого
|
||||
|
||||
@ -49,10 +49,12 @@ import {
|
||||
defaultConnectionFetch,
|
||||
findGranted,
|
||||
internalHosts,
|
||||
liveGrants,
|
||||
openConnectionSecret,
|
||||
recentCalls,
|
||||
Refused,
|
||||
sessionCtx,
|
||||
touchGrants,
|
||||
widest,
|
||||
type ConnectionCheckOptions,
|
||||
type ConnectionCheckResult,
|
||||
@ -343,8 +345,10 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
|
||||
if (conn.status !== "active" || !conn.secretEnc) return deny("revoked");
|
||||
const protocol = conn.protocol;
|
||||
if (!isGatewayProtocol(protocol)) return deny("wrong_protocol");
|
||||
const mine = found.matches.filter((g) => g.agentId == null || g.agentId === s.agentId);
|
||||
if (!mine.length) return deny("no_grant");
|
||||
// PEP-259: only live grants (term not over, not revoked for no use).
|
||||
const live = liveGrants(found.matches, s.agentId, now);
|
||||
if ("reason" in live) return deny(live.reason);
|
||||
const mine = live.mine;
|
||||
const op = PROTOCOL_OPERATIONS[protocol][operation];
|
||||
if (!op) return deny("bad_request");
|
||||
const mode = mine.reduce<GrantMode>((acc, g) => widest(acc, op.kind === "read" ? g.readMode : g.writeMode), "off");
|
||||
@ -363,6 +367,7 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
|
||||
return { ok: false, reason: "upstream_error" };
|
||||
}
|
||||
const callId = record("allowed", null);
|
||||
await touchGrants(db, mine, now);
|
||||
const started = Date.now();
|
||||
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null) => record(decision, reason, { kind: "result", parentId: callId, durationMs: Date.now() - started });
|
||||
// PEP-258: every recognisable form of the secret (base64, URL, hex, JSON, each line of an SSH key).
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
// the agent's project (and the agent, or any agent of the project). See the change
|
||||
// pep-234-access-hub (design.md — threat model).
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, connectionGrants, connectionLog, connections, projects, sessions, users, type Db } from "@peppa/db";
|
||||
import { agents, connectionGrants, connectionLog, connections, keyPrefix, projects, sessions, settings, users, type Db } from "@peppa/db";
|
||||
import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm";
|
||||
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
|
||||
import { request as httpRequest, type IncomingMessage } from "node:http";
|
||||
@ -24,6 +24,7 @@ import { deliverToUser } from "./notifications.ts";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
|
||||
import { projectForUser } from "./users.ts";
|
||||
import { pausedProjectIds } from "./project-pause.ts";
|
||||
|
||||
export { isBlockedAddress } from "./connection-protocols.ts";
|
||||
|
||||
@ -47,6 +48,8 @@ export type ConnectionReason =
|
||||
| "revoked"
|
||||
| "needs_login"
|
||||
| "no_grant"
|
||||
| "expired"
|
||||
| "idle_revoked"
|
||||
| "operation_denied"
|
||||
| "read_denied"
|
||||
| "write_denied"
|
||||
@ -77,6 +80,8 @@ export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
|
||||
revoked: tr("подключение отозвано"),
|
||||
needs_login: tr("нужно заново войти в сервис"),
|
||||
no_grant: tr("нет разрешения для проекта или агента"),
|
||||
expired: tr("срок доступа истёк"),
|
||||
idle_revoked: tr("доступ снят владельцем: им долго не пользовались"),
|
||||
operation_denied: tr("операция не разрешена"),
|
||||
read_denied: tr("чтение не разрешено"),
|
||||
write_denied: tr("запись не разрешена"),
|
||||
@ -124,6 +129,8 @@ export interface ConnectionView {
|
||||
oauthScopes: string[];
|
||||
revokedAt: Date | null;
|
||||
lastUsedAt: Date | null;
|
||||
/** PEP-259: own threshold of «revoke after N hours without calls»; null — platform default. */
|
||||
idleRevokeHours: number | null;
|
||||
createdAt: Date;
|
||||
grants: ConnectionGrantView[];
|
||||
}
|
||||
@ -139,6 +146,69 @@ export interface ConnectionGrantView {
|
||||
readMode: GrantMode;
|
||||
writeMode: GrantMode;
|
||||
createdAt: Date;
|
||||
/** PEP-259: the term chosen; «Продлить» gives the same again. */
|
||||
term: GrantTerm;
|
||||
/** null — until revoked. */
|
||||
expiresAt: Date | null;
|
||||
lastUsedAt: Date | null;
|
||||
/** When the owner is asked whether to revoke it if nobody uses it (null — never: threshold 0, or already asked). */
|
||||
idleAskAt: Date | null;
|
||||
/** The owner was asked «снять?» and has not answered (PEP-259: revoked only by the owner's answer). */
|
||||
idleAskedAt: Date | null;
|
||||
/** active; expired — the term is over; idle — revoked by the owner after a «no use» request. */
|
||||
state: GrantState;
|
||||
endedAt: Date | null;
|
||||
/** Hours of the «no use» threshold (for «не используется 72 ч» / «снято: 72 ч без дела»). */
|
||||
idleHours: number;
|
||||
}
|
||||
|
||||
/** PEP-259: how long a grant lives. */
|
||||
export type GrantTerm = "1h" | "1d" | "7d" | "forever";
|
||||
export const GRANT_TERMS: GrantTerm[] = ["1h", "1d", "7d", "forever"];
|
||||
export const GRANT_TERM_MS: Record<GrantTerm, number | null> = { "1h": 3600_000, "1d": 24 * 3600_000, "7d": 7 * 24 * 3600_000, forever: null };
|
||||
export const GRANT_TERM_TEXT: Record<GrantTerm, string> = { "1h": tr("1 час"), "1d": tr("1 день"), "7d": tr("7 дней"), forever: tr("до отзыва") };
|
||||
/** Default term of a grant given by a button (web form, an agent's request). */
|
||||
export const DEFAULT_GRANT_TERM: GrantTerm = "1d";
|
||||
export type GrantState = "active" | "expired" | "idle";
|
||||
/** PEP-259: «Дать: чтение» / «Дать: полные права» (full = reading and writing at once; PEP-235 mode later). */
|
||||
export type GrantRights = "read" | "full";
|
||||
export const GRANT_RIGHTS: Record<GrantRights, { readMode: GrantMode; writeMode: GrantMode }> = { read: { readMode: "auto", writeMode: "off" }, full: { readMode: "auto", writeMode: "auto" } };
|
||||
export const isGrantTerm = (v: unknown): v is GrantTerm => GRANT_TERMS.includes(v as GrantTerm);
|
||||
|
||||
/** PEP-259: platform default of «ask the owner to revoke a grant after N hours without calls» (0 — never). */
|
||||
export function defaultIdleRevokeHours(env: NodeJS.ProcessEnv = process.env): number {
|
||||
const n = Number(env.PEPPA_CONNECTION_IDLE_HOURS);
|
||||
return env.PEPPA_CONNECTION_IDLE_HOURS != null && env.PEPPA_CONNECTION_IDLE_HOURS !== "" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 72;
|
||||
}
|
||||
export const IDLE_HOURS_CHOICES = [24, 72, 168, 0] as const;
|
||||
const idleHoursOf = (c: { idleRevokeHours: number | null }) => c.idleRevokeHours ?? defaultIdleRevokeHours();
|
||||
|
||||
type GrantRow = typeof connectionGrants.$inferSelect;
|
||||
/** The countdown of «no use» starts at the last call, otherwise at the grant (or the deploy that added the column). */
|
||||
const idleAnchor = (g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">) => Math.max(g.lastUsedAt?.getTime() ?? 0, (g.grantedAt ?? g.createdAt).getTime());
|
||||
export function grantState(g: Pick<GrantRow, "endedAt" | "expiresAt">, now: Date): GrantState {
|
||||
if (g.endedAt) return "idle";
|
||||
if (g.expiresAt && g.expiresAt.getTime() <= now.getTime()) return "expired";
|
||||
return "active";
|
||||
}
|
||||
function idleAskAt(g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">, hours: number, ask?: IdleAsk | null): Date | null {
|
||||
if (hours <= 0) return null;
|
||||
// After «Оставить» (or an unanswered request) the next request comes a full threshold later.
|
||||
const from = Math.max(idleAnchor(g), ask?.at ?? 0);
|
||||
return new Date(from + hours * 3600_000);
|
||||
}
|
||||
/** PEP-259: the request «снять?» about one grant — `settings` `connections.idle.ask:<grantId>`. */
|
||||
interface IdleAsk {
|
||||
at: number;
|
||||
kept?: boolean;
|
||||
}
|
||||
const IDLE_ASK = "connections.idle.ask:";
|
||||
/** The request is open: asked, not answered «Оставить», and nobody used the grant since. */
|
||||
const askOpen = (g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">, ask: IdleAsk | null | undefined): ask is IdleAsk => !!ask && !ask.kept && ask.at >= idleAnchor(g);
|
||||
async function idleAsks(db: Db, grantIds: number[]): Promise<Map<number, IdleAsk>> {
|
||||
if (!grantIds.length) return new Map();
|
||||
const rows = await db.select().from(settings).where(inArray(settings.key, grantIds.map((id) => `${IDLE_ASK}${id}`)));
|
||||
return new Map(rows.map((r) => [Number(r.key.slice(IDLE_ASK.length)), r.value as IdleAsk]));
|
||||
}
|
||||
|
||||
export type GrantMode = "off" | "auto" | "ask";
|
||||
@ -480,6 +550,11 @@ export interface GrantInput {
|
||||
/** PEP-249: reading / writing by the catalog's read rule. */
|
||||
readMode?: GrantMode;
|
||||
writeMode?: GrantMode;
|
||||
/** PEP-259: how long; default — until revoked (the web form and buttons default to 1 day). */
|
||||
term?: GrantTerm;
|
||||
/** «Дать: чтение / полные права» — sets both modes. */
|
||||
rights?: GrantRights;
|
||||
now?: Date;
|
||||
}
|
||||
|
||||
const mode = (m: unknown): GrantMode => (GRANT_MODES.includes(m as GrantMode) ? (m as GrantMode) : "off");
|
||||
@ -493,22 +568,45 @@ export async function grantConnection(db: Db, userId: number, connectionId: numb
|
||||
const [a] = await db.select({ id: agents.id }).from(agents).where(eq(agents.id, agentId));
|
||||
if (!a) throw new PeppaError(tr("Агент не найден"));
|
||||
}
|
||||
const readMode = mode(g.readMode);
|
||||
const writeMode = mode(g.writeMode);
|
||||
const readMode = g.rights ? GRANT_RIGHTS[g.rights].readMode : mode(g.readMode);
|
||||
const writeMode = g.rights ? GRANT_RIGHTS[g.rights].writeMode : mode(g.writeMode);
|
||||
const term: GrantTerm = isGrantTerm(g.term) ? g.term : "forever";
|
||||
const now = g.now ?? new Date();
|
||||
const life = { term, expiresAt: GRANT_TERM_MS[term] == null ? null : new Date(now.getTime() + GRANT_TERM_MS[term]!), grantedAt: now, endedAt: null, endReason: null };
|
||||
const anyMode = readMode !== "off" || writeMode !== "off";
|
||||
const operations = normalizeOperations(g.operations ?? [], { allowEmpty: true });
|
||||
if (!anyMode && !operations.length) throw new PeppaError(tr("Разрешите чтение, запись или хотя бы одну операцию"));
|
||||
const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId);
|
||||
let id: number;
|
||||
if (existing) {
|
||||
await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId }).where(eq(connectionGrants.id, existing.id));
|
||||
await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId, ...life }).where(eq(connectionGrants.id, existing.id));
|
||||
id = existing.id;
|
||||
} else {
|
||||
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId }).returning({ id: connectionGrants.id });
|
||||
const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId, ...life }).returning({ id: connectionGrants.id });
|
||||
id = row!.id;
|
||||
}
|
||||
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode } });
|
||||
return (await grantViews(db, [c.id])).find((x) => x.id === id)!;
|
||||
await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode, term } });
|
||||
return (await grantViews(db, [c.id], now)).find((x) => x.id === id)!;
|
||||
}
|
||||
|
||||
/** PEP-259 «Продлить»: the same term again from now; brings back an expired or revoked-for-idle grant. */
|
||||
export async function extendGrant(db: Db, userId: number, grantId: number, o: { now?: Date } = {}): Promise<ConnectionGrantView> {
|
||||
const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId));
|
||||
if (!g) throw new PeppaError(tr("Разрешение не найдено"));
|
||||
const c = await ownConnection(db, userId, g.connectionId);
|
||||
if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа"));
|
||||
const now = o.now ?? new Date();
|
||||
const ms = GRANT_TERM_MS[g.term];
|
||||
await db.update(connectionGrants).set({ expiresAt: ms == null ? null : new Date(now.getTime() + ms), grantedAt: now, endedAt: null, endReason: null }).where(eq(connectionGrants.id, g.id));
|
||||
await logEvent(db, { projectId: g.projectId, type: "connection_grant_extended", payload: { connectionId: g.connectionId, agentId: g.agentId, term: g.term } });
|
||||
return (await grantViews(db, [c.id], now)).find((x) => x.id === g.id)!;
|
||||
}
|
||||
|
||||
/** PEP-259: the connection's «revoke a grant after N hours without calls»; null — platform default, 0 — never. */
|
||||
export async function setConnectionIdleHours(db: Db, userId: number, connectionId: number, hours: number | null): Promise<void> {
|
||||
const c = await ownConnection(db, userId, connectionId);
|
||||
if (hours != null && (!Number.isInteger(hours) || hours < 0 || hours > 24 * 365)) throw new PeppaError(tr("Недопустимый срок"));
|
||||
await db.update(connections).set({ idleRevokeHours: hours }).where(eq(connections.id, c.id));
|
||||
}
|
||||
|
||||
export async function revokeGrant(db: Db, userId: number, grantId: number): Promise<void> {
|
||||
@ -519,9 +617,9 @@ export async function revokeGrant(db: Db, userId: number, grantId: number): Prom
|
||||
await logEvent(db, { projectId: g.projectId, type: "connection_grant_revoked", payload: { connectionId: g.connectionId, agentId: g.agentId } });
|
||||
}
|
||||
|
||||
async function grantViews(db: Db, connectionIds: number[]): Promise<Array<ConnectionGrantView & { connectionId: number }>> {
|
||||
async function grantViews(db: Db, connectionIds: number[], now: Date = new Date()): Promise<Array<ConnectionGrantView & { connectionId: number }>> {
|
||||
if (!connectionIds.length) return [];
|
||||
return db
|
||||
const rows = await db
|
||||
.select({
|
||||
id: connectionGrants.id,
|
||||
connectionId: connectionGrants.connectionId,
|
||||
@ -534,21 +632,36 @@ async function grantViews(db: Db, connectionIds: number[]): Promise<Array<Connec
|
||||
readMode: connectionGrants.readMode,
|
||||
writeMode: connectionGrants.writeMode,
|
||||
createdAt: connectionGrants.createdAt,
|
||||
term: connectionGrants.term,
|
||||
expiresAt: connectionGrants.expiresAt,
|
||||
grantedAt: connectionGrants.grantedAt,
|
||||
lastUsedAt: connectionGrants.lastUsedAt,
|
||||
endedAt: connectionGrants.endedAt,
|
||||
idleRevokeHours: connections.idleRevokeHours,
|
||||
})
|
||||
.from(connectionGrants)
|
||||
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
|
||||
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
|
||||
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
|
||||
.where(inArray(connectionGrants.connectionId, connectionIds))
|
||||
.orderBy(asc(projects.key), asc(connectionGrants.id));
|
||||
const asks = await idleAsks(db, rows.map((r) => r.id));
|
||||
return rows.map(({ grantedAt, idleRevokeHours, ...r }) => {
|
||||
const idleHours = idleHoursOf({ idleRevokeHours });
|
||||
const state = grantState(r, now);
|
||||
const ask = asks.get(r.id);
|
||||
const open = state === "active" && askOpen({ ...r, grantedAt }, ask);
|
||||
return { ...r, state, idleHours, idleAskedAt: open ? new Date(ask!.at) : null, idleAskAt: state === "active" && !open ? idleAskAt({ ...r, grantedAt }, idleHours, ask) : null };
|
||||
});
|
||||
}
|
||||
|
||||
/** Short name for agents; connections made before PEP-249 get one from their name. */
|
||||
export const connectionSlug = (r: { id: number; name: string; slug: string | null }) => r.slug || slugify(r.name) || `c${r.id}`;
|
||||
|
||||
/** The user's own connections with grants; never the key. */
|
||||
export async function listConnections(db: Db, userId: number): Promise<ConnectionView[]> {
|
||||
export async function listConnections(db: Db, userId: number, o: { now?: Date } = {}): Promise<ConnectionView[]> {
|
||||
const rows = await db.select().from(connections).where(eq(connections.ownerId, userId)).orderBy(asc(connections.name));
|
||||
const grants = await grantViews(db, rows.map((r) => r.id));
|
||||
const grants = await grantViews(db, rows.map((r) => r.id), o.now);
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
@ -567,6 +680,7 @@ export async function listConnections(db: Db, userId: number): Promise<Connectio
|
||||
oauthScopes: r.oauthScopes ?? [],
|
||||
revokedAt: r.revokedAt,
|
||||
lastUsedAt: r.lastUsedAt,
|
||||
idleRevokeHours: r.idleRevokeHours,
|
||||
createdAt: r.createdAt,
|
||||
grants: grants.filter((g) => g.connectionId === r.id).map(({ connectionId: _, ...g }) => g),
|
||||
}));
|
||||
@ -658,6 +772,8 @@ export interface AgentConnection {
|
||||
/** PEP-251: http — call_connection; others — use_connection with these operations. */
|
||||
protocol: ConnectionProtocol;
|
||||
protocolOperations: Array<{ name: string; kind: "read" | "write"; args: string[]; help: string }>;
|
||||
/** PEP-259: the latest end among the agent's live grants; null — at least one is until revoked. */
|
||||
expiresAt: Date | null;
|
||||
}
|
||||
|
||||
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
||||
@ -665,12 +781,13 @@ const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
||||
export const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
|
||||
|
||||
/** What this session's agent may use: active connections granted to its project and agent. */
|
||||
export async function agentConnections(db: Db, sessionId: number): Promise<AgentConnection[]> {
|
||||
export async function agentConnections(db: Db, sessionId: number, o: { now?: Date } = {}): Promise<AgentConnection[]> {
|
||||
const now = o.now ?? new Date();
|
||||
const s = await sessionCtx(db, sessionId);
|
||||
// Like the gateway: an unisolated agent is refused, so it is shown nothing.
|
||||
if (!s || !agentIsolated(s)) return [];
|
||||
const rows = await db
|
||||
.select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
|
||||
.select({ c: connections, g: connectionGrants, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
|
||||
.from(connectionGrants)
|
||||
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
|
||||
.where(and(eq(connectionGrants.projectId, s.projectId), inArray(connections.status, ["active", "relogin"])))
|
||||
@ -678,10 +795,13 @@ export async function agentConnections(db: Db, sessionId: number): Promise<Agent
|
||||
const by = new Map<number, AgentConnection>();
|
||||
for (const r of rows) {
|
||||
if (r.agentId != null && r.agentId !== s.agentId) continue;
|
||||
if (grantState(r.g, now) !== "active") continue;
|
||||
const card = catalogService(r.c.catalogId);
|
||||
const proto = r.c.protocol;
|
||||
const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : [];
|
||||
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.status === "relogin" ? "bad_key" : r.c.checkStatus, protocol: proto, protocolOperations };
|
||||
const first = !by.has(r.c.id);
|
||||
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.status === "relogin" ? "bad_key" : r.c.checkStatus, protocol: proto, protocolOperations, expiresAt: null };
|
||||
c.expiresAt = first ? r.g.expiresAt : c.expiresAt && r.g.expiresAt ? (r.g.expiresAt > c.expiresAt ? r.g.expiresAt : c.expiresAt) : null;
|
||||
c.operations = [...new Set([...c.operations, ...r.operations])];
|
||||
c.readMode = widest(c.readMode, r.readMode);
|
||||
c.writeMode = widest(c.writeMode, r.writeMode);
|
||||
@ -732,12 +852,12 @@ function buildRequest(conn: typeof connections.$inferSelect, secret: string, cle
|
||||
return { url, headers };
|
||||
}
|
||||
|
||||
export type GrantedRow = { c: typeof connections.$inferSelect; agentId: number | null; operations: string[]; readMode: GrantMode; writeMode: GrantMode };
|
||||
export type GrantedRow = { c: typeof connections.$inferSelect; g: typeof connectionGrants.$inferSelect; agentId: number | null; operations: string[]; readMode: GrantMode; writeMode: GrantMode };
|
||||
|
||||
/** The connection among those granted to this session's project (never by a bare id of someone else). */
|
||||
export async function findGranted(db: Db, s: SessionCtx, connection: string | number): Promise<{ matches: GrantedRow[] } | { reason: "ambiguous_connection" | "unknown_connection" }> {
|
||||
const granted = await db
|
||||
.select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
|
||||
.select({ c: connections, g: connectionGrants, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode })
|
||||
.from(connectionGrants)
|
||||
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
|
||||
.where(eq(connectionGrants.projectId, s.projectId));
|
||||
@ -751,6 +871,23 @@ export async function findGranted(db: Db, s: SessionCtx, connection: string | nu
|
||||
return { matches };
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-259: the grants of this agent that still work. With none left, the reason: no grant at all,
|
||||
* the term is over, or it was revoked for no use.
|
||||
*/
|
||||
export function liveGrants(matches: GrantedRow[], agentId: number | null, now: Date): { mine: GrantedRow[] } | { reason: "no_grant" | "expired" | "idle_revoked" } {
|
||||
const ours = matches.filter((g) => g.agentId == null || g.agentId === agentId);
|
||||
if (!ours.length) return { reason: "no_grant" };
|
||||
const mine = ours.filter((g) => grantState(g.g, now) === "active");
|
||||
if (!mine.length) return { reason: ours.some((g) => grantState(g.g, now) === "expired") ? "expired" : "idle_revoked" };
|
||||
return { mine };
|
||||
}
|
||||
|
||||
/** The grant is in use: the idle countdown starts again. */
|
||||
export async function touchGrants(db: Db, grants: GrantedRow[], now: Date): Promise<void> {
|
||||
if (grants.length) await db.update(connectionGrants).set({ lastUsedAt: now }).where(inArray(connectionGrants.id, grants.map((g) => g.g.id)));
|
||||
}
|
||||
|
||||
/** Calls of this session in the last minute (one budget for every kind of connection). */
|
||||
export async function recentCalls(db: Db, sessionId: number, now: Date): Promise<number> {
|
||||
const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, sessionId), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }];
|
||||
@ -945,8 +1082,9 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
if (conn.status === "relogin") return deny("needs_login");
|
||||
if (conn.status !== "active" || !conn.secretEnc) return deny("revoked");
|
||||
if (conn.protocol !== "http") return deny("wrong_protocol");
|
||||
const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId);
|
||||
if (!mine.length) return deny("no_grant");
|
||||
const live = liveGrants(matches, s.agentId, now);
|
||||
if ("reason" in live) return deny(live.reason);
|
||||
const mine = live.mine;
|
||||
if (!CONNECTION_METHODS.includes(method as ConnectionMethod)) return deny("bad_request");
|
||||
const clean = cleanPath(rawPath);
|
||||
if (!clean) return deny("bad_path");
|
||||
@ -971,6 +1109,8 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
|
||||
|
||||
// Written before the service is called: a crash in the middle leaves «started, no result».
|
||||
const callId = (await record("allowed", null, null))!;
|
||||
// PEP-259: the grant is in use — the idle countdown starts again (even if the service then fails).
|
||||
await touchGrants(db, mine, now);
|
||||
const started = Date.now();
|
||||
const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) =>
|
||||
record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started });
|
||||
@ -1148,3 +1288,167 @@ export async function tellKeyStopped(db: Db, c: { id: number; ownerId: number; n
|
||||
push: { title: tr("FORGE"), body: text, url: "/connections", tag: key },
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
// ---------- PEP-259: terms and the «no use» request ----------
|
||||
|
||||
/** Revoked and expired grants stay visible (extend in one click) this long, then go. */
|
||||
export const GRANT_KEEP_ENDED_MS = 30 * 24 * 3600_000;
|
||||
const IDLE_DIGEST = "connections.idle.digest:";
|
||||
const IDLE_DIGEST_SENT = "connections.idle.sent:";
|
||||
const DIGEST_EVERY_MS = 24 * 3600_000;
|
||||
/** Buttons in one request message (Telegram keeps it readable). */
|
||||
const DIGEST_BUTTONS = 5;
|
||||
|
||||
export interface IdleDigestItem {
|
||||
grantId: number;
|
||||
connection: string;
|
||||
project: string;
|
||||
agent: string | null;
|
||||
hours: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Watchdog tick (PEP-259, PM: revoked only on request): a live grant nobody called for the
|
||||
* connection's threshold (default 72 h) is NOT revoked — its owner gets a request «снять?»
|
||||
* (one summary a day, buttons «Снять» / «Оставить» in Telegram and on «Подключения»). The
|
||||
* agent keeps working meanwhile; unanswered, the request comes again a threshold later.
|
||||
* Paused projects are skipped. Ended grants older than 30 days are deleted.
|
||||
* Returns how many grants were asked about.
|
||||
*/
|
||||
export async function grantExpiryTick(db: Db, o: { now?: Date; notify?: (db: Db, ownerId: number, items: IdleDigestItem[]) => Promise<void> } = {}): Promise<number> {
|
||||
if (process.env.PEPPA_CONNECTION_IDLE === "off") return 0;
|
||||
const now = o.now ?? new Date();
|
||||
const paused = await pausedProjectIds(db);
|
||||
const rows = await db
|
||||
.select({ g: connectionGrants, c: connections, projectKey: projects.key, agentName: agents.name })
|
||||
.from(connectionGrants)
|
||||
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
|
||||
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
|
||||
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
|
||||
.where(and(isNull(connectionGrants.endedAt), eq(connections.status, "active")));
|
||||
const asks = await idleAsks(db, rows.map((r) => r.g.id));
|
||||
let asked = 0;
|
||||
for (const r of rows) {
|
||||
if (paused.has(r.g.projectId) || grantState(r.g, now) !== "active") continue;
|
||||
const hours = idleHoursOf(r.c);
|
||||
const ask = asks.get(r.g.id);
|
||||
if (askOpen(r.g, ask) && now.getTime() - ask.at < hours * 3600_000) continue;
|
||||
const at = idleAskAt(r.g, hours, ask);
|
||||
if (!at || at.getTime() > now.getTime()) continue;
|
||||
asked++;
|
||||
await setSetting(db, `${IDLE_ASK}${r.g.id}`, { at: now.getTime() } satisfies IdleAsk);
|
||||
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_idle", payload: { connectionId: r.c.id, grantId: r.g.id, agentId: r.g.agentId, hours } });
|
||||
const key = `${IDLE_DIGEST}${r.c.ownerId}`;
|
||||
const list = ((await getSetting<IdleDigestItem[]>(db, key)) ?? []).filter((i) => i.grantId !== r.g.id);
|
||||
list.push({ grantId: r.g.id, connection: r.c.name, project: r.projectKey, agent: r.agentName, hours });
|
||||
await setSetting(db, key, list.slice(-50));
|
||||
}
|
||||
// Ended long ago — gone (the journal keeps the history).
|
||||
const old = new Date(now.getTime() - GRANT_KEEP_ENDED_MS);
|
||||
const gone = await db
|
||||
.delete(connectionGrants)
|
||||
.where(sql`(${connectionGrants.endedAt} is not null and ${connectionGrants.endedAt} < ${old.getTime()}) or (${connectionGrants.endedAt} is null and ${connectionGrants.expiresAt} is not null and ${connectionGrants.expiresAt} < ${old.getTime()})`)
|
||||
.returning({ id: connectionGrants.id });
|
||||
if (gone.length) await db.delete(settings).where(inArray(settings.key, gone.map((g) => `${IDLE_ASK}${g.id}`)));
|
||||
// One request a day per owner, only with grants still waiting for the answer.
|
||||
for (const d of await db.select().from(settings).where(keyPrefix(settings.key, IDLE_DIGEST))) {
|
||||
const ownerId = Number(d.key.slice(IDLE_DIGEST.length));
|
||||
const queued = (d.value as IdleDigestItem[] | null) ?? [];
|
||||
if (!Number.isFinite(ownerId) || !queued.length) continue;
|
||||
const sent = await getSetting<number>(db, `${IDLE_DIGEST_SENT}${ownerId}`);
|
||||
if (sent != null && now.getTime() - sent < DIGEST_EVERY_MS) continue;
|
||||
const still = await idleAsks(db, queued.map((i) => i.grantId));
|
||||
const live = await db.select().from(connectionGrants).where(inArray(connectionGrants.id, queued.map((i) => i.grantId)));
|
||||
const items = queued.filter((i) => {
|
||||
const g = live.find((x) => x.id === i.grantId);
|
||||
return g && !g.endedAt && askOpen(g, still.get(i.grantId));
|
||||
});
|
||||
await setSetting(db, d.key, []);
|
||||
if (!items.length) continue;
|
||||
await setSetting(db, `${IDLE_DIGEST_SENT}${ownerId}`, now.getTime());
|
||||
await (o.notify ?? tellIdleGrants)(db, ownerId, items);
|
||||
}
|
||||
return asked;
|
||||
}
|
||||
|
||||
/** Telegram button data of the request: `cg:<grantId>:r|k` (revoke / keep). */
|
||||
export function idleGrantCallback(grantId: number, decision: "revoke" | "keep"): string {
|
||||
return `cg:${grantId}:${decision === "revoke" ? "r" : "k"}`;
|
||||
}
|
||||
export function parseIdleGrantCallback(data: string): { grantId: number; decision: "revoke" | "keep" } | null {
|
||||
const mm = /^cg:(\d+):([rk])$/.exec(data);
|
||||
return mm ? { grantId: Number(mm[1]), decision: mm[2] === "r" ? "revoke" : "keep" } : null;
|
||||
}
|
||||
|
||||
/** The owner's request: grants nobody used — revoke? Master chat + Telegram/push (night quiet is the outbox's). */
|
||||
export async function tellIdleGrants(db: Db, ownerId: number, items: IdleDigestItem[]): Promise<void> {
|
||||
const lines = items.slice(0, 10).map((i) =>
|
||||
i.agent
|
||||
? tr("— «{name}» в {project}, агент {agent}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), agent: asIs(i.agent), hours: i.hours })
|
||||
: tr("— «{name}» в {project}: {hours} ч без дела", { name: asIs(i.connection), project: asIs(i.project), hours: i.hours }),
|
||||
);
|
||||
const more = items.length > 10 ? [tr("и ещё {n}", { n: items.length - 10 })] : [];
|
||||
const text = [tr("Агенты давно не пользуются разрешениями: {n}. Снять их? Пока вы не решили, доступ остаётся. Решить можно кнопками ниже или в разделе «Подключения».", { n: items.length }), ...lines, ...more].join("\n");
|
||||
const label = (i: IdleDigestItem) => clip(i.agent ? `${i.connection} · ${i.project} · ${i.agent}` : `${i.connection} · ${i.project}`, 40);
|
||||
const keyboard = items.slice(0, DIGEST_BUTTONS).map((i) => [
|
||||
{ text: tr("Снять: {name}", { name: asIs(label(i)) }), callback_data: idleGrantCallback(i.grantId, "revoke") },
|
||||
{ text: tr("Оставить"), callback_data: idleGrantCallback(i.grantId, "keep") },
|
||||
]);
|
||||
const key = `connection-idle:${ownerId}:${Date.now()}`;
|
||||
await addMasterMessage(db, ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}`, url: "/connections" }).catch(() => null);
|
||||
const [u] = await db.select().from(users).where(eq(users.id, ownerId));
|
||||
if (!u) return;
|
||||
await deliverToUser(db, u, {
|
||||
event: "questions",
|
||||
dedupeKey: `${key}:${u.telegramChatId}`,
|
||||
pushKey: `${key}:u${u.id}`,
|
||||
telegram: { params: { text, reply_markup: { inline_keyboard: keyboard } } },
|
||||
push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-idle" },
|
||||
}).catch(() => null);
|
||||
}
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
||||
|
||||
/**
|
||||
* The owner's answer to the «no use» request (web or Telegram button). Only the connection's
|
||||
* owner decides. «Снять» ends the grant (journal REVOKE, `idle_revoked` for the agent; «Продлить»
|
||||
* brings it back); «Оставить» keeps it and the next request comes a full threshold later.
|
||||
* Returns the toast text.
|
||||
*/
|
||||
export async function decideIdleGrant(db: Db, userId: number, grantId: number, decision: "revoke" | "keep", o: { now?: Date } = {}): Promise<string> {
|
||||
const now = o.now ?? new Date();
|
||||
const [r] = await db
|
||||
.select({ g: connectionGrants, c: connections, projectKey: projects.key, agentName: agents.name })
|
||||
.from(connectionGrants)
|
||||
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
|
||||
.innerJoin(projects, eq(projects.id, connectionGrants.projectId))
|
||||
.leftJoin(agents, eq(agents.id, connectionGrants.agentId))
|
||||
.where(eq(connectionGrants.id, grantId));
|
||||
if (!r || r.c.ownerId !== userId) throw new PeppaError(tr("Разрешение не найдено"));
|
||||
if (r.g.endedAt) return tr("Разрешение уже снято");
|
||||
if (decision === "keep") {
|
||||
await setSetting(db, `${IDLE_ASK}${grantId}`, { at: now.getTime(), kept: true } satisfies IdleAsk);
|
||||
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_kept", payload: { connectionId: r.c.id, grantId, agentId: r.g.agentId } });
|
||||
return tr("Разрешение оставлено");
|
||||
}
|
||||
const hours = idleHoursOf(r.c);
|
||||
await db.update(connectionGrants).set({ endedAt: now, endReason: "idle" }).where(and(eq(connectionGrants.id, grantId), isNull(connectionGrants.endedAt)));
|
||||
await db.delete(settings).where(eq(settings.key, `${IDLE_ASK}${grantId}`));
|
||||
await appendJournal(db, {
|
||||
ownerId: r.c.ownerId,
|
||||
kind: "call",
|
||||
connectionId: r.c.id,
|
||||
connectionName: r.c.name,
|
||||
projectId: r.g.projectId,
|
||||
projectKey: r.projectKey,
|
||||
agentId: r.g.agentId,
|
||||
agentName: r.agentName,
|
||||
method: "REVOKE",
|
||||
path: "/",
|
||||
decision: "denied",
|
||||
reason: "idle_revoked",
|
||||
statusCode: null,
|
||||
createdAt: now,
|
||||
});
|
||||
await logEvent(db, { projectId: r.g.projectId, type: "connection_grant_revoked", payload: { connectionId: r.c.id, grantId, agentId: r.g.agentId, reason: "idle", hours } });
|
||||
return tr("Разрешение снято");
|
||||
}
|
||||
|
||||
@ -3,7 +3,9 @@
|
||||
// message.refusals:<s<id>|t<id>> refusals of the format in a row (core/agent-message.ts)
|
||||
// task.result:<taskId> the agent's own words about the finished story («готово»)
|
||||
// Details of an event (progress, blocker) live in its payload.
|
||||
import { settings, type Db } from "@peppa/db";
|
||||
import { questions, settings, type Db } from "@peppa/db";
|
||||
|
||||
type Question = typeof questions.$inferSelect;
|
||||
import { inArray } from "drizzle-orm";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
|
||||
@ -16,6 +18,19 @@ export async function setMessageDetails(db: Db, questionId: number, details?: st
|
||||
else await deleteSetting(db, qKey(questionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a `questions` row together with its details in one transaction: a reader (the bot,
|
||||
* a page, a test) never sees the new message without its «Подробнее».
|
||||
*/
|
||||
export function insertQuestion(db: Db, values: typeof questions.$inferInsert, details?: string | null): Question {
|
||||
const d = (details ?? "").trim().slice(0, DETAILS_MAX);
|
||||
return db.transaction((tx) => {
|
||||
const row = tx.insert(questions).values(values).returning().get() as Question;
|
||||
if (d) tx.insert(settings).values({ key: qKey(row.id), value: d }).onConflictDoUpdate({ target: settings.key, set: { value: d, updatedAt: new Date() } }).run();
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
export async function messageDetails(db: Db, ids: number[]): Promise<Map<number, string>> {
|
||||
const uniq = [...new Set(ids)];
|
||||
if (!uniq.length) return new Map();
|
||||
|
||||
@ -7,7 +7,7 @@ import { actorColumns } from "./actor.ts";
|
||||
import type { Question, QuestionKind } from "./tasks.ts";
|
||||
import { defaultMessageType, type MessageType } from "./questions.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
import { setMessageDetails } from "./message-details.ts";
|
||||
import { insertQuestion, setMessageDetails } from "./message-details.ts";
|
||||
import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText } from "./user-text.ts";
|
||||
|
||||
@ -205,11 +205,7 @@ export async function raiseSessionQuestion(
|
||||
const original = text;
|
||||
text = messageText(kind, text);
|
||||
const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => {
|
||||
const [created] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) })
|
||||
.returning();
|
||||
return created!;
|
||||
return insertQuestion(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) }, details);
|
||||
});
|
||||
if (details !== undefined) await setMessageDetails(db, row.id, details);
|
||||
await keepQuestionDetails(db, row.id, original, text).catch(() => {});
|
||||
|
||||
@ -19,7 +19,7 @@ import { raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts";
|
||||
import { defaultMessageType, type MessageType } from "./questions.ts";
|
||||
import { renderMain, type AgentMessage } from "./agent-message.ts";
|
||||
import { setMessageDetails } from "./message-details.ts";
|
||||
import { insertQuestion, setMessageDetails } from "./message-details.ts";
|
||||
import { touchVersion } from "./task-origin.ts";
|
||||
|
||||
export type Task = typeof tasks.$inferSelect;
|
||||
@ -348,11 +348,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, details, ...q }
|
||||
q = { ...q, text: messageText(q.kind, q.text) };
|
||||
// PEP-151: the same state of the story again refreshes the earlier message instead of adding one.
|
||||
const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => {
|
||||
const [created] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) })
|
||||
.returning();
|
||||
return created!;
|
||||
return insertQuestion(db, { projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }, details);
|
||||
});
|
||||
// The status goes right after the question: an answer that comes at once (it moves the story
|
||||
// on) must not be overwritten by a late «awaiting approval».
|
||||
|
||||
8
packages/db/migrations/0034_grant_terms.sql
Normal file
8
packages/db/migrations/0034_grant_terms.sql
Normal file
@ -0,0 +1,8 @@
|
||||
ALTER TABLE `connection_grants` ADD `term` text DEFAULT 'forever' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `connection_grants` ADD `expires_at` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_grants` ADD `granted_at` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_grants` ADD `last_used_at` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_grants` ADD `ended_at` integer;--> statement-breakpoint
|
||||
ALTER TABLE `connection_grants` ADD `end_reason` text;--> statement-breakpoint
|
||||
ALTER TABLE `connections` ADD `idle_revoke_hours` integer;--> statement-breakpoint
|
||||
UPDATE `connection_grants` SET `granted_at` = CAST(unixepoch('subsec') * 1000 AS INTEGER);
|
||||
5381
packages/db/migrations/meta/0034_snapshot.json
Normal file
5381
packages/db/migrations/meta/0034_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -239,6 +239,13 @@
|
||||
"when": 1795611432851,
|
||||
"tag": "0033_access_hub_oauth",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 34,
|
||||
"version": "6",
|
||||
"when": 1795621825422,
|
||||
"tag": "0034_grant_terms",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -708,6 +708,8 @@ export const connections = sqliteTable(
|
||||
oauthScopes: text("oauth_scopes", { mode: "json" }).$type<string[]>(),
|
||||
tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }),
|
||||
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
|
||||
// PEP-259: hours without calls after which a grant is revoked; null = platform default (72), 0 = never.
|
||||
idleRevokeHours: integer("idle_revoke_hours"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
@ -728,6 +730,15 @@ export const connectionGrants = sqliteTable(
|
||||
readMode: text("read_mode").$type<"off" | "auto" | "ask">().notNull().default("off"),
|
||||
writeMode: text("write_mode").$type<"off" | "auto" | "ask">().notNull().default("off"),
|
||||
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
|
||||
// PEP-259: the term chosen (extend gives the same again) and when it ends (null = until revoked).
|
||||
term: text("term").$type<"1h" | "1d" | "7d" | "forever">().notNull().default("forever"),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp_ms" }),
|
||||
// Idle countdown anchor: given / extended (migration: the deploy time); last allowed call.
|
||||
grantedAt: integer("granted_at", { mode: "timestamp_ms" }),
|
||||
lastUsedAt: integer("last_used_at", { mode: "timestamp_ms" }),
|
||||
// Revoked by the watchdog (the row stays to tell the agent why and let the owner extend).
|
||||
endedAt: integer("ended_at", { mode: "timestamp_ms" }),
|
||||
endReason: text("end_reason").$type<"idle">(),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("connection_grants_project").on(t.projectId), index("connection_grants_connection").on(t.connectionId)],
|
||||
|
||||
@ -440,7 +440,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
// PEP-234 Access Hub: the owner's external services, reached only through Peppa's gateway.
|
||||
tool(
|
||||
"list_connections",
|
||||
"List the external services (Access Hub connections) you may use in this session — HTTP services, and (PEP-251) databases, SSH servers, S3 storages and mailboxes with their operations: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».",
|
||||
"List the external services (Access Hub connections) you may use in this session — HTTP services, and (PEP-251) databases, SSH servers, S3 storages and mailboxes with their operations: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works, until when the access lasts and when it is revoked if unused. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».",
|
||||
{},
|
||||
async () => {
|
||||
if (!sessionId) return "Connections work only in sessions started by FORGE.";
|
||||
@ -458,6 +458,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
` key: ${keyText(c.checkStatus)}${c.docsUrl ? `; API docs: ${c.docsUrl}` : ""}`,
|
||||
// PEP-251: a database, a server, a storage or a mailbox — use_connection with these operations.
|
||||
...(c.protocol !== "http" ? [` kind: ${c.protocol} — call with use_connection; operations:`, ...c.protocolOperations.map((op) => ` · ${op.name}(${op.args.join(", ")}) [${op.kind}] — ${op.help}`)] : []),
|
||||
` access: ${c.expiresAt ? `until ${c.expiresAt.toISOString()}` : "until the owner revokes it"}; unused for long, the owner is asked whether to revoke it`,
|
||||
].join("\n"),
|
||||
),
|
||||
].join("\n");
|
||||
@ -476,7 +477,9 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
},
|
||||
async ({ connection, method, path, body, content_type }) => {
|
||||
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
|
||||
if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`);
|
||||
// PEP-259: a term that ran out / a grant revoked for no use — the owner extends it with one click.
|
||||
const again = r.ok ? "" : 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.` : "";
|
||||
if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}${again}`);
|
||||
const s = await getSession(db, sessionId!);
|
||||
const data = await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId, source: `подключение ${String(connection)}`, text: r.body });
|
||||
return [`HTTP ${r.status}${r.contentType ? ` · ${r.contentType}` : ""}${r.truncated ? " · truncated at 256 KB" : ""}`, data].join("\n");
|
||||
|
||||
@ -40,7 +40,7 @@ import { limitDelay, limitOver } from "./limit-delay.ts";
|
||||
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
|
||||
import { readyDigestTick } from "./ready-digest.ts";
|
||||
import { stuckTaskTick } from "./stuck-tasks.ts";
|
||||
import { connectionCheckTick, connectionJournalTick } from "@peppa/core";
|
||||
import { connectionCheckTick, connectionJournalTick, grantExpiryTick } from "@peppa/core";
|
||||
import { domainGuardTick } from "./domain-guard.ts";
|
||||
import { orphanContainersTick } from "./orphan-containers.ts";
|
||||
import { removeContainer } from "./sandbox.ts";
|
||||
@ -437,6 +437,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
|
||||
await connectionCheckTick(db).catch(failed(db, log, "connection check failed"));
|
||||
// PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table.
|
||||
await connectionJournalTick(db, { log }).catch(failed(db, log, "connection journal failed"));
|
||||
// PEP-259: grants nobody used for the connection's threshold (72 h) are revoked; one summary a day.
|
||||
await grantExpiryTick(db).catch(failed(db, log, "connection grants expiry failed"));
|
||||
// PEP-209: one «Готово к приёмке» summary instead of many «готово» messages in Telegram.
|
||||
await acceptDigestTick(db, { log }).catch(failed(db, log, "accept digest failed"));
|
||||
await pruneAcceptFailures(db).catch(() => {});
|
||||
|
||||
@ -240,6 +240,42 @@ export const accessHub: Record<string, string> = {
|
||||
"сервис вернул ошибку": "the service returned an error",
|
||||
"сервис не принял пароль или ключ": "the service didn't accept the password or key",
|
||||
"у этого подключения другие операции": "this connection has other operations",
|
||||
// PEP-259: grant terms and revoking unused grants.
|
||||
"срок истёк": "term is over",
|
||||
"снято: {n} ч без дела": "revoked: {n} h unused",
|
||||
"Продлить на {term}": "Extend for {term}",
|
||||
"до {when}": "until {when}",
|
||||
"до отзыва": "until revoked",
|
||||
"действовало до {when}": "was valid until {when}",
|
||||
"снято {ago}": "revoked {ago}",
|
||||
"последний вызов {ago}": "last call {ago}",
|
||||
"вызовов ещё не было": "no calls yet",
|
||||
"спросим вас о снятии через {left} без дела": "we'll ask you about revoking it in {left} if unused",
|
||||
"Срок": "Term",
|
||||
"не спрашивать": "never ask",
|
||||
"{n} дн без дела": "{n} days unused",
|
||||
"{n} ч без дела": "{n} h unused",
|
||||
"Спрашивать, снять ли разрешение, которым не пользуются:": "Ask whether to revoke a permission nobody uses after:",
|
||||
"Спрашивать о разрешении без дела": "Ask about an unused permission",
|
||||
"как обычно — {text}": "default — {text}",
|
||||
"разрешение снято": "permission revoked",
|
||||
"срок доступа истёк": "the access term is over",
|
||||
"доступ снят владельцем: им долго не пользовались": "the owner revoked the access: unused for too long",
|
||||
"1 час": "1 hour",
|
||||
"1 день": "1 day",
|
||||
"7 дней": "7 days",
|
||||
"Недопустимый срок": "Invalid term",
|
||||
"— «{name}» в {project}, агент {agent}: {hours} ч без дела": "— «{name}» in {project}, agent {agent}: {hours} h unused",
|
||||
"— «{name}» в {project}: {hours} ч без дела": "— «{name}» in {project}: {hours} h unused",
|
||||
"Агенты давно не пользуются разрешениями: {n}. Снять их? Пока вы не решили, доступ остаётся. Решить можно кнопками ниже или в разделе «Подключения».": "Agents haven't used some permissions for a long time: {n}. Revoke them? Until you decide, the access stays. Decide with the buttons below or in «Connections».",
|
||||
"Снять: {name}": "Revoke: {name}",
|
||||
"Оставить": "Keep",
|
||||
"Снять": "Revoke",
|
||||
"не используется {n} ч — снять?": "unused for {n} h — revoke?",
|
||||
"Разрешение уже снято": "The permission is already revoked",
|
||||
"Разрешение оставлено": "The permission is kept",
|
||||
"Разрешение снято": "The permission is revoked",
|
||||
"Вернуть": "Restore",
|
||||
// PEP-252: signing in to services.
|
||||
"Не удалось войти в сервис": "Could not sign in to the service",
|
||||
"Не удалось начать вход в сервис": "Could not start signing in to the service",
|
||||
|
||||
@ -240,6 +240,42 @@ export const accessHub: Record<string, string> = {
|
||||
"сервис вернул ошибку": "сервис қате қайтарды",
|
||||
"сервис не принял пароль или ключ": "сервис құпиясөзді немесе кілтті қабылдамады",
|
||||
"у этого подключения другие операции": "бұл қосылымның басқа операциялары бар",
|
||||
// PEP-259: grant terms and revoking unused grants.
|
||||
"срок истёк": "мерзімі өтті",
|
||||
"снято: {n} ч без дела": "алынды: {n} сағ қолданылмады",
|
||||
"Продлить на {term}": "{term} ұзарту",
|
||||
"до {when}": "{when} дейін",
|
||||
"до отзыва": "кері қайтарылғанға дейін",
|
||||
"действовало до {when}": "{when} дейін жарамды болды",
|
||||
"снято {ago}": "алынды {ago}",
|
||||
"последний вызов {ago}": "соңғы шақыру {ago}",
|
||||
"вызовов ещё не было": "шақырулар әлі болған жоқ",
|
||||
"спросим вас о снятии через {left} без дела": "қолданылмаса, {left} кейін алуды сізден сұраймыз",
|
||||
"Срок": "Мерзімі",
|
||||
"не спрашивать": "сұрамау",
|
||||
"{n} дн без дела": "{n} күн қолданылмаса",
|
||||
"{n} ч без дела": "{n} сағ қолданылмаса",
|
||||
"Спрашивать, снять ли разрешение, которым не пользуются:": "Қолданылмайтын рұқсатты алу керек пе деп сұрау:",
|
||||
"Спрашивать о разрешении без дела": "Қолданылмайтын рұқсат туралы сұрау",
|
||||
"как обычно — {text}": "әдеттегідей — {text}",
|
||||
"разрешение снято": "рұқсат алынды",
|
||||
"срок доступа истёк": "қолжетімділік мерзімі өтті",
|
||||
"доступ снят владельцем: им долго не пользовались": "иесі қолжетімділікті алды: ұзақ уақыт қолданылмады",
|
||||
"1 час": "1 сағат",
|
||||
"1 день": "1 күн",
|
||||
"7 дней": "7 күн",
|
||||
"Недопустимый срок": "Жарамсыз мерзім",
|
||||
"— «{name}» в {project}, агент {agent}: {hours} ч без дела": "— «{name}», {project}, агент {agent}: {hours} сағ қолданылмады",
|
||||
"— «{name}» в {project}: {hours} ч без дела": "— «{name}», {project}: {hours} сағ қолданылмады",
|
||||
"Агенты давно не пользуются разрешениями: {n}. Снять их? Пока вы не решили, доступ остаётся. Решить можно кнопками ниже или в разделе «Подключения».": "Агенттер кейбір рұқсаттарды ұзақ уақыт қолданбайды: {n}. Оларды алу керек пе? Сіз шешкенше қолжетімділік сақталады. Төмендегі түймелермен немесе «Қосылымдар» бөлімінде шешуге болады.",
|
||||
"Снять: {name}": "Алу: {name}",
|
||||
"Оставить": "Қалдыру",
|
||||
"Снять": "Алу",
|
||||
"не используется {n} ч — снять?": "{n} сағ қолданылмайды — алу керек пе?",
|
||||
"Разрешение уже снято": "Рұқсат бұрын алынған",
|
||||
"Разрешение оставлено": "Рұқсат қалдырылды",
|
||||
"Разрешение снято": "Рұқсат алынды",
|
||||
"Вернуть": "Қайтару",
|
||||
// PEP-252: signing in to services.
|
||||
"Не удалось войти в сервис": "Сервиске кіру мүмкін болмады",
|
||||
"Не удалось начать вход в сервис": "Сервиске кіруді бастау мүмкін болмады",
|
||||
|
||||
249
packages/testkit/test/access-hub-terms.test.ts
Normal file
249
packages/testkit/test/access-hub-terms.test.ts
Normal file
@ -0,0 +1,249 @@
|
||||
// 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<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
|
||||
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));
|
||||
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<void>((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/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user