// 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 { 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 { 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(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 { 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 }; }