// PEP-201: the watchdog watches DNS and the internet from the Peppa host. Every few minutes each // important host is resolved by the system resolver and by a fallback one (1.1.1.1), and its // addresses are tried on port 443. A state that holds for two checks in a row and differs from the // last announced one goes to the platform's Telegram channel (no channel — to the superadmins). // glossary-ignore-file: messages here are for the superadmin. import { Resolver, lookup } from "node:dns/promises"; import net from "node:net"; import { alertAdmins, getPlatformChannel, getSetting, postToChannel, setSetting } from "@peppa/core"; import { m } from "@peppa/shared/i18n"; import type { Db } from "@peppa/db"; export type HostState = "ok" | "dns" | "blocked" | "down"; export interface HostProbe { host: string; state: HostState; /** System resolver's addresses. */ system: string[]; /** Fallback resolver's addresses that answered. */ working: string[]; } export interface NetProbes { systemLookup(host: string): Promise; fallbackLookup(host: string): Promise; reachable(ip: string, port: number): Promise; } export const DEFAULT_NET_HOSTS = ["sign.aitu.uz", "chatgpt.com", "api.anthropic.com", "api.telegram.org", "git.telecom.quest", "registry.npmjs.org"]; export const NET_WATCH_EVERY_MS = 5 * 60_000; const STATE = "net.watch"; interface WatchState { /** Announced state per host, and since when. */ hosts: Record; internet?: { down: boolean; since: string; pending?: boolean }; } export const netWatchHosts = () => (process.env.PEPPA_NET_WATCH_HOSTS ?? "").split(",").map((s) => s.trim()).filter(Boolean).concat(process.env.PEPPA_NET_WATCH_HOSTS ? [] : DEFAULT_NET_HOSTS); export const realNetProbes: NetProbes = { async systemLookup(host) { return (await lookup(host, { all: true, family: 4 }).catch(() => [])).map((a) => a.address); }, async fallbackLookup(host) { const servers = (process.env.PEPPA_FALLBACK_DNS ?? "1.1.1.1,1.0.0.1").split(",").map((s) => s.trim()).filter((s) => s && s !== "off"); if (!servers.length) return []; const r = new Resolver({ timeout: 4_000, tries: 2 }); r.setServers(servers); return r.resolve4(host).catch(() => []); }, reachable(ip, port) { return new Promise((resolve) => { const s = net.connect({ host: ip, port, timeout: 5_000 }); const done = (ok: boolean) => (s.destroy(), resolve(ok)); s.once("connect", () => done(true)); s.once("timeout", () => done(false)); s.once("error", () => done(false)); }); }, }; export async function probeHost(host: string, p: NetProbes): Promise { const system = await p.systemLookup(host); const sysOk = (await Promise.all(system.slice(0, 3).map((ip) => p.reachable(ip, 443)))).some(Boolean); if (sysOk) return { host, state: "ok", system, working: [] }; const fallback = (await p.fallbackLookup(host)).filter((ip) => !system.includes(ip)).slice(0, 3); const ok = await Promise.all(fallback.map((ip) => p.reachable(ip, 443))); const answered = fallback.filter((_, i) => ok[i]); if (answered.length) return { host, state: system.length ? "blocked" : "dns", system, working: answered }; return { host, state: "down", system, working: [] }; } const ago = (since: string, now: Date) => Math.max(1, Math.round((now.getTime() - Date.parse(since)) / 60_000)); export function describeProbe(p: HostProbe): string { switch (p.state) { case "ok": return m("✅ {host} снова открывается.", { host: p.host }); case "dns": return m("🌐 {host}: системный DNS не отвечает, запасной DNS (1.1.1.1) даёт рабочие адреса {ips}. Смените DNS на 1.1.1.1 в настройках сети.", { host: p.host, ips: p.working.join(", ") }); case "blocked": return m("🌐 {host}: системный DNS отдаёт недоступные адреса {bad}, рабочие — {ips} (их даёт 1.1.1.1). Смените DNS на 1.1.1.1 в настройках сети или напишите провайдеру.", { host: p.host, bad: p.system.join(", "), ips: p.working.join(", ") }); case "down": return m("🌐 {host} недоступен ни по одному адресу.", { host: p.host }); } } async function announce(db: Db, key: string, text: string, log: (m: string) => void): Promise { const channel = await getPlatformChannel(db); if (await postToChannel(db, "services", `mon:ch:${key}`, text, channel)) { log(`net watch: ${text}`); return; } await alertAdmins(db, `mon:${key}`, text, log); } /** One check of every host; announces states that held for two checks. */ export async function netWatchTick(db: Db, o: { now?: Date; probes?: NetProbes; hosts?: string[]; log?: (m: string) => void } = {}): Promise { if (process.env.PEPPA_NET_WATCH === "off") return []; const now = o.now ?? new Date(); const log = o.log ?? (() => {}); const probes = o.probes ?? realNetProbes; const results = await Promise.all((o.hosts ?? netWatchHosts()).map((h) => probeHost(h, probes))); const st = (await getSetting(db, STATE)) ?? { hosts: {} }; const iso = now.toISOString(); const stamp = now.getTime(); // No host answers at all: one "no internet" message instead of one per host. const allDown = results.length > 0 && results.every((r) => r.state === "down"); const inet = st.internet ?? { down: false, since: iso }; if (allDown !== inet.down) { if (inet.pending === allDown) { await announce(db, `net:inet:${allDown ? "down" : "up"}:${stamp}`, allDown ? m("🌐 С сервера Peppa FACTORY нет интернета: не открывается ни один из адресов {hosts}.", { hosts: results.map((r) => r.host).join(", ") }) : m("✅ Интернет на сервере Peppa FACTORY снова есть — не было {n} мин.", { n: ago(inet.since, now) }), log); st.internet = { down: allDown, since: iso }; } else st.internet = { ...inet, pending: allDown }; } else st.internet = { down: inet.down, since: inet.since }; for (const r of results) { const prev = st.hosts[r.host] ?? { state: "ok" as HostState, since: iso }; if (r.state === prev.state) { st.hosts[r.host] = { state: prev.state, since: prev.since }; continue; } if (prev.pending !== r.state) { st.hosts[r.host] = { ...prev, pending: r.state }; continue; } // Hosts that are down while the whole internet is down are covered by the message above. const quiet = allDown || (r.state === "ok" && prev.state === "down" && inet.down); if (!quiet) { const text = r.state === "ok" ? `${describeProbe(r)} ${m("Не открывался {n} мин.", { n: ago(prev.since, now) })}` : describeProbe(r); await announce(db, `net:${r.host}:${r.state}:${stamp}`, text, log); } st.hosts[r.host] = { state: r.state, since: iso }; } await setSetting(db, STATE, st); return results; }