PEP-189: страж порта и домена — чужой контейнер на порту/домене Peppa останавливается, публичный адрес проверяется

Агент IA-2 опубликовал свой контейнер на 127.0.0.1:3100 и подменил сайт платформы.
Вачдог раз в минуту останавливает (не удаляет) контейнер, занявший зарезервированный
порт или домен платформы, пишет суперадмину и агенту; /api/health публичного адреса
должен отвечать Peppa. Маршруты Traefik — priority 100000, правило агентам в RULES.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-17 12:36:39 +05:00
parent 80457bde42
commit 15d06cdad1
19 changed files with 570 additions and 3 deletions

View File

@ -90,6 +90,7 @@
- **Полоса для продакта и имена подписок (PEP-121)**: в режиме «Продакт» полоса над страницами — `AgentsStrip` («Агенты работают» / «Агенты продолжат в ЧЧ:ММ», `agentsLine` в core/usage.ts: пауза — только когда все живые агенты проектов пользователя ждут лимита, или никто не запущен и все подписки пулов в лимите); «Инженер» — прежний `UsageStrip`. Имя подписки (в нём логин подключившего) видят суперадмин и автор (`subscriptions.created_by`): `core/subscription-names.ts` (`visibleSubscriptionName(sub, viewer)`, `publicSubscriptionName` → «Подписка Claude|ChatGPT|OpenCode»); `accountUsageForUser` (полоса, `/status`, `get_usage`) и `poolOverview(…, viewer)` маскируют сами; в вебе имя у сессий — только через `<SubscriptionName>` / `subscriptionNamesVisible()` (суперадмин), `switchText(payload, names)`; сообщения участникам проекта (переключение, последняя подписка, запасная, «агенты не запустятся») — без имён, в payload событий имена остаются. Новое место показа подписки — через эти функции. Тест `subscription-names.test.ts`
- **Уведомления (PEP-29/35/55)**: события `questions`/`review`/`failures`/`releases`/`incidents`/`monitoring`/`digest` × каналы Telegram/push на пользователя — `notify.prefs:<userId>` в `settings` (`getNotifyPrefs` с умолчаниями, всё включено, кроме дайджеста в браузер), тихие часы (Telegram с `disable_notification`, push пропускается), таймзона (по умолчанию сервера или `PEPPA_TZ`), выключенные проекты. Всё идёт через `deliverToUser` (core/notifications.ts): вопросы (бот `reconcile`, категория — `questionEvent`, получатели — `projectAudience`; ключи Telegram `q:<id>:<chat>` прежние), ошибки из прода, алерты мониторинга. Web Push — свой на `node:crypto` (core/webpush.ts: VAPID в `settings` `push.vapid`, aes128gcm), таблицы `push_subscriptions` + `push_outbox` (разбирает бот вместе с Telegram-outbox, 404/410 удаляют подписку; push только для вопросов моложе 30 мин). Веб: «Настройки → Уведомления», `public/sw.js`, `app/manifest.ts` (PWA), `AttentionBadge` (счётчик в заголовке и значке, звук; `/api/attention`). Дайджест (core/digest.ts): `digestTick` в `tick` вачдога — в выбранное время (окно 3 ч, `digest.last:<userId>`), пустой не шлётся; `/digest` в боте. Мок — `mock-push` (testkit: проверяет VAPID и расшифровывает)
- **Сообщение о новом пользователе (PEP-113)**: `core/new-users.ts` `announceNewUser(db, user, via)` — зовут сами функции создания учётки (`registerEgovUser`, `registerGoogleUser`, `createLocalUser`) после успешной вставки; получатели — `platformAdmins` кроме новичка и автора (`currentActor().userId`), событие уведомлений `users` («Новые пользователи (админам)», строка в настройках — только суперадмину, как `monitoring`), ключ outbox `newuser:<id>:<chat>`, ИИН в текст не идёт, не бросает. Новый способ регистрации — добавить вызов. Тест `new-users.test.ts`
- **Страж порта и домена (PEP-189)**: `core/domain-guard.ts` (`guardRules`: порты 3100/3180/3190 + порт `PEPPA_WEB_URL` + `PEPPA_RESERVED_PORTS`, домены из `PEPPA_WEB_URL`/`BUGSINK_URL`/`GITEA_URL` + `PEPPA_RESERVED_HOSTS`; свои контейнеры — точные имена + `PEPPA_GUARD_ALLOW`, не префикс `peppa-`: так зовутся и песочницы агентов) и `runner/domain-guard.ts` — `domainGuardTick` в минутном блоке вачдога: `docker ps` → чужой контейнер, который публикует зарезервированный порт или метит Traefik `Host()` на домен платформы, — `docker stop` (не удаляется), суперадмину одно сообщение на контейнер (`guard:<имя>:<id>`), живому агенту задачи (имя / compose-проект начинается с `<ключ>-` или `<slug>-`) — перенести на порт от 18000; `publicHealthTick`: `/api/health` публичного адреса (`PEPPA_PUBLIC_HEALTH_URL` или `PEPPA_WEB_URL`, localhost пропускается) должен быть ответом Peppa (`boot` + `services`), иначе после двух подряд — одно сообщение на эпизод (`settings` `guard.public`), 5xx — не его дело. `PEPPA_DOMAIN_GUARD=off`; в тестах выключен (`helpers.ts`), `mock-docker ps|stop` (`$MOCK_DOCKER_STATE/ps`). Маршруты `infra/traefik/*.yml` — priority 100000. Правило агентам — «Порты и домены платформы» в `template/RULES.md`. Тест `domain-guard.test.ts`
- **Канал платформы и дайджест Пеппы (PEP-60)**: `core/platform-channel.ts`, настройки в `settings` `platform.telegram_channel` (Chat ID, `check` — результат `checkPlatformChannel`: Bot API `getMe`→`getChat`→`getChatMember`, «бот не видит канал — добавьте его администратором» / нет права публикации; события releases/services/digest; `digest.time/timezone/users`, личные чаты по умолчанию выкл). В канал пишет только при `check.ok` (`postToChannel`, outbox; сервисные ключи `mon:ch:*` — вачдог доставит сам, если упал бот); неработающий канал вачдог перепроверяет раз в час (`recheckPlatformChannel`). События: `checkServices` — одно «не отвечает» и одно «снова работает — простой N мин» на простой, «перезапущен» при смене процесса без простоя (`monitor.process:<service>`, heartbeat несёт `commit`); `platformBuildTick` (runner/platform-build.ts) — HEAD корня ≠ `platform.build` и входит в `main` → «🚀 Peppa vX · sha» + стори из коммитов (первый раз только запоминает). `platformDigestTick` (вачдог): «Что нового» (done-стори `PEPPA_PLATFORM_KEY`, сборки) + «Сейчас» (версия, сервисы, раннеры, вопросы, лимиты), пустой не шлётся, в канал и пользователям событием уведомлений `platform`. Веб `/platform` (суперадмин), CLI `peppa platform channel chat=<id> [k=v…]|check`, `peppa platform digest [now]`. Мок — каналы в `mock-telegram` (`addChannel`)
- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:<service>`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon:<service>:…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]`
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/` — `capacity: 4` job одновременно на регистрацию (PEP-157; меняется перезапуском контейнера, тест `ci-runner-config.test.ts`), контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect <KEY>` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)

