PEP-259: срок у разрешения Access Hub и автоснятие без дела
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 46с
peppa/build build: success за 35с
peppa/test test: success за 1453с
peppa-ci / ci (pull_request) Successful in 26m21s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 13:50:41 +00:00
parent eee9ab5c85
commit 7991a2e374
20 changed files with 6217 additions and 42 deletions

View File

@ -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`.
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.

View File

@ -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` (выдача/продление; миграция 0033 поставила старым время выкатки), `last_used_at` (шлюз при разрешённом вызове), `ended_at`/`end_reason` (`idle`; строка остаётся — агенту причина, владельцу «Продлить»). Шлюз решает только по живым разрешениям, иначе `expired`/`idle_revoked`. `grantExpiryTick` (вачдог): простой ≥ `connections.idle_revoke_hours` (null — `PEPPA_CONNECTION_IDLE_HOURS`, 72; 0 — не снимать; проекты на паузе пропускаются) → снято + строка журнала `REVOKE` через `appendJournal` + сводка владельцу раз в сутки (`connections.idle.digest:<userId>`); снятые/истёкшие старше 30 дней удаляются; `PEPPA_CONNECTION_IDLE=off`. `extendGrant` — тот же срок заново; `GRANT_RIGHTS` read/full — для кнопок «Дать» (PEP-261). Тест `access-hub-terms.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`
- **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:<taskId>` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts`

View File

@ -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, 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";
@ -1086,7 +1086,24 @@ 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: «Снимать разрешение без дела через …» 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));
});
}

View File

