import { execFile } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { agent } from "@crosscode/contracts"; import { paths } from "./paths"; /** * frp's config on this server (agent 1.4.0): frps's on the central server, frpc's on a church * server. The agent finds the file itself (the path set from the Hub, else the systemd unit's * `-c`, else a usual place), reads frp's two formats (INI and TOML), hides secret values before * anything leaves the server, and writes a new file from the Hub the careful way: secrets put * back, `verify`, a backup, a restart, and the old file back when the service doesn't come up. */ export type FrpService = "frps" | "frpc"; export type FrpSource = (typeof agent.FRP_CONFIG_SOURCES)[number]; export const serviceFor = (mode: agent.AgentMode): FrpService => (mode === "central" ? "frps" : "frpc"); // ─── Where the file is ──────────────────────────────────────────────────────── /** frps.toml, frpc.ini, frps-main.toml … */ const FRP_FILE = /^frp[A-Za-z0-9._-]*\.(ini|toml)$/; const rememberedFile = () => path.join(paths.stateDir, "frp.json"); /** The path set from the Hub (an `frp-read` with a path), if any. */ export function rememberedPath(): string | null { try { const p = JSON.parse(fs.readFileSync(rememberedFile(), "utf8")).path; return typeof p === "string" && path.isAbsolute(p) && FRP_FILE.test(path.basename(p)) ? p : null; } catch { return null; } } export function rememberPath(p: string): void { fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 }); fs.writeFileSync(rememberedFile(), `${JSON.stringify({ path: p, at: new Date().toISOString() })}\n`, { mode: 0o600 }); } /** `-c `, `-c=`, `--config ` or `--config=` in a command line. */ export function configFromCommand(argv: string): string | null { const parts = argv.trim().split(/\s+/); for (let i = 0; i < parts.length; i++) { const a = parts[i]!; const eq = /^(?:-c|--config)=(.+)$/.exec(a); if (eq) return eq[1]!; if ((a === "-c" || a === "--config") && parts[i + 1]) return parts[i + 1]!; } return null; } /** The config and the binary from `systemctl show -p ExecStart --value` ("{ path=… ; argv[]=… ; … }"). */ export function parseExecStart(text: string): { config: string | null; bin: string | null } { const argv = /argv\[\]=([^;]*)/.exec(text)?.[1]?.trim() ?? text.trim(); const bin = argv.split(/\s+/)[0] || null; return { config: configFromCommand(argv), bin: bin && bin.startsWith("/") ? bin : null }; } function execText(cmd: string, args: string[], timeout = 10_000): Promise<{ ok: boolean; out: string; err: string; missing: boolean }> { return new Promise((resolve) => { execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({ ok: !err, out: String(stdout ?? ""), err: String(stderr ?? "") || (err ? err.message : ""), missing: (err as NodeJS.ErrnoException | null)?.code === "ENOENT", })); }); } async function fromSystemd(service: FrpService): Promise<{ config: string | null; bin: string | null }> { const r = await execText("systemctl", ["show", service, "-p", "ExecStart", "--value"]); return r.ok ? parseExecStart(r.out) : { config: null, bin: null }; } /** Where frp is usually kept, in the order the agent looks. */ export function usualPlaces(service: FrpService): string[] { const dirs = ["/etc/frp", `/etc/${service}`, "/usr/local/etc/frp", "/usr/local/frp", "/opt/frp", `/opt/${service}`, "/root/frp"]; return dirs.flatMap((d) => [`${d}/${service}.toml`, `${d}/${service}.ini`]); } export interface FoundConfig { path: string | null; source: FrpSource | null; /** frps / frpc as the systemd unit runs it (for `verify`), else the name on PATH. */ bin: string; looked: string[]; } const exists = (f: string) => { try { return fs.statSync(f).isFile(); } catch { return false; } }; let cache: { at: number; mode: agent.AgentMode; found: FoundConfig } | null = null; /** The config this server's frp uses. The Hub's path wins (even when the file isn't there: the Hub then says so). */ export async function findConfig(mode: agent.AgentMode, opts: { fresh?: boolean } = {}): Promise { if (!opts.fresh && cache && cache.mode === mode && Date.now() - cache.at < 5 * 60_000) return cache.found; const service = serviceFor(mode); const unit = await fromSystemd(service); const bin = unit.bin ?? service; const looked: string[] = []; let found: FoundConfig | null = null; const hub = rememberedPath(); // The old setting (agent 1.0–1.3) still works, for a server that set it in the unit. const env = mode === "central" ? process.env.CROSSCODE_FRPS_INI : process.env.CROSSCODE_FRPC_INI; if (hub) found = { path: hub, source: "hub", bin, looked }; else if (env) found = { path: env, source: "hub", bin, looked }; else { const candidates: Array<[string, FrpSource]> = []; if (unit.config) candidates.push([unit.config, "systemd"]); for (const p of usualPlaces(service)) candidates.push([p, "usual-place"]); for (const [p, source] of candidates) { looked.push(p); if (exists(p)) { found = { path: p, source, bin, looked: [] }; break; } } } const result = found ?? { path: null, source: null, bin, looked: looked.slice(0, 20) }; cache = { at: Date.now(), mode, found: result }; return result; } export function forgetFound(): void { cache = null; } // ─── Reading INI and TOML ───────────────────────────────────────────────────── export type FrpFormat = "ini" | "toml"; export const formatOf = (file: string, text = ""): FrpFormat => (file.endsWith(".toml") ? "toml" : file.endsWith(".ini") ? "ini" : /^\s*\[common\]/m.test(text) ? "ini" : "toml"); interface Line { /** `[common]`, `[[proxies]]`: the header the line is under ("" before any), with how many came before it. */ section: string; sectionIndex: number; key: string; /** The value as written, after `=` (quotes kept, comments after it dropped for TOML). */ raw: string; /** The value without quotes. */ value: string; /** Where `raw` starts and ends in the line. */ start: number; end: number; } function unquote(v: string): string { const t = v.trim(); if ((t.startsWith('"') && t.endsWith('"') && t.length >= 2) || (t.startsWith("'") && t.endsWith("'") && t.length >= 2)) return t.slice(1, -1); return t; } /** Each `key = value` line, with the section it's in. */ export function lines(text: string, format: FrpFormat): Array { let section = ""; const seen = new Map(); let sectionIndex = 0; return text.split("\n").map((rawLine) => { const line = rawLine.replace(/\r$/, ""); const t = line.trim(); if (!t || t.startsWith("#") || t.startsWith(";")) return null; const header = /^(\[\[?[^\]]+\]\]?)\s*(#.*)?$/.exec(t); if (header) { section = header[1]!.replace(/\s+/g, ""); sectionIndex = seen.get(section) ?? 0; seen.set(section, sectionIndex + 1); return null; } const m = /^(\s*)([A-Za-z0-9_.-]+|"[^"]+")(\s*=\s*)(.*)$/.exec(line); if (!m) return null; let raw = m[4]!; if (format === "toml") { // A comment after the value (outside quotes). let q: string | null = null; for (let i = 0; i < raw.length; i++) { const c = raw[i]!; if (q) { if (c === q && raw[i - 1] !== "\\") q = null; continue; } if (c === '"' || c === "'") q = c; else if (c === "#") { raw = raw.slice(0, i); break; } } } raw = raw.replace(/\s+$/, ""); const start = m[1]!.length + m[2]!.length + m[3]!.length; return { section, sectionIndex, key: m[2]!.replace(/"/g, ""), raw, value: unquote(raw), start, end: start + raw.length }; }); } export interface FrpSettings { proxyBindAddr: string | null; allowPorts: string | null; /** Ports frpc's proxies use (remote and local), or frps's own ports (bind, dashboard …). */ usedPorts: number[]; } /** TOML's allowPorts = [{ start = 2000, end = 3000 }, { single = 3001 }] → "2000-3000,3001". */ export function tomlAllowPorts(text: string): string | null { const m = /^\s*allowPorts\s*=\s*\[([\s\S]*?)\]\s*$/m.exec(text); if (!m) return null; const out: string[] = []; for (const obj of m[1]!.matchAll(/\{([^}]*)\}/g)) { const single = /single\s*=\s*(\d+)/.exec(obj[1]!)?.[1]; const start = /start\s*=\s*(\d+)/.exec(obj[1]!)?.[1]; const end = /end\s*=\s*(\d+)/.exec(obj[1]!)?.[1]; if (single) out.push(single); else if (start && end) out.push(`${start}-${end}`); else if (start) out.push(start); } return out.length ? out.join(",") : null; } const PORT_KEYS = /^(remote_?port|remotePort|local_?port|localPort|bind_?port|bindPort|kcp_?bind_?port|kcpBindPort|quic_?bind_?port|quicBindPort|vhost_?http_?port|vhostHTTPPort|vhost_?https_?port|vhostHTTPSPort|dashboard_?port|admin_?port|webServer\.port|port|tcpmux_?httpconnect_?port|tcpmuxHTTPConnectPort)$/; export function parseSettings(text: string, format: FrpFormat): FrpSettings { const all = lines(text, format).filter((l): l is Line => !!l); const used = new Set(); for (const l of all) { if (!PORT_KEYS.test(l.key)) continue; // INI: `remote_port = 6000`; frpc's `local_port` of a proxy is a port on the server too. for (const n of l.value.split(/[,\s]+/)) if (/^\d+$/.test(n)) used.add(Number(n)); } if (format === "ini") { const common = all.filter((l) => l.section === "[common]"); const get = (k: string) => common.find((l) => l.key === k)?.value || null; return { proxyBindAddr: get("proxy_bind_addr"), allowPorts: get("allow_ports"), usedPorts: [...used].sort((a, b) => a - b) }; } const top = all.filter((l) => l.section === ""); return { proxyBindAddr: top.find((l) => l.key === "proxyBindAddr")?.value || null, allowPorts: tomlAllowPorts(text), usedPorts: [...used].sort((a, b) => a - b), }; } /** Keeps the old helper's shape (agent ≤ 1.3 tests and stats). */ export function parseFrpsIni(text: string): { proxyBindAddr: string | null; allowPorts: string | null } { const s = parseSettings(text, "ini"); return { proxyBindAddr: s.proxyBindAddr, allowPorts: s.allowPorts }; } // ─── Secrets ────────────────────────────────────────────────────────────────── /** token, auth.token, dashboard_pwd, webServer.password, oidc client secret, privilege_token … */ const SECRET_KEY = /(token|pwd|passw(or)?d|secret|private_?key|privateKey|credential)/i; export const isSecretKey = (key: string): boolean => SECRET_KEY.test(key); /** A secret key, or an inline table with one in it (auth = { token = "…" }). */ const INLINE_SECRET = /[{,]\s*[A-Za-z0-9_.]*(token|pwd|passw(or)?d|secret|private_?key|credential)[A-Za-z0-9_]*\s*=/i; const isSecretLine = (l: Line): boolean => isSecretKey(l.key) || INLINE_SECRET.test(l.raw); const idOf = (l: Line) => `${l.section}#${l.sectionIndex}/${l.key}`; const nameOf = (l: Line) => (l.section && !l.section.startsWith("[[") && l.section !== "[common]" ? `${l.section.replace(/[[\]]/g, "")}.${l.key}` : l.key); function hiddenRaw(raw: string): string { const t = raw.trim(); if (t.startsWith('"')) return `"${agent.FRP_HIDDEN}"`; if (t.startsWith("'")) return `'${agent.FRP_HIDDEN}'`; return agent.FRP_HIDDEN; } /** The file with secret values replaced, and their names. */ export function hideSecrets(text: string, format: FrpFormat): { content: string; hidden: string[] } { const hidden: string[] = []; const src = text.split("\n"); lines(text, format).forEach((l, i) => { if (!l || !isSecretLine(l) || !l.value) return; const line = src[i]!; src[i] = line.slice(0, l.start) + hiddenRaw(l.raw) + line.slice(l.end); hidden.push(nameOf(l)); }); return { content: src.join("\n"), hidden: [...new Set(hidden)].slice(0, 50) }; } /** * A file from the Hub with the server's secret values put back. Refused when it changes a secret, * or has a hidden value the server's file has no value for. */ export function restoreSecrets(incoming: string, current: string, format: FrpFormat): { ok: true; content: string } | { ok: false; message: string } { const now = new Map(); for (const l of lines(current, format)) if (l && isSecretLine(l)) now.set(idOf(l), l); const src = incoming.split("\n"); const parsed = lines(incoming, format); for (let i = 0; i < parsed.length; i++) { const l = parsed[i]; if (!l || !isSecretLine(l)) continue; const old = now.get(idOf(l)); if (l.value === agent.FRP_HIDDEN) { if (!old) return { ok: false, message: `${nameOf(l)} shows ${agent.FRP_HIDDEN}, but the file on the server has no value for it there. Secrets are set on the server.` }; src[i] = src[i]!.slice(0, l.start) + old.raw + src[i]!.slice(l.end); } else if (l.value && (!old || old.value !== l.value)) { return { ok: false, message: `${nameOf(l)} is a secret: it can't be set or changed from the Hub. Change it on the server.` }; } } return { ok: true, content: src.join("\n") }; } // ─── Read, write ────────────────────────────────────────────────────────────── /** systemd's view of a unit: true / false, or null when there's no systemctl. */ export async function serviceActive(unit: string): Promise { const r = await execText("systemctl", ["is-active", unit]); if (r.missing) return null; return r.out.trim() === "active"; } export interface FrpDeps { /** For tests: systemctl and `frp* verify`. */ exec?: (cmd: string, args: string[]) => Promise<{ ok: boolean; out: string; err: string; missing: boolean }>; wait?: (ms: number) => Promise; } export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise { const service = serviceFor(mode); if (opts.path) { if (exists(opts.path)) rememberPath(opts.path); forgetFound(); } const found = opts.path ? { ...(await findConfig(mode, { fresh: true })), ...(exists(opts.path) ? {} : { path: opts.path, source: "hub" as const }) } : await findConfig(mode, { fresh: true }); const exec = deps.exec ?? execText; const running = await (async () => { const r = await exec("systemctl", ["is-active", service]); return r.missing ? null : r.out.trim() === "active"; })(); const base = { service, path: found.path, source: found.source, serviceRunning: running, readAt: new Date().toISOString() }; let text: string | null = null; if (found.path) { try { const st = fs.statSync(found.path); if (st.size > agent.FRP_CONFIG_MAX) throw new Error(`${found.path} is ${st.size} bytes; the Hub shows files up to ${agent.FRP_CONFIG_MAX}.`); text = fs.readFileSync(found.path, "utf8"); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e; } } if (text === null) { return { ...base, found: false, format: null, content: null, hidden: [], proxyBindAddr: null, allowPorts: null, looked: found.path ? [found.path] : found.looked }; } const format = formatOf(found.path!, text); const settings = parseSettings(text, format); const { content, hidden } = hideSecrets(text, format); return { ...base, found: true, format, content, hidden, proxyBindAddr: service === "frps" ? settings.proxyBindAddr : null, allowPorts: service === "frps" ? settings.allowPorts : null, }; } export interface WriteOutcome { status: agent.JobStatus; message?: string; steps: agent.ReportStep[]; result: Record; } const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, ""); export async function writeConfig(mode: agent.AgentMode, args: { path: string; content: string; restart: boolean }, deps: FrpDeps = {}): Promise { const exec = deps.exec ?? execText; const wait = deps.wait ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); const service = serviceFor(mode); const steps: agent.ReportStep[] = []; const step = (name: string, outcome: agent.ReportStep["outcome"], detail?: string) => { const at = new Date().toISOString(); steps.push({ name, startedAt: at, finishedAt: at, outcome, ...(detail ? { detail: detail.slice(0, 2000) } : {}) }); }; const refuse = (message: string): WriteOutcome => ({ status: "refused", message, steps, result: {} }); const found = await findConfig(mode, { fresh: true }); if (found.path !== args.path) return refuse(`This server's ${service} config is ${found.path ?? "not found"}, not ${args.path}. Read it again on the Hub first.`); if (!path.basename(args.path).startsWith(service)) return refuse(`${args.path} isn't ${service}'s config (the name must start with ${service}).`); let current: string; try { current = fs.readFileSync(args.path, "utf8"); } catch { return refuse(`There's no file at ${args.path} to replace.`); } const format = formatOf(args.path, current); const restored = restoreSecrets(args.content.replace(/\r\n/g, "\n"), current, format); if (!restored.ok) return refuse(restored.message); const next = restored.content.endsWith("\n") ? restored.content : `${restored.content}\n`; if (next === current) { step("Compare", "skipped", "The file is already like this; nothing changed."); return { status: "succeeded", message: "Nothing changed: the file is already like this.", steps, result: await readConfig(mode, {}, deps) as unknown as Record }; } const dir = path.dirname(args.path); const tmp = path.join(dir, `.${path.basename(args.path)}.crosscode-${process.pid}${path.extname(args.path)}`); const mode0 = fs.statSync(args.path).mode & 0o777; fs.writeFileSync(tmp, next, { mode: mode0 }); try { const v = await exec(found.bin, ["verify", "-c", tmp]); if (v.missing) { step(`${service} verify`, "failed", `${found.bin} wasn't found.`); return { status: "failed", message: `${found.bin} wasn't found, so the new config couldn't be checked; nothing changed.`, steps, result: {} }; } if (!v.ok) { step(`${service} verify`, "failed", `${v.out}\n${v.err}`.trim()); return { status: "failed", message: `${service} verify refused the new config, so nothing changed: ${(v.err || v.out).trim().slice(0, 500)}`, steps, result: {} }; } step(`${service} verify`, "ok"); } catch (e) { fs.rmSync(tmp, { force: true }); throw e; } const backups = path.join(dir, "backups"); fs.mkdirSync(backups, { recursive: true, mode: 0o700 }); const backup = path.join(backups, `${path.basename(args.path)}.${stamp()}`); fs.copyFileSync(args.path, backup); fs.chmodSync(backup, mode0); fs.renameSync(tmp, args.path); step("Replace the config", "ok", `Backup: ${backup}`); if (!args.restart) { step(`Restart ${service}`, "skipped", "Not asked: the new config is used when frp next starts."); return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } }; } const restart = await exec("systemctl", ["restart", service]); await wait(3000); const up = (await exec("systemctl", ["is-active", service])).out.trim() === "active"; if (restart.ok && up) { step(`Restart ${service}`, "ok"); return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } }; } step(`Restart ${service}`, "failed", restart.err || `${service} isn't running after the restart.`); fs.copyFileSync(backup, args.path); await exec("systemctl", ["restart", service]); await wait(3000); const back = (await exec("systemctl", ["is-active", service])).out.trim() === "active"; step("Put the old config back", back ? "rolled-back" : "failed", back ? `${service} runs with the old config again.` : `${service} isn't running with the old config either: look at it on the server (journalctl -u ${service}).`); return { status: back ? "rolled-back" : "failed", message: back ? `${service} didn't start with the new config, so the old one was put back.` : `${service} didn't start with the new config, and isn't running after putting the old one back either.`, steps, result: { ...(await readConfig(mode, {}, deps)), backup }, }; } // ─── Free ports (probe-ports) ───────────────────────────────────────────────── /** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */ export function portAllowed(port: number, allowPorts: string | null): boolean { if (!allowPorts) return true; return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => { const [a, b] = range.split("-").map((n) => Number(n.trim())); if (!Number.isFinite(a)) return false; return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b; }); } export function probePorts(ports: number[], mode: agent.AgentMode, settings: FrpSettings | null, listening: Map, configPath: string | null): agent.ProbePortsResult { const used = new Set(settings?.usedPorts ?? []); return { configPath, ports: ports.map((port) => { const addrs = listening.get(port); if (addrs?.length) return { port, free: false, reason: `In use: something listens on ${[...new Set(addrs)].join(", ")}.` }; if (mode === "central" && settings && !portAllowed(port, settings.allowPorts)) return { port, free: false, reason: "Not in frps's allow_ports." }; if (used.has(port)) return { port, free: false, reason: `Used in ${mode === "central" ? "frps" : "frpc"}'s config.` }; return { port, free: true, reason: null }; }), }; } /** The settings of the config this server uses, or null when there's none. */ export async function currentSettings(mode: agent.AgentMode): Promise<{ path: string | null; settings: FrpSettings | null }> { const found = await findConfig(mode); if (!found.path) return { path: null, settings: null }; try { const text = fs.readFileSync(found.path, "utf8"); return { path: found.path, settings: parseSettings(text, formatOf(found.path, text)) }; } catch { return { path: found.path, settings: null }; } }