View File

@ -6,7 +6,8 @@ http:
rule: "Host(`bugsink.telecom.quest`)"
service: bugsink
entryPoints: [web]
priority: 30
# PEP-189: выше любого маршрута контейнера проекта — метка Host() на этот домен его не перехватит.
priority: 100000
middlewares: [compress]
services:
bugsink:

View File

@ -7,7 +7,8 @@ http:
rule: "Host(`peppa.telecom.quest`)"
service: peppa
entryPoints: [web]
priority: 30
# PEP-189: выше любого маршрута контейнера проекта — метка Host() на этот домен его не перехватит.
priority: 100000
middlewares: [compress]
services:
peppa:

View File

@ -0,0 +1,8 @@
## Решения
- **Останавливаем, а не удаляем** (`docker stop`): PM просил не удалять чужое; контейнер можно поднять снова на другом порту.
- **Кого не трогаем**: точные имена `peppa-bugsink`, `peppa-act-runner`, `peppa-postgres`, `gitea`, `gitea-pages`, `traefik` (+ `PEPPA_GUARD_ALLOW`). Не префикс `peppa-`: так называются и контейнеры агентов `peppa-s<id>`.
- **Порты**: `PEPPA_RESERVED_PORTS` (по умолчанию `3100,3180,3190` и порт из `PEPPA_WEB_URL`). Нарушение — публикация на хосте (`… :3100->`), любой адрес.
- **Домены**: хост `PEPPA_WEB_URL`, `BUGSINK_URL`, `GITEA_URL` и `PEPPA_RESERVED_HOSTS`; ищем `Host(`…`)` в метках `traefik.http.routers.*.rule`.
- **Агент**: имя контейнера или `com.docker.compose.project` начинается с `<ключ задачи в нижнем регистре>-` (`ia-2-smoke`) или со `<slug проекта>-` → живые сессии этой задачи/проекта получают `sendToSession`.
- **Сообщения**: `alertAdmins` с ключом `guard:<имя>:<id контейнера>` — один раз на контейнер; публичная проверка — `guard:public:<эпизод>`; состояние в `settings` `guard.public`.
- Публичная проверка пропускается, если `PEPPA_WEB_URL` указывает на localhost (тесты, стенд) и не задан `PEPPA_PUBLIC_HEALTH_URL`.

View File

@ -0,0 +1,10 @@
## Why
2026-11-17 агент IA-2 для своей проверки запустил контейнер с `-p 127.0.0.1:3100:3100`. Traefik ведёт peppa.telecom.quest на `host.docker.internal:3100`, OrbStack отдаёт этот адрес в `127.0.0.1:3100` — весь сайт Peppa показывал чужое приложение, войти было нельзя. Next слушает `*:3100` на IPv6, поэтому мониторинг (`localhost`) был зелёным.
## What Changes
- Список зарезервированных портов и доменов платформы (`core/domain-guard.ts`, env `PEPPA_RESERVED_PORTS`, `PEPPA_RESERVED_HOSTS`, `PEPPA_GUARD_ALLOW`).
- `domainGuardTick` в вачдоге (раз в минуту): чужой контейнер, который публикует зарезервированный порт или метит Traefik-маршрут на домен платформы, останавливается (`docker stop`, не удаляется); суперадмину одно сообщение на контейнер; живому агенту задачи (по имени контейнера / compose-проекту) — указание сменить порт. `PEPPA_DOMAIN_GUARD=off` выключает.
- Проверка публичного адреса: `/api/health` по `PEPPA_WEB_URL` должен отвечать Peppa (JSON с `boot`); иначе суперадмину «домен отдаёт чужое приложение», одно на эпизод, и «снова Peppa» по возвращении.
- `infra/traefik/peppa.yml` и `bugsink.yml` — приоритет 100000: метка Traefik контейнера проекта не перекроет домен.
- `template/RULES.md`: порты 3000–3199 и домены платформы агентам запрещены, для проверок — от 18000.
- `mock-docker`: `ps` и `stop`.