@ -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,
@ -23,6 +29,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";
@ -33,7 +40,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, deleteConnectionAction, extendGrantAction, grantConnectionAction, replaceConnectionSecretAction, resetHostKeyAction, revokeConnectionAction, revokeGrantAction, setConnectionIdleAction } from "../actions";
export async function generateMetadata() {
const t = await getT();
@ -69,23 +76,97 @@ 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 a grant is revoked 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>}
{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">
{(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.idleRevokeAt && <span>{t("снимется через {left} без дела", { left: hoursLeft(g.idleRevokeAt, 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">
@ -128,6 +209,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)}
@ -193,6 +275,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>
@ -539,9 +622,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} />

View File

@ -0,0 +1,17 @@
## 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 перенумеровать.

View File

@ -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`.

View File

@ -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** в ответе есть время окончания доступа и время снятия без дела

View File

@ -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`; миграция 0033 (старым — `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

View File

@ -321,3 +321,69 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
- **WHEN** агент проекта «boris» просит `query` через него
- **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 сниматься само в тике вачдога. Отсчёт 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** в ответе есть время окончания доступа и время снятия без дела

View File

@ -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 });
const mask = (t: string) => maskSecrets(t, secret.length >= 4 ? [secret] : []);

View File

@ -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";
@ -23,6 +23,7 @@ import { deliverToUser } from "./notifications.ts";
import { PeppaError } from "./errors.ts";
import { maskSecrets } from "./secrets.ts";
import { projectForUser } from "./users.ts";
import { pausedProjectIds } from "./project-pause.ts";
export { isBlockedAddress } from "./connection-protocols.ts";
@ -45,6 +46,8 @@ export type ConnectionReason =
| "ambiguous_connection"
| "revoked"
| "no_grant"
| "expired"
| "idle_revoked"
| "operation_denied"
| "read_denied"
| "write_denied"
@ -74,6 +77,8 @@ export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
ambiguous_connection: tr("несколько подключений с таким названием"),
revoked: tr("подключение отозвано"),
no_grant: tr("нет разрешения для проекта или агента"),
expired: tr("срок доступа истёк"),
idle_revoked: tr("доступ снят: им долго не пользовались"),
operation_denied: tr("операция не разрешена"),
read_denied: tr("чтение не разрешено"),
write_denied: tr("запись не разрешена"),
@ -116,6 +121,8 @@ export interface ConnectionView {
hasKey: boolean;
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[];
}
@ -131,6 +138,51 @@ 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 it is revoked if nobody uses it (null — never: the connection's threshold is 0). */
idleRevokeAt: Date | null;
/** active; expired — the term is over; idle — revoked by the watchdog for no use. */
state: GrantState;
endedAt: Date | null;
/** Hours of the threshold that revoked it (for «снято: 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 «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 idleRevokeAt(g: Pick<GrantRow, "lastUsedAt" | "grantedAt" | "createdAt">, hours: number): Date | null {
return hours > 0 ? new Date(idleAnchor(g) + hours * 3600_000) : null;
}
export type GrantMode = "off" | "auto" | "ask";
@ -458,6 +510,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");
@ -471,22 +528,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> {
@ -497,9 +577,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,
@ -512,21 +592,33 @@ 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));
return rows.map(({ grantedAt, idleRevokeHours, ...r }) => {
const idleHours = idleHoursOf({ idleRevokeHours });
const state = grantState(r, now);
return { ...r, state, idleHours, idleRevokeAt: state === "active" ? idleRevokeAt({ ...r, grantedAt }, idleHours) : 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,
@ -543,6 +635,7 @@ export async function listConnections(db: Db, userId: number): Promise<Connectio
hasKey: !!r.secretEnc,
revokedAt: r.revokedAt,
lastUsedAt: r.lastUsedAt,
idleRevokeHours: r.idleRevokeHours,
createdAt: r.createdAt,
grants: grants.filter((g) => g.connectionId === r.id).map(({ connectionId: _, ...g }) => g),
}));
@ -634,6 +727,10 @@ 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;
/** When the last live grant is revoked without calls; null — never. */
idleRevokeAt: Date | null;
}
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
@ -641,12 +738,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), eq(connections.status, "active")))
@ -654,10 +752,15 @@ 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.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.checkStatus, protocol: proto, protocolOperations, expiresAt: null, idleRevokeAt: null };
const idle = idleRevokeAt(r.g, idleHoursOf(r.c));
c.expiresAt = first ? r.g.expiresAt : c.expiresAt && r.g.expiresAt ? (r.g.expiresAt > c.expiresAt ? r.g.expiresAt : c.expiresAt) : null;
c.idleRevokeAt = first ? idle : c.idleRevokeAt && idle ? (idle > c.idleRevokeAt ? idle : c.idleRevokeAt) : null;
c.operations = [...new Set([...c.operations, ...r.operations])];
c.readMode = widest(c.readMode, r.readMode);
c.writeMode = widest(c.writeMode, r.writeMode);
@ -708,12 +811,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));
@ -727,6 +830,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 }];
@ -852,8 +972,9 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
if (!agentIsolated(s, o.env)) return deny("not_isolated");
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");
@ -879,6 +1000,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 });
@ -1010,3 +1133,110 @@ 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 revoking idle grants ----------
/** Revoked-for-idle 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;
interface IdleDigestItem {
connection: string;
project: string;
agent: string | null;
hours: number;
}
/**
* Watchdog tick: a live grant nobody called for the connection's threshold (default 72 h) is
* revoked — journal row, event, a line for the owner's daily summary; the live agent is told
* nothing (it learns on its next call). Paused projects are skipped (their agents can't call).
* Ended grants older than 30 days are deleted. Returns how many were revoked.
*/
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")));
let revoked = 0;
for (const r of rows) {
if (paused.has(r.g.projectId) || grantState(r.g, now) !== "active") continue;
const hours = idleHoursOf(r.c);
const at = idleRevokeAt(r.g, hours);
if (!at || at.getTime() > now.getTime()) continue;
// Claim: a concurrent call that just used it, or another tick, wins.
const done = await db
.update(connectionGrants)
.set({ endedAt: now, endReason: "idle" })
.where(and(eq(connectionGrants.id, r.g.id), isNull(connectionGrants.endedAt), r.g.lastUsedAt ? eq(connectionGrants.lastUsedAt, r.g.lastUsedAt) : isNull(connectionGrants.lastUsedAt)))
.returning({ id: connectionGrants.id });
if (!done.length) continue;
revoked++;
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, agentId: r.g.agentId, reason: "idle", hours } });
const key = `${IDLE_DIGEST}${r.c.ownerId}`;
const list = (await getSetting<IdleDigestItem[]>(db, key)) ?? [];
list.push({ 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);
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()})`);
// One summary a day per owner, only when something was revoked.
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 items = (d.value as IdleDigestItem[] | null) ?? [];
if (!Number.isFinite(ownerId) || !items.length) continue;
const sent = await getSetting<number>(db, `${IDLE_DIGEST_SENT}${ownerId}`);
if (sent != null && now.getTime() - sent < DIGEST_EVERY_MS) continue;
await setSetting(db, `${IDLE_DIGEST_SENT}${ownerId}`, now.getTime());
await setSetting(db, d.key, []);
await (o.notify ?? tellIdleRevoked)(db, ownerId, items);
}
return revoked;
}
/** The owner's daily summary of grants revoked for no use: master chat + Telegram/push (night quiet is the outbox's). */
export async function tellIdleRevoked(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 key = `connection-idle:${ownerId}:${Date.now()}`;
await addMasterMessage(db, ownerId, { kind: "event", 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: "failures",
dedupeKey: `${key}:${u.telegramChatId}`,
pushKey: `${key}:u${u.id}`,
telegram: { params: { text } },
push: { title: tr("FORGE"), body: text, url: "/connections", tag: "connection-idle" },
}).catch(() => null);
}

View 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);

File diff suppressed because it is too large Load Diff

View File

@ -232,6 +232,13 @@
"when": 1795530560091,
"tag": "0032_secrets_agent_env",
"breakpoints": true
},
{
"idx": 33,
"version": "6",
"when": 1795533628410,
"tag": "0033_grant_terms",
"breakpoints": true
}
]
}

