Agent 1.4.0 + contracts 1.15.0: frp config anywhere, edited from the Hub; ports probed before installs

- The agent finds frps/frpc's config (Hub path, systemd -c, usual places) and reads INI and TOML.
- New jobs frp-read, frp-write (secrets kept on the server, verify, backup, restart, roll back)
  and probe-ports (which ports are free here), on central and church servers.
- Stats report frpConfigPath; crosscode gets FRPC_INI on church servers.
- Website plan versions move up to contracts 1.16.0 and Hub 2.12.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 11:07:50 +02:00
co-authored by Claude Opus 5.5
parent 4cc30c1445
commit 8542d19be0
23 changed files with 1183 additions and 84 deletions
+17 -48
View File
@@ -1,51 +1,15 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import { paths } from "./paths";
import type { FrpSettings } from "./frp";
import { portAllowed } from "./frp";
export { parseFrpsIni, portAllowed } from "./frp";
/**
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
* 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).
*/
export interface FrpsSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
}
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
export function parseFrpsIni(text: string): FrpsSettings {
let inCommon = false;
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
if (!m) continue;
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
}
return out;
}
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
try {
return parseFrpsIni(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
/** 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;
});
}
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
export function parseSs(text: string): Map<number, string[]> {
const out = new Map<number, string[]>();
@@ -72,11 +36,16 @@ export interface PortCheck {
ok: boolean;
}
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
export function checkPorts(
ports: number[],
frps: Pick<FrpSettings, "proxyBindAddr" | "allowPorts"> | null,
listening: Map<number, string[]>,
configPath: string | null = null,
): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } {
const warnings: string[] = [];
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
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 in frps.ini.`);
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);
@@ -86,9 +55,9 @@ export function checkPorts(ports: number[], frps: FrpsSettings | null, listening
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.`);
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, warnings };
return { ports: results, proxyBindAddr: bind, configPath, warnings };
}
export function listeningNow(): Promise<Map<number, string[]>> {
+4 -1
View File
@@ -3,7 +3,7 @@ import type { agent } from "@crosscode/contracts";
/**
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
* as an array passed straight to the process (never through a shell). Jobs the agent handles
* itself (update-agent, check-ports) have none.
* itself (update-agent, check-ports, frp-read, frp-write, probe-ports) have none.
*
* `--config <file>` is added by the runner when the job brings config; `--json` always.
*/
@@ -71,6 +71,9 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
case "update-agent":
case "check-ports":
case "frp-read":
case "frp-write":
case "probe-ports":
return null;
}
}
+454
View File
@@ -0,0 +1,454 @@
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 <file>`, `-c=<file>`, `--config <file>` or `--config=<file>` 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 <unit> -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<FoundConfig> {
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<Line | null> {
let section = "";
const seen = new Map<string, number>();
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<number>();
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<string, Line>();
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<boolean | null> {
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<void>;
}
export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise<agent.FrpReadResult> {
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<string, unknown>;
}
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<WriteOutcome> {
const exec = deps.exec ?? execText;
const wait = deps.wait ?? ((ms: number) => new Promise<void>((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<string, unknown> };
}
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<number, string[]>, 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 };
}
}
+23 -3
View File
@@ -2,7 +2,8 @@ import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { encryptExport } from "@crosscode/contracts/signing";
import { checkPorts, listeningNow, readFrps } from "./central";
import { checkPorts, listeningNow } from "./central";
import { currentSettings, findConfig, probePorts, readConfig, writeConfig } from "./frp";
import { crosscodeArgs } from "./command";
import type { AgentConfig, Keys } from "./config";
import { type HubClient, HubRequestError } from "./hub";
@@ -153,10 +154,25 @@ export class Agent {
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
}
case "check-ports": {
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
const { path: configPath, settings } = await currentSettings("central");
const res = checkPorts(job.args.ports, settings, await listeningNow(), configPath);
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-read": {
const result = await readConfig(this.deps.config.mode, { path: job.args.path });
const message = result.found ? undefined : `No ${result.service} config found${result.path ? ` at ${result.path}` : ""}.`;
return { status: result.found ? "succeeded" : "failed", steps: [], result: result as unknown as Record<string, unknown>, message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-write": {
const w = await writeConfig(this.deps.config.mode, job.args);
return { status: w.status, steps: w.steps, result: w.result, message: w.message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "probe-ports": {
const { path: configPath, settings } = await currentSettings(this.deps.config.mode);
const result = probePorts(job.args.ports, this.deps.config.mode, settings, await listeningNow(), configPath);
return { status: "succeeded", steps: [], result: result as unknown as Record<string, unknown>, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "export":
return await this.runExport(job, limit);
case "status":
@@ -181,7 +197,11 @@ export class Agent {
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
if (this.deps.run) return this.deps.run(args, job);
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
return (async () => {
// crosscode edits frpc's config on installs: tell it where the file is (agent 1.4.0).
const frpc = this.deps.config.mode === "church" ? (await findConfig("church").catch(() => null))?.path : null;
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit, env: frpc ? { FRPC_INI: frpc } : {} });
})();
}
/**
-2
View File
@@ -15,8 +15,6 @@ export const paths = {
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
/** frps.ini on the central server. */
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
/** The churches on a church server. */
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
};
+3 -1
View File
@@ -27,6 +27,8 @@ export interface RunOptions {
sealedConfig?: agent.Sealed | null;
x25519Pem: string;
timeLimitMinutes: number;
/** Extra environment for crosscode (FRPC_INI). */
env?: Record<string, string>;
/** For tests. */
bin?: string;
}
@@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
const child = spawn(opts.bin ?? paths.crosscode, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
env: { ...process.env, ...opts.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
});
let timedOut = false;
const timer = setTimeout(() => {
+5 -4
View File
@@ -3,7 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { agent } from "@crosscode/contracts";
import { readFrps } from "./central";
import { currentSettings, serviceActive } from "./frp";
import { paths } from "./paths";
/**
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.3.1";
export const AGENT_VERSION = "1.4.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
@@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentSt
frpcRunning,
processes,
};
const frp = await currentSettings(mode).catch(() => ({ path: null, settings: null }));
stats.frpConfigPath = frp.path;
if (mode === "central") {
const frps = readFrps();
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
stats.central = { proxyBindAddr: frp.settings?.proxyBindAddr ?? null, allowPorts: frp.settings?.allowPorts ?? null, frpsRunning: await serviceActive("frps") };
}
return stats;
}