View File

@ -0,0 +1,25 @@
## ADDED Requirements
### Requirement: Порт и домен Peppa не перехватываются
Вачдог SHALL останавливать чужие контейнеры, которые занимают порт или домен платформы, и SHALL проверять, что публичный адрес отдаёт Peppa.
#### Scenario: Контейнер агента занял порт Peppa
- **GIVEN** контейнер `ia-2-smoke` публикует `127.0.0.1:3100->3100/tcp`, агент задачи IA-2 работает
- **WHEN** проходит тик стража
- **THEN** контейнер остановлен `docker stop`, не удалён
- **AND** суперадмину одно сообщение, агенту IA-2 — указание сменить порт
#### Scenario: Метка Traefik на домен Peppa
- **GIVEN** контейнер проекта с меткой `traefik.http.routers.x.rule=Host(`peppa.telecom.quest`)`
- **WHEN** проходит тик стража
- **THEN** контейнер остановлен
#### Scenario: Свои сервисы
- **GIVEN** `peppa-bugsink` публикует `127.0.0.1:3180`
- **WHEN** проходит тик стража
- **THEN** контейнер работает дальше
#### Scenario: Домен отдаёт чужое приложение
- **GIVEN** `/api/health` публичного адреса отвечает не Peppa
- **WHEN** проходит проверка
- **THEN** суперадмину одно сообщение за эпизод, по возвращении — «снова Peppa»

View File

@ -0,0 +1,5 @@
- [x] 1. `core/domain-guard.ts`: зарезервированные порты/домены, разбор `docker ps`, поиск нарушителей
- [x] 2. `runner/domain-guard.ts`: `domainGuardTick` (stop, сообщения суперадмину и агенту) + публичная проверка; вызов из вачдога раз в минуту
- [x] 3. `mock-docker`: `ps`, `stop`
- [x] 4. `infra/traefik/*.yml` — priority 100000; `template/RULES.md` — правило о портах
- [x] 5. Тест `domain-guard.test.ts`; AGENTS.md

View File

@ -0,0 +1,30 @@
# domain-guard Specification
## Purpose
TBD - created by archiving change pep-189-domain-guard. Update Purpose after archive.
## Requirements
### Requirement: Порт и домен Peppa не перехватываются
Вачдог SHALL останавливать чужие контейнеры, которые занимают порт или домен платформы, и SHALL проверять, что публичный адрес отдаёт Peppa.
#### Scenario: Контейнер агента занял порт Peppa
- **GIVEN** контейнер `ia-2-smoke` публикует `127.0.0.1:3100->3100/tcp`, агент задачи IA-2 работает
- **WHEN** проходит тик стража
- **THEN** контейнер остановлен `docker stop`, не удалён
- **AND** суперадмину одно сообщение, агенту IA-2 — указание сменить порт
#### Scenario: Метка Traefik на домен Peppa
- **GIVEN** контейнер проекта с меткой `traefik.http.routers.x.rule=Host(`peppa.telecom.quest`)`
- **WHEN** проходит тик стража
- **THEN** контейнер остановлен
#### Scenario: Свои сервисы
- **GIVEN** `peppa-bugsink` публикует `127.0.0.1:3180`
- **WHEN** проходит тик стража
- **THEN** контейнер работает дальше
#### Scenario: Домен отдаёт чужое приложение
- **GIVEN** `/api/health` публичного адреса отвечает не Peppa
- **WHEN** проходит проверка
- **THEN** суперадмину одно сообщение за эпизод, по возвращении — «снова Peppa»

View File