View File

@ -701,6 +701,8 @@ export const connections = sqliteTable(
status: text("status").$type<"active" | "revoked">().notNull().default("active"),
revokedAt: integer("revoked_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(),
},
@ -721,6 +723,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)],

View File

@ -412,7 +412,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.";
@ -430,6 +430,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"}${c.idleRevokeAt ? `; revoked automatically if unused until ${c.idleRevokeAt.toISOString()} (each allowed call restarts this countdown)` : ""}`,
].join("\n"),
),
].join("\n");
@ -448,7 +449,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");

View File

@ -39,7 +39,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";
@ -428,6 +428,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(() => {});

View File

@ -240,4 +240,33 @@ 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} без дела": "revoked in {left} if unused",
"Срок": "Term",
"не снимать": "never revoke",
"{n} дн без дела": "{n} days unused",
"{n} ч без дела": "{n} h unused",
"Снимать разрешение, которым не пользуются:": "Revoke a permission nobody uses after:",
"Снимать разрешение без дела": "Revoke an unused permission",
"как обычно — {text}": "default — {text}",
"разрешение снято": "permission revoked",
"срок доступа истёк": "the access term is over",
"доступ снят: им долго не пользовались": "access revoked: 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}. Если доступ снова нужен — нажмите «Продлить» в разделе «Подключения».": "Permissions agents haven't used for a long time were revoked: {n}. If the access is needed again, press «Extend» in «Connections».",
"Вернуть": "Restore",
};

View File

@ -240,4 +240,33 @@ 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}. Қолжетімділік қайта керек болса, «Қосылымдар» бөлімінде «Ұзарту» түймесін басыңыз.",
"Вернуть": "Қайтару",
};

View File

@ -0,0 +1,204 @@
// PEP-259 Access Hub: a grant lives for a term (1 h · 1 day · 7 days · until revoked) and is
// revoked by the watchdog after the connection's threshold (72 h) without calls. 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!.idleRevokeAt && view!.idleRevokeAt.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.idleRevokeAt, 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, proj } = await setup({ term: "forever", at: new Date(now.getTime() - 73 * H) });
const sent: Array<{ ownerId: number; n: number }> = [];
const n = await core.grantExpiryTick(db, { now, notify: async (_db, ownerId, items) => void sent.push({ ownerId, n: items.length }) });
assert.ok(n >= 1);
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" });
assert.ok(sent.some((x) => x.ownerId === anna.id));
// Within a day — no second summary even if more are revoked.
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 summary");
// 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 { 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.idleRevokeAt, 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);
assert.ok(list[0]!.idleRevokeAt);
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, /revoked automatically if unused until/);
});
});