peppa/packages/runner/src/domain-guard.ts

212 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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, edgeConfig, findIntruders, getSetting, guardRules, intruderOwner, isPeppaHealth, listProjects, listSessions, observeRemindMin, parseDockerPs, probeWebPort, 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} самой FORGE — из-за этого сайт платформы показывал твоё приложение. ` +
`Подними его заново на порту от 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; probe?: () => Promise<boolean | null> } = {}): 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 the way in is broken (Cloudflare 502/530). The web itself is the port
// check's business (PEP-168); the way in — publicPathCheck (PEP-245). Not "someone else answers".
if (res.status >= 500 && !isPeppaHealth(body)) {
await publicPathCheck(db, { url, ok: false, what: cloudflareWhat(res.status, body) }, o);
return null;
}
ok = isPeppaHealth(body);
if (!ok) why = `HTTP ${res.status}: ${body.replace(/\s+/g, " ").slice(0, 120)}`;
} catch (e) {
log(`domain guard: public health: ${(e as Error).message}`);
await publicPathCheck(db, { url, ok: false, what: (e as Error).name === "TimeoutError" ? "timeout" : (e as Error).message.slice(0, 80) }, o);
return null;
}
if (ok) await publicPathCheck(db, { url, ok: true, what: "" }, o);
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} отвечает не FORGE — адрес перехвачен. Ответ: {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} снова отвечает FORGE.", { url }), log);
}
return ok;
}
/** «HTTP 530 · Cloudflare 1033» — a short name of a broken-way answer for the superadmin. */
function cloudflareWhat(status: number, body: string): string {
const code = /error code:?\s*(\d{3,4})/i.exec(body)?.[1] ?? /Error (\d{4})/.exec(body)?.[1];
const tunnel = /Cloudflare Tunnel error/i.test(body);
return [`HTTP ${status}`, code ? `Cloudflare ${code}` : tunnel ? "Cloudflare Tunnel error" : null].filter(Boolean).join(" · ");
}
interface PathState {
down: boolean;
/** Bad answers in a row before the episode (two make it). */
strikes?: number;
since?: string;
lastAt?: string;
reminders?: number;
}
export const PATH_KEY = "guard.path";
/**
* PEP-245: the public address does not open from outside while the web on the server answers —
* the way in (Cloudflare → Mac → SSH tunnel → server, or the server's own tunnel) is broken.
* Two bad checks in a row → one message with the reason, a reminder every PEPPA_OBSERVE_REMIND_MIN,
* «opens again, downtime N min» when back. The web itself being down is checkServices' business.
*/
export async function publicPathCheck(
db: Db,
r: { url: string; ok: boolean; what: string },
o: { now?: Date; log?: (m: string) => void; probe?: () => Promise<boolean | null> } = {},
): Promise<void> {
const log = o.log ?? (() => {});
const now = o.now ?? new Date();
const prev = (await getSetting<PathState>(db, PATH_KEY)) ?? { down: false };
if (r.ok) {
if (prev.down && prev.since) {
const min = Math.max(1, Math.round((now.getTime() - Date.parse(prev.since)) / 60_000));
await alertAdmins(db, `guard:path:${prev.since}:back`, m("✅ {url} снова открывается снаружи. Простой — {min} мин.", { url: r.url, min }), log);
}
if (prev.down || prev.strikes) await setSetting(db, PATH_KEY, { down: false } satisfies PathState);
return;
}
// Only when the web inside answers: otherwise the outage is the web's, not the way's.
if ((await (o.probe ?? probeWebPort)()) !== true) return;
if (!prev.down) {
const strikes = (prev.strikes ?? 0) + 1;
if (strikes < 2) {
await setSetting(db, PATH_KEY, { down: false, strikes } satisfies PathState);
return;
}
const since = now.toISOString();
await setSetting(db, PATH_KEY, { down: true, since, lastAt: since, reminders: 0 } satisfies PathState);
await alertAdmins(db, `guard:path:${since}`, m("🌐 {url} не открывается снаружи, хотя FORGE на сервере работает: {reason}. Ответ: {what}", { url: r.url, reason: pathReason(), what: r.what }), log);
return;
}
const remindMs = observeRemindMin() * 60_000;
if (!remindMs || !prev.since || !prev.lastAt || now.getTime() - Date.parse(prev.lastAt) < remindMs) return;
const n = (prev.reminders ?? 0) + 1;
const min = Math.round((now.getTime() - Date.parse(prev.since)) / 60_000);
await setSetting(db, PATH_KEY, { ...prev, lastAt: now.toISOString(), reminders: n } satisfies PathState);
await alertAdmins(db, `guard:path:${prev.since}:r${n}`, m("🌐 {url} всё ещё не открывается снаружи — {min} мин: {reason}. Ответ: {what}", { url: r.url, min, reason: pathReason(), what: r.what }), log);
}
/** Where the way in breaks: the server's own tunnel (PEP-231 done) or the Mac. */
function pathReason(): string {
return edgeConfig()
? m("туннель адресов на сервере (peppa-cloudflared) не на связи с Cloudflare")
: m("нет связи Mac → сервер — адреса пока идут через Mac (туннель launchd quest.telecom.peppa.tunnel)");
}
/** 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 };
}