@ -0,0 +1,145 @@
// PEP-189: the platform's port and domains are not for projects. A container that publishes a
// reserved port (the web on 3100 — Traefik reaches it at host.docker.internal:3100, which OrbStack
// maps to the host's 127.0.0.1) or routes a platform domain through Traefik labels takes over
// peppa.telecom.quest. Pure helpers here; the watchdog side is runner/domain-guard.ts.
/** Containers of the platform itself — exact names: agent sandboxes are `peppa-s<id>` too. */
const OWN_CONTAINERS = ["peppa-bugsink", "peppa-act-runner", "peppa-postgres", "gitea", "gitea-pages", "traefik"];
export interface DockerContainer {
id: string;
name: string;
/** `docker ps` Ports column: `127.0.0.1:3100->3100/tcp, 3000/tcp`. */
ports: string;
/** `docker ps` Labels column: `k=v,k=v`. */
labels: string;
}
export interface GuardRules {
ports: number[];
hosts: string[];
allow: string[];
}
export interface Intruder {
container: DockerContainer;
/** Reserved host ports it publishes. */
ports: number[];
/** Platform domains its Traefik labels route. */
hosts: string[];
/** `com.docker.compose.project` label, when present. */
composeProject: string | null;
}
function hostOf(url: string | undefined): string | null {
if (!url) return null;
try {
return new URL(url).hostname.toLowerCase();
} catch {
return null;
}
}
function portOf(url: string | undefined): number | null {
if (!url) return null;
try {
const u = new URL(url);
return u.port ? Number(u.port) : null;
} catch {
return null;
}
}
const isLocal = (h: string | null) => !h || h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
const list = (v: string | undefined) => (v ?? "").split(",").map((s) => s.trim()).filter(Boolean);
/** Reserved ports and domains from env: the web's port, Bugsink, the bot's mock port and PEPPA_RESERVED_*. */
export function guardRules(env: NodeJS.ProcessEnv = process.env): GuardRules {
const ports = new Set<number>([3100, 3180, 3190]);
const webPort = portOf(env.PEPPA_WEB_URL);
if (webPort) ports.add(webPort);
for (const p of list(env.PEPPA_RESERVED_PORTS)) if (Number.isInteger(Number(p))) ports.add(Number(p));
const hosts = new Set<string>();
for (const u of [env.PEPPA_WEB_URL, env.BUGSINK_URL, env.GITEA_URL]) {
const h = hostOf(u);
if (!isLocal(h)) hosts.add(h!);
}
for (const h of list(env.PEPPA_RESERVED_HOSTS)) hosts.add(h.toLowerCase());
return { ports: [...ports].sort((a, b) => a - b), hosts: [...hosts].sort(), allow: [...OWN_CONTAINERS, ...list(env.PEPPA_GUARD_ALLOW)] };
}
/** `docker ps --format '{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}'` → containers. */
export function parseDockerPs(out: string): DockerContainer[] {
return out
.split("\n")
.filter((l) => l.trim())
.map((l) => {
const [id = "", name = "", ports = "", labels = ""] = l.split("\t");
return { id: id.trim(), name: name.trim(), ports: ports.trim(), labels: labels.trim() };
})
.filter((c) => c.id && c.name);
}
/** Host ports a container publishes: `0.0.0.0:80->80/tcp`, `[::]:80->80/tcp`, `127.0.0.1:3100->3100/tcp`. */
export function publishedPorts(ports: string): number[] {
const out = new Set<number>();
for (const m of ports.matchAll(/:(\d+)(?:-(\d+))?->/g)) {
const from = Number(m[1]);
const to = m[2] ? Number(m[2]) : from;
for (let p = from; p <= to && p - from < 1000; p++) out.add(p);
}
return [...out];
}
/** Hosts named in `Host(`…`)` of the container's Traefik router rules. */
export function traefikHosts(labels: string): string[] {
const out = new Set<string>();
for (const rule of labels.matchAll(/traefik\.http\.routers\.[^=,]+\.rule=([^]*?)(?=,[a-z0-9_.-]+=|$)/gi)) {
for (const h of rule[1]!.matchAll(/Host\(([^)]*)\)/gi)) {
for (const v of h[1]!.matchAll(/[`"']([^`"']+)[`"']/g)) out.add(v[1]!.toLowerCase());
}
}
return [...out];
}
function label(labels: string, key: string): string | null {
const m = labels.match(new RegExp(`(?:^|,)${key.replace(/\./g, "\\.")}=([^,]*)`));
return m ? m[1]! : null;
}
/** Containers that take a reserved port or a platform domain; the platform's own are skipped. */
export function findIntruders(containers: DockerContainer[], rules: GuardRules): Intruder[] {
const out: Intruder[] = [];
for (const c of containers) {
if (rules.allow.includes(c.name)) continue;
const ports = publishedPorts(c.ports).filter((p) => rules.ports.includes(p));
const hosts = traefikHosts(c.labels).filter((h) => rules.hosts.includes(h));
if (!ports.length && !hosts.length) continue;
out.push({ container: c, ports, hosts, composeProject: label(c.labels, "com.docker.compose.project") });
}
return out;
}
/**
* Whose container it is: the name or compose project starts with `<task key>-` (`ia-2-smoke`)
* or with `<project slug>-` (`brendmanager-pr64`). Returns the matching task key / slug.
*/
export function intruderOwner(i: Intruder, taskKeys: string[], slugs: string[]): { taskKey?: string; slug?: string } {
const names = [i.container.name, i.composeProject].filter((n): n is string => !!n).map((n) => n.toLowerCase());
const starts = (n: string, p: string) => n === p || n.startsWith(`${p}-`) || n.startsWith(`${p}_`);
const task = [...taskKeys].sort((a, b) => b.length - a.length).find((k) => names.some((n) => starts(n, k.toLowerCase())));
if (task) return { taskKey: task };
const slug = [...slugs].sort((a, b) => b.length - a.length).find((s) => names.some((n) => starts(n, s.toLowerCase())));
return slug ? { slug } : {};
}
/** True when the body is Peppa's own /api/health answer. */
export function isPeppaHealth(body: string): boolean {
try {
const j = JSON.parse(body) as { boot?: unknown; services?: unknown };
return typeof j.boot === "string" && Array.isArray(j.services);
} catch {
return false;
}
}

View File

@ -21,6 +21,7 @@ export * from "./users.ts";
export * from "./oauth.ts";
export * from "./access.ts";
export * from "./monitor.ts";
export * from "./domain-guard.ts";
export * from "./error-report.ts";
export * from "./backup.ts";
export * from "./repo-info.ts";

View File

@ -0,0 +1,138 @@
// PEP-189: the watchdog keeps the platform's port and domains to itself.
// 1. A container that publishes a reserved port or routes a platform domain is stopped (not
// removed), the superadmin hears about it once, the agent whose container it is — to move it.
// 2. The public address answers Peppa's own /api/health; otherwise one message per episode.
// glossary-ignore-file: messages here are for the superadmin and the agent.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { alertAdmins, findIntruders, getSetting, guardRules, intruderOwner, isPeppaHealth, listProjects, listSessions, parseDockerPs, setSetting, type Intruder } from "@peppa/core";
import { m } from "@peppa/shared/i18n";
import type { Db } from "@peppa/db";
import { sendToSession } from "./sessions.ts";
const run = promisify(execFile);
const docker = () => process.env.PEPPA_DOCKER_BIN ?? "docker";
export interface GuardResult {
stopped: Intruder[];
publicOk: boolean | null;
}
function describe(i: Intruder): string {
const what = [...i.ports.map((p) => m("порт {port}", { port: p })), ...i.hosts.map((h) => m("адрес {host}", { host: h }))].join(", ");
return what;
}
/** Stops containers that take the platform's port or domain; tells the superadmin and the agent. */
export async function containerGuardTick(db: Db, o: { log?: (m: string) => void } = {}): Promise<Intruder[]> {
const log = o.log ?? (() => {});
let out: string;
try {
({ stdout: out } = await run(docker(), ["ps", "--no-trunc", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}"], { timeout: 20_000, maxBuffer: 16 * 1024 ** 2 }));
} catch (e) {
log(`domain guard: docker ps: ${(e as Error).message.split("\n")[0]}`);
return [];
}
const intruders = findIntruders(parseDockerPs(out), guardRules());
if (!intruders.length) return [];
const live = await listSessions(db, { active: true });
const projects = await listProjects(db);
const stopped: Intruder[] = [];
for (const i of intruders) {
const c = i.container;
try {
await run(docker(), ["stop", "-t", "5", c.id], { timeout: 60_000 });
} catch (e) {
log(`domain guard: stop ${c.name}: ${(e as Error).message.split("\n")[0]}`);
continue;
}
stopped.push(i);
const what = describe(i);
log(`domain guard: stopped ${c.name} (${what})`);
const owner = intruderOwner(i, live.map((s) => s.taskKey).filter((k): k is string => !!k), projects.map((p) => p.slug));
const project = owner.slug ? projects.find((p) => p.slug === owner.slug) : null;
const agents = live.filter((s) => (owner.taskKey ? s.taskKey === owner.taskKey : project ? s.projectId === project.id : false));
const who = owner.taskKey ?? owner.slug ?? m("неизвестно чей");
await alertAdmins(
db,
`guard:${c.name}:${c.id.slice(0, 12)}`,
m("🛡 Контейнер {name} ({who}) занял {what} платформы — остановлен, не удалён. {agents}", {
name: c.name,
who,
what,
agents: agents.length ? m("Агенту сказано перенести его на другой порт.") : m("Живого агента не нашли."),
}),
log,
);
for (const s of agents) {
await sendToSession(
db,
s.id,
`Платформа остановила твой контейнер ${c.name}: он занял ${what} самой Peppa FACTORY — из-за этого сайт платформы показывал твоё приложение. ` +
`Подними его заново на порту от 18000 (например, -p 127.0.0.1:18300:<порт приложения>), без меток Traefik на домены платформы. ` +
`Порты 3000–3199 и домены платформы не используй никогда.`, // i18n-ignore
).catch((e) => log(`domain guard: tell #${s.id}: ${(e as Error).message}`));
}
}
return stopped;
}
interface PublicState {
bad: boolean;
since?: string;
/** Foreign answers in a row; two make an episode (one could be a redeploy blip). */
strikes?: number;
}
/** The public address must answer Peppa's /api/health; one message when it stops, one when back. */
export async function publicHealthTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<boolean | null> {
const log = o.log ?? (() => {});
const explicit = process.env.PEPPA_PUBLIC_HEALTH_URL;
const web = process.env.PEPPA_WEB_URL ?? "";
let host = "";
try {
host = new URL(web).hostname;
} catch {}
if (!explicit && (!host || host === "localhost" || host === "127.0.0.1")) return null;
const url = explicit ?? `${web.replace(/\/$/, "")}/api/health`;
let ok = false;
let why = "";
try {
const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache" } });
const body = await res.text();
// 5xx: the web is down or restarting (Cloudflare 502/530) — the port check handles that.
if (res.status >= 500 && !isPeppaHealth(body)) return null;
ok = isPeppaHealth(body);
if (!ok) why = `HTTP ${res.status}: ${body.replace(/\s+/g, " ").slice(0, 120)}`;
} catch (e) {
// Network trouble is the port check's business (PEP-168); here — only "someone else answers".
log(`domain guard: public health: ${(e as Error).message}`);
return null;
}
const key = "guard.public";
const prev = (await getSetting<PublicState>(db, key)) ?? { bad: false };
const now = (o.now ?? new Date()).toISOString();
if (!ok && !prev.bad) {
const strikes = (prev.strikes ?? 0) + 1;
if (strikes < 2) {
await setSetting(db, key, { bad: false, strikes } satisfies PublicState);
return ok;
}
await setSetting(db, key, { bad: true, since: now } satisfies PublicState);
await alertAdmins(db, `guard:public:${now}`, m("🛡 {url} отвечает не Peppa FACTORY — адрес перехвачен. Ответ: {why}", { url, why }), log);
} else if (ok && prev.strikes) {
await setSetting(db, key, { bad: false } satisfies PublicState);
} else if (ok && prev.bad) {
await setSetting(db, key, { bad: false } satisfies PublicState);
await alertAdmins(db, `guard:public:back:${now}`, m("✅ {url} снова отвечает Peppa FACTORY.", { url }), log);
}
return ok;
}
/** PEP-189: both checks; `PEPPA_DOMAIN_GUARD=off` disables. Called about once a minute. */
export async function domainGuardTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<GuardResult> {
if (process.env.PEPPA_DOMAIN_GUARD === "off") return { stopped: [], publicOk: null };
const stopped = await containerGuardTick(db, o);
const publicOk = await publicHealthTick(db, o);
return { stopped, publicOk };
}

View File

@ -56,6 +56,7 @@ export * from "./agent-relay.ts";
export * from "./chats.ts";
export * from "./limit-delay.ts";
export * from "./platform-delays.ts";
export * from "./domain-guard.ts";
export * from "./pipeline-guard.ts";
export * from "./pause.ts";
export * from "./pick-question.ts";

View File

@ -31,6 +31,7 @@ import * as tmux from "./tmux.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, recordLimit } from "./limits.ts";
import { limitDelay, limitOver } from "./limit-delay.ts";
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
import { domainGuardTick } from "./domain-guard.ts";
import { killRunner, resumeSession, stopSession } from "./sessions.ts";
import { hostTick } from "./hosts.ts";
import { getProjectPause, injectionDigestTick, getSubscription, isUsable, pausedProjectIds, reportPlatformError, setProjectPause } from "@peppa/core";
@ -335,6 +336,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
await reviewCardTick(db, { log }).catch(failed(db, log, "review cards failed"));
// PEP-150: checks that have not started for too long — a delay, not a question to the owner.
await checksQueueTick(db, { stuckMin: (await getWatchdogSettings(db)).checksStuckMin, log }).catch(failed(db, log, "checks queue failed"));
// PEP-189: no container takes the platform's port or domain; the public address answers Peppa.
await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed"));
}
// Daily copy of the SQLite database (PEP-36); a no-op until a day has passed.
await backupDb(db, { log }).catch(failed(db, log, "backup failed"));

View File

@ -0,0 +1,13 @@
import type { Dict } from "../index.ts";
// PEP-189: the watchdog keeps the platform's port and domains to itself.
export const domainGuard: Dict = {
"порт {port}": "port {port}",
"адрес {host}": "address {host}",
"неизвестно чей": "owner unknown",
"🛡 Контейнер {name} ({who}) занял {what} платформы — остановлен, не удалён. {agents}": "🛡 Container {name} ({who}) took the platform's {what} — stopped, not removed. {agents}",
"Агенту сказано перенести его на другой порт.": "The agent was told to move it to another port.",
"Живого агента не нашли.": "No live agent found.",
"🛡 {url} отвечает не Peppa FACTORY — адрес перехвачен. Ответ: {why}": "🛡 {url} is not answered by Peppa FACTORY — the address is taken over. Answer: {why}",
"✅ {url} снова отвечает Peppa FACTORY.": "✅ {url} is answered by Peppa FACTORY again.",
};

View File

@ -20,5 +20,6 @@ import { capacity } from "./capacity.ts";
import { untrusted } from "./untrusted.ts";
import { mcpGuide } from "./mcp-guide.ts";
import { subscriptionRequest } from "./subscription-request.ts";
import { domainGuard } from "./domain-guard.ts";
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest };
export const en: Dict = { ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard };

View File

@ -9,6 +9,7 @@
# whose target differs from its source (/peppa/run, /peppa/home) is mapped back in argv and env.
# Each run is logged to $MOCK_DOCKER_STATE/runs.jsonl (name, image, mounts, env names, argv).
# `docker rm -f <name>` drops containers/<name>; MOCK_DOCKER_RUNNER_FAIL=1 fails a runner run.
# PEP-189: `docker ps` prints $st/ps, `docker stop` removes its row and appends to $st/stopped.
set -uo pipefail
# Called through symlinks (a `docker` on PATH): resolve to this file to find the repo.
_src="$0"; while [[ -L "$_src" ]]; do _l="$(readlink "$_src")"; [[ "$_l" == /* ]] && _src="$_l" || _src="$(dirname "$_src")/$_l"; done
@ -69,6 +70,13 @@ case "$1" in
[[ -f "$st/containers/$c" ]] || { echo "Error: No such object: $c" >&2; exit 1; }
cat "$st/containers/$c" ;;
version) echo "27.3.1-mock" ;;
ps) # PEP-189: docker ps … --format '{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}' — rows of $st/ps (that format)
[[ -n "${MOCK_DOCKER_PS_FAIL:-}" ]] && { echo "Cannot connect to the Docker daemon" >&2; exit 1; }
[[ -f "$st/ps" ]] && cat "$st/ps"; exit 0 ;;
stop) # docker stop [-t N] <id|name> — drops the row from $st/ps, logs to $st/stopped
c="${@: -1}"
[[ -f "$st/ps" ]] && grep -q -E "^$c | $c " "$st/ps" || { echo "Error response from daemon: No such container: $c" >&2; exit 1; }
grep -v -E "^$c | $c " "$st/ps" > "$st/ps.tmp"; mv "$st/ps.tmp" "$st/ps"; echo "$c" >> "$st/stopped"; echo "$c" ;;
rm) # docker rm -f <name>
c="${@: -1}"
[[ -f "$st/containers/$c" ]] || { echo "Error response from daemon: No such container: $c" >&2; exit 1; }

View File

@ -0,0 +1,163 @@
// PEP-189: containers that take the platform's port or domain are stopped (not removed); the
// superadmin hears once, the agent whose container it is — to move it; the public address must
// answer Peppa's /api/health.
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs";
import { createServer, type Server } from "node:http";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, beforeEach, describe, test } from "node:test";
import { core, db, runner, teardown } from "./helpers.ts";
import { settings, telegramOutbox, users } from "@peppa/db";
import { eq, like, sql } from "drizzle-orm";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const state = mkdtempSync(join(tmpdir(), "mock-docker-guard-"));
process.env.PEPPA_DOCKER_BIN = join(ROOT, "packages/testkit/bin/mock-docker");
process.env.MOCK_DOCKER_STATE = state;
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const logs: string[] = [];
const log = (m: string) => void logs.push(m);
const row = (id: string, name: string, ports: string, labels = "") => [id, name, ports, labels].join("\t");
const ps = (...rows: string[]) => writeFileSync(join(state, "ps"), rows.map((r) => `${r}\n`).join(""));
const stopped = () => (existsSync(join(state, "stopped")) ? readFileSync(join(state, "stopped"), "utf8").trim().split("\n").filter(Boolean) : []);
const ADMIN_CHAT = 9301;
async function adminMessages(): Promise<string[]> {
const rows = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "guard:%")).orderBy(telegramOutbox.id);
return rows.map((r) => String(r.params.text));
}
describe("pure rules", () => {
const rules = core.guardRules({ PEPPA_WEB_URL: "https://peppa.telecom.quest", BUGSINK_URL: "https://bugsink.telecom.quest", GITEA_URL: "https://git.telecom.quest" } as NodeJS.ProcessEnv);
test("reserved ports and platform domains", () => {
assert.ok(rules.ports.includes(3100) && rules.ports.includes(3180));
assert.deepEqual(rules.hosts, ["bugsink.telecom.quest", "git.telecom.quest", "peppa.telecom.quest"]);
});
test("published ports and Traefik hosts are parsed", () => {
assert.deepEqual(core.publishedPorts("3000/tcp, 127.0.0.1:3100->3100/tcp, [::]:80->80/tcp"), [3100, 80]);
assert.deepEqual(core.traefikHosts("a=b,traefik.http.routers.x.rule=Host(`Peppa.telecom.quest`,`y.telecom.quest`),traefik.enable=true"), ["peppa.telecom.quest", "y.telecom.quest"]);
});
test("own containers, other ports and project hosts are left alone", () => {
const list = core.parseDockerPs(
[
row("a1", "peppa-bugsink", "127.0.0.1:3180->8000/tcp"),
row("a2", "brendmanager-prod-web-1", "3000/tcp", "traefik.http.routers.b.rule=Host(`brendmanager-prod.telecom.quest`)"),
row("a3", "ia-2-smoke", "3000/tcp, 127.0.0.1:3100->3100/tcp"),
row("a4", "x-prod-web-1", "", "com.docker.compose.project=x-prod,traefik.http.routers.x.rule=Host(`peppa.telecom.quest`)"),
row("a5", "peppa-s12", "127.0.0.1:18300->3000/tcp"),
].join("\n"),
);
const found = core.findIntruders(list, rules);
assert.deepEqual(found.map((i) => i.container.name), ["ia-2-smoke", "x-prod-web-1"]);
assert.deepEqual(found[0]!.ports, [3100]);
assert.deepEqual(found[1]!.hosts, ["peppa.telecom.quest"]);
assert.equal(found[1]!.composeProject, "x-prod");
assert.deepEqual(core.intruderOwner(found[0]!, ["IA-2", "IA-20"], ["ii-assistent"]), { taskKey: "IA-2" });
assert.deepEqual(core.intruderOwner(found[1]!, [], ["x"]), { slug: "x" });
});
test("Peppa's health answer is recognised", () => {
assert.ok(core.isPeppaHealth(JSON.stringify({ ok: true, boot: "c7a2-x", services: [] })));
assert.ok(!core.isPeppaHealth("<!doctype html><title>Redirecting...</title>"));
});
});
describe("watchdog guard", () => {
let server: Server;
let answer = { status: 200, body: "" };
let base = "";
before(async () => {
const u = await core.upsertUserFromGitea(db, { id: 9311, login: "mock-guard-admin" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, u.id));
await core.setAllowedLogins(db, ["mock-guard-admin"]);
await core.setPlatformAdmins(db, ["mock-guard-admin"]);
server = createServer((_q, r) => {
r.writeHead(answer.status, { "content-type": "text/plain" });
r.end(answer.body);
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
process.env.PEPPA_DOMAIN_GUARD = "on";
});
beforeEach(async () => {
await db.delete(telegramOutbox);
db.run(sql`delete from settings where key = 'guard.public'`);
writeFileSync(join(state, "stopped"), "");
delete process.env.PEPPA_PUBLIC_HEALTH_URL;
});
after(async () => {
process.env.PEPPA_DOMAIN_GUARD = "off";
server.close();
await teardown();
});
test("a container on the platform's port is stopped once; the superadmin hears once", async () => {
ps(row("c0ffee", "peppa-bugsink", "127.0.0.1:3180->8000/tcp"), row("deadbeef", "ia-2-smoke", "127.0.0.1:3100->3100/tcp"), row("f00d", "dika-prod-web-1", "3000/tcp"));
const r = await runner.domainGuardTick(db, { log });
assert.deepEqual(r.stopped.map((i) => i.container.name), ["ia-2-smoke"]);
assert.deepEqual(stopped(), ["deadbeef"], "stopped by id, not removed");
assert.ok(!readFileSync(join(state, "calls.log"), "utf8").includes("docker rm"));
const msgs = await adminMessages();
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /ia-2-smoke.*3100.*остановлен, не удалён/);
// Gone now: the next tick finds nothing and says nothing.
await runner.domainGuardTick(db, { log });
assert.deepEqual(stopped(), ["deadbeef"]);
assert.equal((await adminMessages()).length, 1);
});
test("docker unavailable — nothing happens, no throw", async () => {
process.env.MOCK_DOCKER_PS_FAIL = "1";
try {
const r = await runner.domainGuardTick(db, { log });
assert.deepEqual(r.stopped, []);
} finally {
delete process.env.MOCK_DOCKER_PS_FAIL;
}
});
test("off switch", async () => {
ps(row("beef01", "ia-3-smoke", "127.0.0.1:3100->3100/tcp"));
process.env.PEPPA_DOMAIN_GUARD = "off";
try {
await runner.domainGuardTick(db, { log });
assert.deepEqual(stopped(), []);
} finally {
process.env.PEPPA_DOMAIN_GUARD = "on";
ps();
}
});
test("public address answered by someone else: one message after two strikes, one when back; 5xx ignored", async () => {
ps();
process.env.PEPPA_PUBLIC_HEALTH_URL = `${base}/api/health`;
answer = { status: 302, body: "<title>Redirecting...</title>" };
assert.equal(await runner.publicHealthTick(db, { log }), false);
assert.equal((await adminMessages()).length, 0, "one foreign answer could be a blip");
await runner.publicHealthTick(db, { log });
await runner.publicHealthTick(db, { log });
let msgs = await adminMessages();
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /не Peppa FACTORY/);
answer = { status: 502, body: "Bad gateway" };
assert.equal(await runner.publicHealthTick(db, { log }), null);
answer = { status: 200, body: JSON.stringify({ ok: true, boot: "x", services: [] }) };
assert.equal(await runner.publicHealthTick(db, { log }), true);
msgs = await adminMessages();
assert.equal(msgs.length, 2);
assert.match(msgs[1]!, /снова отвечает Peppa FACTORY/);
const st = await db.select().from(settings).where(eq(settings.key, "guard.public"));
assert.equal((st[0]!.value as { bad: boolean }).bad, false);
});
test("public check is skipped for a local web address", async () => {
assert.equal(await runner.publicHealthTick(db, { log }), null);
});
});

View File

@ -35,6 +35,9 @@ Object.assign(process.env, {
PEPPA_PICK_QUESTION: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.
PEPPA_WEB_PROBE: "off",
// PEP-189: the guard runs `docker stop` — never against the real docker of the machine running tests;
// domain-guard.test.ts turns it on with mock-docker.
PEPPA_DOMAIN_GUARD: "off",
});
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });

View File

@ -165,6 +165,16 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
- PR открывай MCP-инструментом `peppa.open_pull_request` (ссылку — в `update_task` как `pr_url`).
- Не ищи токены и не пытайся выйти за рабочую копию — это граница безопасности, а не ошибка.
### Порты и домены платформы — не твои
Peppa FACTORY живёт на той же машине. Контейнер, который занял её порт или домен, подменяет
сайт платформы для всех пользователей — так уже было.
- Для локальных проверок (`docker run -p …`, dev-сервер) бери порт **от 18000**: `-p 127.0.0.1:18300:<порт приложения>`.
- Порты **3000–3199** на хосте не публикуй никогда (3100 — сама Peppa, 3180 — Bugsink, 3000 — Gitea).
- Метки Traefik ставь только на свои адреса `<slug>-pr<N>|staging|prod.telecom.quest` (их пишет `peppa-deploy.sh`); домены платформы (peppa., git., bugsink.) не трогай.
- Вачдог останавливает контейнер, который нарушил это правило, и пишет тебе. Подними его заново на разрешённом порту.
## Спецификации — сценарии в формате Gherkin
Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а