import { execFile } from "node:child_process"; import type { FrpSettings } from "./frp"; import { portAllowed } from "./frp"; export { parseFrpsIni, portAllowed } from "./frp"; /** * The central server (AGENT-1.0-PLAN §6): the `check-ports` job after an install. Are the new * tunnel's ports allowed by frps, open, and bound to 127.0.0.1 only? frps's config is found and * read by ./frp.ts (INI or TOML, wherever it is). */ /** Listening TCP sockets from `ss -ltnH`: port → local addresses. */ export function parseSs(text: string): Map { const out = new Map(); for (const line of text.split("\n")) { const cols = line.trim().split(/\s+/); const local = cols[3]; if (!local) continue; const i = local.lastIndexOf(":"); const port = Number(local.slice(i + 1)); const addr = local.slice(0, i).replace(/^\[|\]$/g, "").replace(/%.*$/, ""); if (!Number.isFinite(port)) continue; out.set(port, [...(out.get(port) ?? []), addr]); } return out; } const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]); export interface PortCheck { port: number; allowed: boolean; listening: boolean; loopbackOnly: boolean; ok: boolean; } export function checkPorts( ports: number[], frps: Pick | null, listening: Map, configPath: string | null = null, ): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } { const warnings: string[] = []; if (!frps) warnings.push(configPath ? `frps's config isn't at ${configPath} (Hub → the central server → frp config).` : "frps's config wasn't found (Hub → the central server → frp config: set where it is)."); const bind = frps?.proxyBindAddr ?? null; if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 (frps.toml: proxyBindAddr = "127.0.0.1") in ${configPath ?? "frps's config"}.`); const results = ports.map((port) => { const addrs = listening.get(port) ?? []; const allowed = portAllowed(port, frps?.allowPorts ?? null); const loopbackOnly = addrs.length > 0 && addrs.every((a) => LOOPBACK.has(a)); return { port, allowed, listening: addrs.length > 0, loopbackOnly, ok: allowed && addrs.length > 0 && loopbackOnly }; }); for (const r of results) { if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`); else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`); else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1 (${(listening.get(r.port) ?? []).join(", ")}).`); } return { ports: results, proxyBindAddr: bind, configPath, warnings }; } export function listeningNow(): Promise> { return new Promise((resolve) => { execFile("ss", ["-ltnH"], { timeout: 10_000 }, (err, stdout) => resolve(err ? new Map() : parseSs(String(stdout)))); }); }