diff --git a/CHANGELOG.md b/CHANGELOG.md index 1afb2a2..b70832e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## agent@1.4.0 + contracts@1.15.0 - 2026-11-21 + +- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes + `/etc/frp/frps.ini`: it uses the path set on the Hub, else the `-c` in the frps/frpc systemd + unit, else the usual places (`/etc/frp`, `/usr/local/frp`, `/opt/frp` …), and reads TOML + (`proxyBindAddr`, `allowPorts = [{ start, end }]`) as well as INI. The central server's check + after an install failed with "No frps.ini at /etc/frp/frps.ini" on a server that keeps it + elsewhere. Stats say which file it uses (`frpConfigPath`). `crosscode` gets `FRPC_INI` for it + on church servers. +- **New jobs** (both modes): `frp-read` (the config, secrets hidden), `frp-write` (secrets put + back, `frp* verify`, backup, restart, the old file back if frp doesn't start) and + `probe-ports` (which of these ports are free here). Contracts 1.15.0: the job arguments, + `frpReadResultSchema`, `probePortsResultSchema`, `FRP_JOBS_MIN_AGENT`, `FRP_HIDDEN`, + `agentStats.frpConfigPath`. The Hub needs agent 1.4.0 on a server for these (Hub 2.11.0). +- The Church Website plan's versions move up one: contracts 1.16.0, Hub 2.12.0. + ## crosscode script - 2026-11-20 (no tag: servers run `main`) - **Fix:** the database dump made before each Accounts deploy (`apps/accounts/backend/backups/`) diff --git a/apps/agent/README.md b/apps/agent/README.md index 62663e2..39c3268 100644 --- a/apps/agent/README.md +++ b/apps/agent/README.md @@ -13,8 +13,9 @@ curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/ma | sudo bash -s -- --hub https://hub.crosscode.co.za --token ``` -Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs -`check-ports` and `status`. The script installs Node 24 if needed, the agent in +Add `--central` on the central (FastPanel) server: there the agent only runs `check-ports`, +`probe-ports`, `status`, `update-agent`, and `frp-read` / `frp-write` (frps's config, from the +server's page on the Hub; agent 1.4.0+). The script installs Node 24 if needed, the agent in `/opt/crosscode/agent/releases/` (with `current` pointing at it), the `crosscode` script in `/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts `crosscode-agent.service`. diff --git a/apps/agent/package.json b/apps/agent/package.json index 21d434e..5ca73ba 100644 --- a/apps/agent/package.json +++ b/apps/agent/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/agent", - "version": "1.3.1", + "version": "1.4.0", "private": true, "description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)", "license": "UNLICENSED", diff --git a/apps/agent/src/central.ts b/apps/agent/src/central.ts index 09097f5..4bca243 100644 --- a/apps/agent/src/central.ts +++ b/apps/agent/src/central.ts @@ -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 { const out = new Map(); @@ -72,11 +36,16 @@ export interface PortCheck { ok: boolean; } -export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } { +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(`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> { diff --git a/apps/agent/src/command.ts b/apps/agent/src/command.ts index 0b3c40d..761cfec 100644 --- a/apps/agent/src/command.ts +++ b/apps/agent/src/command.ts @@ -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 ` 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; } } diff --git a/apps/agent/src/frp.ts b/apps/agent/src/frp.ts new file mode 100644 index 0000000..da3daab --- /dev/null +++ b/apps/agent/src/frp.ts @@ -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 `, `-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 }; + } +} diff --git a/apps/agent/src/loop.ts b/apps/agent/src/loop.ts index d4b1fc1..b96fd2e 100644 --- a/apps/agent/src/loop.ts +++ b/apps/agent/src/loop.ts @@ -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, 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, 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, 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 { 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 } : {} }); + })(); } /** diff --git a/apps/agent/src/paths.ts b/apps/agent/src/paths.ts index 53b0718..7355a91 100644 --- a/apps/agent/src/paths.ts +++ b/apps/agent/src/paths.ts @@ -15,8 +15,6 @@ export const paths = { get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); }, /** Agent releases: releases// (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"); }, }; diff --git a/apps/agent/src/runner.ts b/apps/agent/src/runner.ts index 7346165..be8e0fb 100644 --- a/apps/agent/src/runner.ts +++ b/apps/agent/src/runner.ts @@ -27,6 +27,8 @@ export interface RunOptions { sealedConfig?: agent.Sealed | null; x25519Pem: string; timeLimitMinutes: number; + /** Extra environment for crosscode (FRPC_INI). */ + env?: Record; /** For tests. */ bin?: string; } @@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise { 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(() => { diff --git a/apps/agent/src/stats.ts b/apps/agent/src/stats.ts index dd76b6a..638e9f0 100644 --- a/apps/agent/src/stats.ts +++ b/apps/agent/src/stats.ts @@ -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 { return new Promise((resolve) => { @@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise ({ 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; } diff --git a/apps/agent/tests/frp.test.ts b/apps/agent/tests/frp.test.ts new file mode 100644 index 0000000..2347617 --- /dev/null +++ b/apps/agent/tests/frp.test.ts @@ -0,0 +1,167 @@ +import fs from "node:fs"; +import path from "node:path"; +import { agent } from "@crosscode/contracts"; +import { + configFromCommand, findConfig, forgetFound, hideSecrets, parseExecStart, parseSettings, probePorts, readConfig, restoreSecrets, writeConfig, +} from "../src/frp"; +import { tempState } from "./helpers"; + +const H = agent.FRP_HIDDEN; + +const TOML = `bindPort = 7000 +proxyBindAddr = "127.0.0.1" +auth.token = "s3cret-token" # the shared token +allowPorts = [ + { start = 20000, end = 29999 }, + { single = 3001 }, +] + +[webServer] +port = 7500 +password = 'dash-pass' +`; + +const FRPC_INI = `[common] +server_addr = 203.0.113.10 +server_port = 7000 +token = abc123 + +[hope-events-web] +type = tcp +local_ip = 127.0.0.1 +local_port = 20010 +remote_port = 20010 +`; + +const noSystemd = async () => ({ ok: false, out: "", err: "", missing: true }); + +describe("finding frp's config", () => { + it("reads -c from the systemd unit", () => { + expect(configFromCommand("/usr/local/bin/frps -c /usr/local/frp/frps.toml")).toBe("/usr/local/frp/frps.toml"); + expect(configFromCommand("/usr/bin/frps --config=/etc/frps/frps.ini")).toBe("/etc/frps/frps.ini"); + expect(configFromCommand("/usr/bin/frps")).toBeNull(); + expect(parseExecStart("{ path=/usr/local/bin/frps ; argv[]=/usr/local/bin/frps -c /opt/frp/frps.toml ; ignore_errors=no ; start_time=[n/a] }")) + .toEqual({ config: "/opt/frp/frps.toml", bin: "/usr/local/bin/frps" }); + }); + + it("the path from the Hub wins, and is remembered", async () => { + const dir = tempState(); + const file = path.join(dir, "frps.toml"); + fs.writeFileSync(file, TOML); + forgetFound(); + const exec = async () => ({ ok: true, out: "active\n", err: "", missing: false }); + const r = await readConfig("central", { path: file }, { exec }); + expect(r).toMatchObject({ found: true, source: "hub", path: file, format: "toml", proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001", serviceRunning: true }); + forgetFound(); + expect((await findConfig("central", { fresh: true })).path).toBe(file); + }); + + it("a path that isn't there is reported, not remembered", async () => { + const dir = tempState(); + forgetFound(); + const r = await readConfig("central", { path: path.join(dir, "nope", "frps.ini") }, { exec: noSystemd }); + expect(r).toMatchObject({ found: false, content: null }); + expect(fs.existsSync(path.join(dir, "frp.json"))).toBe(false); + }); +}); + +describe("frp settings, INI and TOML", () => { + it("TOML", () => { + expect(parseSettings(TOML, "toml")).toMatchObject({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001" }); + expect(parseSettings(TOML, "toml").usedPorts).toEqual(expect.arrayContaining([7000, 7500])); + }); + it("INI: frpc's tunnels use their ports", () => { + expect(parseSettings(FRPC_INI, "ini").usedPorts).toEqual([20010]); + }); +}); + +describe("secrets never leave the server", () => { + it("are hidden in TOML and INI, keeping the quotes", () => { + const t = hideSecrets(TOML, "toml"); + expect(t.content).toContain(`auth.token = "${H}" # the shared token`); + expect(t.content).toContain(`password = '${H}'`); + expect(t.content).not.toMatch(/s3cret|dash-pass/); + expect(t.hidden).toEqual(["auth.token", "webServer.password"]); + const i = hideSecrets(FRPC_INI, "ini"); + expect(i.content).toContain(`token = ${H}`); + expect(i.content).not.toContain("abc123"); + }); + it("in inline tables too", () => { + expect(hideSecrets(`auth = { method = "token", token = "zzz" }\n`, "toml").content).not.toContain("zzz"); + }); + it("are put back on write, and can't be changed from the Hub", () => { + const shown = hideSecrets(TOML, "toml").content.replace("bindPort = 7000", "bindPort = 7001"); + const back = restoreSecrets(shown, TOML, "toml"); + expect(back.ok && back.content).toBe(TOML.replace("bindPort = 7000", "bindPort = 7001")); + expect(restoreSecrets(shown.replace(`"${H}"`, '"new"'), TOML, "toml")).toMatchObject({ ok: false, message: expect.stringMatching(/auth.token is a secret/) }); + expect(restoreSecrets(`${shown}\n[extra]\ntoken = "${H}"\n`, TOML, "toml")).toMatchObject({ ok: false }); + }); +}); + +describe("writing the config", () => { + const setup = () => { + const dir = tempState(); + const file = path.join(dir, "frps.toml"); + fs.writeFileSync(file, TOML); + fs.writeFileSync(path.join(dir, "frp.json"), JSON.stringify({ path: file })); + forgetFound(); + return { dir, file }; + }; + const shown = () => hideSecrets(TOML, "toml").content; + + it("verify, backup, replace, restart", async () => { + const { dir, file } = setup(); + const calls: string[] = []; + const exec = async (cmd: string, args: string[]) => { calls.push(`${cmd} ${args.join(" ")}`); return { ok: true, out: "active", err: "", missing: false }; }; + const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} }); + expect(r.status).toBe("succeeded"); + expect(fs.readFileSync(file, "utf8")).toContain("bindPort = 7001"); + expect(fs.readFileSync(file, "utf8")).toContain("s3cret-token"); + expect(fs.readdirSync(path.join(dir, "backups"))).toHaveLength(1); + expect(calls.some((c) => / verify -c /.test(c))).toBe(true); + expect(calls).toContain("systemctl restart frps"); + expect(JSON.stringify(r.result)).not.toContain("s3cret"); + }); + + it("verify refuses: nothing changes", async () => { + const { file } = setup(); + const exec = async (cmd: string) => ({ ok: cmd === "systemctl", out: "", err: "bad key", missing: false }); + const r = await writeConfig("central", { path: file, content: "nonsense = [", restart: true }, { exec, wait: async () => {} }); + expect(r.status).toBe("failed"); + expect(fs.readFileSync(file, "utf8")).toBe(TOML); + }); + + it("frps doesn't come back: the old file is put back", async () => { + const { file } = setup(); + let restarts = 0; + const exec = async (_cmd: string, args: string[]) => { + if (args[0] === "restart") restarts++; + if (args[0] === "is-active") return { ok: true, out: restarts >= 2 ? "active" : "failed", err: "", missing: false }; + return { ok: true, out: "", err: "", missing: false }; + }; + const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} }); + expect(r.status).toBe("rolled-back"); + expect(fs.readFileSync(file, "utf8")).toBe(TOML); + }); + + it("only the file the agent uses", async () => { + const { dir } = setup(); + const r = await writeConfig("central", { path: path.join(dir, "frpc.toml"), content: "x = 1", restart: false }, { exec: noSystemd }); + expect(r.status).toBe("refused"); + }); +}); + +describe("free ports before an install", () => { + it("central: not listening and inside allow_ports", () => { + const listening = new Map([[20001, ["0.0.0.0"]]]); + const r = probePorts([20000, 20001, 30000], "central", parseSettings(TOML, "toml"), listening, "/etc/frp/frps.toml"); + expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20000, true], [20001, false], [30000, false]]); + }); + it("church: not listening and not in frpc's tunnels", () => { + const r = probePorts([20010, 20011], "church", parseSettings(FRPC_INI, "ini"), new Map(), "/etc/frp/frpc.ini"); + expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20010, false], [20011, true]]); + }); + it("with no config found, listening is all it can check", () => { + expect(probePorts([20010], "central", null, new Map(), null).ports[0]!.free).toBe(true); + }); +}); diff --git a/docs/AGENT-1.0-PLAN.md b/docs/AGENT-1.0-PLAN.md index 49c8c35..69fffa3 100644 --- a/docs/AGENT-1.0-PLAN.md +++ b/docs/AGENT-1.0-PLAN.md @@ -83,7 +83,8 @@ build differs from this plan, see [Changes while building](#changes-while-buildi - **Polling:** every 30 s `POST /api/agent/v1/poll` (signed) with a short status; the reply holds any jobs due. Every 60 s the stats (§10). Requests back off when the Hub doesn't answer. - **Modes:** `church` (default) and `central` (§6). The central agent can't run any job but - `check-ports` and `status`. + `check-ports`, `status` and `update-agent`, and from agent 1.4.0 `frp-read`, `frp-write` and + `probe-ports` (below). - **Updating itself:** an `update-agent` job checks out the newest `agent@…` tag, builds it next to the running copy, switches the systemd unit over and reports its new version. If the new one doesn't poll within 2 minutes, a systemd timer starts the previous one again. @@ -246,7 +247,25 @@ remote_port = 20011 - The `.ini` format is deprecated in newer frp versions in favour of TOML. The agent reads the format the server has; moving to TOML is a separate job for later. -**The central agent** (`--central`, on the FastPanel server, read-only) answers `check-ports`: +**frp's config from the Hub (agent 1.4.0, Hub 2.11.0).** frps and frpc aren't always in +`/etc/frp/*.ini`: the agent finds the file itself (the path set on the Hub for that server, else +the `-c` in the systemd unit's ExecStart, else the usual places) and reads INI and TOML. The +server's page on the Hub shows it (`frp-read`) and can change it (`frp-write`, with two-factor): +secret values (token, passwords) never leave the server (shown as `***hidden***`, put back on +write, and can't be changed from the Hub), the new file is checked with `frps verify` / +`frpc verify`, a backup is kept in `/backups/`, the service is restarted, and the old file +goes back if it doesn't come up. **This ends "the central agent is read-only":** it can change +frps's config, and nothing else (no FastPanel, no firewall). + +**Ports checked before an install (agent 1.4.0, Hub 2.11.0).** A new install reserves a few +candidate ports and sends `probe-ports` to every central server and to the church server. The +central agent says which are free (nothing listening, inside allow_ports); the church agent says +which are free there (nothing listening, not in frpc's config). The install waits (scheduled) and +then runs on the first pair free on both; busy ports go in the port list as taken. Too few free: +another round with new ports (3 rounds), then the install is called off and its ports freed. +With an agent older than 1.4.0 on either server, the install runs as before, with a warning. + +**The central agent** (`--central`, on the FastPanel server) answers `check-ports` after an install: - the port is inside `allow_ports` in `frps.ini`, - frps has the tunnel open (the port is listening; frps's dashboard API is used if it's enabled @@ -280,7 +299,8 @@ It changes nothing on the central server: no frps edits, no firewall changes, no with the Hub using its licence. 5. **On failure** anything this job created is removed again (PM2 processes, frpc block, database and role, folder), in reverse order, and the report says what failed and what was cleaned up. -6. **Central check:** the Hub asks the central agent to `check-ports` for both ports. +6. **Central check:** the Hub asks the central agent to `check-ports` for both ports. (From Hub + 2.11.0 the ports were already checked free on both servers before step 1; see §6.) 7. **Emails to Joshua:** the install report and, if everything passed, the **FastPanel email** (§11). The install shows **Waiting for proxy** in the Hub. 8. Joshua sets up FastPanel by hand and clicks **Proxy done**. The Hub checks the public URLs diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index 238a2b8..796aa78 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -29,7 +29,7 @@ every release). | 1 | Hub 2.0 → 2.10.0 | **Released, deployed and tested** (Hub `v2.10.0`) | | 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released, rolled out and tested.** Every install adopted onto the monorepo | | 1c | Cross Events 2.3.x: authenticator app 2FA | **Released and rolled out** (carried into Accounts in phase 4) | -| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.3.1` on every server; the central server's agent is read-only) | +| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.3.1` on every server; from agent 1.4.0 the central server's agent can also read and change frps's config from the Hub) | | 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | **Released, rolled out and tested** ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)) | | 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) | | 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.6.1`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed | @@ -85,7 +85,7 @@ Everything up to and including the 2026-11-20 releases is deployed, rolled out a 1. **Phase 5, Church Website 1.0.0** (ROADMAP §6, §9). Planned in [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Order: - contracts 1.15.0 → Accounts 1.7.0 → Events 3.7.0 (shared fonts and footer) → Hub 2.11.0 → + contracts 1.16.0 → Accounts 1.7.0 → Events 3.7.0 (shared fonts and footer) → Hub 2.12.0 → `website@1.0.0` → Hope Family Church → a second church → crosscode-site 1.7.0. 2. **Archive `hope-events`** if it isn't yet (every install now reports 2.2.0 or later; EVENTS-2.2-PLAN §7). diff --git a/docs/ROADMAP-v3.md b/docs/ROADMAP-v3.md index a7d9abd..19fea00 100644 --- a/docs/ROADMAP-v3.md +++ b/docs/ROADMAP-v3.md @@ -641,7 +641,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short: | 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists | | 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0). **Released 2026-11-18** (`accounts@1.0.0`, 1.0.1 on 2026-11-19); the VM test and a run on real Postgres are still to do before a church gets it | Every later product signs in through it | | 4 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide. **Planned 2026-11-19:** [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0; decisions confirmed 2026-11-19) | Breaking change, so a major version. **Moved before the Website on 2026-11-19** (decision 38): Events is the product churches use today, so Accounts is proven on real users first, and the Website then starts with a church whose people already have accounts | -| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.15.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.11.0) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one | +| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.16.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.12.0) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one | | 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed) | Starts with shared users and the feed already in place | | 7 | Church App 1.x | Reading plans, sermons, groups, pastoral care, serving, giving links, directory | After House of Prayer is in use | diff --git a/docs/VERSIONS.md b/docs/VERSIONS.md index 1682dcc..1e65a1d 100644 --- a/docs/VERSIONS.md +++ b/docs/VERSIONS.md @@ -12,9 +12,9 @@ separately below; the two often differ. |------|------|--------|-----|----------| | Cross Events | `crosscode-platform` (`apps/events`) | **3.6.1** | `events@3.6.1` | 2026-11-20 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.6.0** | `accounts@1.6.0` | 2026-11-20 | -| Server agent | `crosscode-platform` (`apps/agent`) | **1.3.1** | `agent@1.3.1` | 2026-11-20 | -| Contracts | `crosscode-platform` (`packages/contracts`) | **1.14.0** | `contracts@1.14.0` | 2026-11-20 | -| Cross Code Hub | `events-hub` | **2.10.0** | `v2.10.0` | 2026-11-20 | +| Server agent | `crosscode-platform` (`apps/agent`) | **1.4.0** | `agent@1.4.0` | 2026-11-21 | +| Contracts | `crosscode-platform` (`packages/contracts`) | **1.15.0** | `contracts@1.15.0` | 2026-11-21 | +| Cross Code Hub | `events-hub` | **2.11.0** | `v2.11.0` | 2026-11-21 | | crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 | | `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-20 (last change: Accounts' pre-deploy dumps don't stop a deploy) | @@ -37,6 +37,14 @@ need their own tags until something outside this repo depends on them. ## What each latest release was for +- **Agent 1.4.0 + contracts 1.15.0 + Hub 2.11.0:** the agent finds frps's / frpc's config wherever + it is (the path set on the Hub, the systemd unit's `-c`, the usual places) and reads TOML too; + each server's Hub page reads and changes that config (secrets stay on the server, `verify`, + backup, restart, put back if frp doesn't start, two-factor); a new install first checks its + ports are free on the central server and the church server (`probe-ports`) and runs on a pair + free on both. Update the agents first (central and church), then deploy the Hub (migration + `20261121110000_server_frp_config`). With older agents the Hub installs as before, with a warning. + - **`crosscode` script (2026-11-20, later):** the database dump made before each Accounts deploy (`backend/backups/`) no longer stops the next deploy as "added by hand" on Accounts below 1.3.0. Released by pushing `main`; the next Hub job pulls it. diff --git a/docs/WEBSITE-1.0-PLAN.md b/docs/WEBSITE-1.0-PLAN.md index 38c7a91..0f6a447 100644 --- a/docs/WEBSITE-1.0-PLAN.md +++ b/docs/WEBSITE-1.0-PLAN.md @@ -17,7 +17,7 @@ prove it repeats. Then it goes on sale (crosscode-site, ROADMAP §9). **Done when:** -- `website@1.0.0`, `contracts@1.15.0`, `accounts@1.7.0`, `events@3.7.0` and Hub `v2.11.0` are +- `website@1.0.0`, `contracts@1.16.0`, `accounts@1.7.0`, `events@3.7.0` and Hub `v2.12.0` are tagged; the Hub installs the Website from New install (after Accounts) and lists its releases. - All four templates pass the same checks (§13) at phone, tablet and desktop sizes: layout, axe, the §11 SEO checks, and Lighthouse (SEO 100, accessibility 95+, performance 90+). @@ -88,7 +88,7 @@ them (phase 6–7). | Shared: `crosscode.church/1` | Website-only | |---|---| | Already there: name, short name, logo, icon, colours, campuses, service times, contact, social, links | Template, section variants, style settings other than fonts and corners (§3), homepage order | -| **New in contracts 1.15.0:** `branding.style`: `fontPairing` (an id from the shared list, §3) and `corners` (`sharp` / `soft` / `round`). Optional and additive, so a minor version | Pages, sections and blocks, navigation, custom pages | +| **New in contracts 1.16.0:** `branding.style`: `fontPairing` (an id from the shared list, §3) and `corners` (`sharp` / `soft` / `round`). Optional and additive, so a minor version | Pages, sections and blocks, navigation, custom pages | | | About (story, mission, vision, values, beliefs), Plan your visit, Leaders, Ministries, Give | | | Messages and series (§7), simple events (§8), media library, per-page SEO | | | Drafts, published versions, preview links | @@ -293,7 +293,7 @@ only freed when neither the working copy nor the last 10 published versions use - **Hub protocol v2, product `website`.** The heartbeat's `websiteStatsSchema` is already in the contracts (pages, messages, events, editors, storage). A Website licence needs the church's Accounts, installed first (as Events 3.x). -- **Hub 2.11.0:** New install offers the Website; release sync for `website@` tags and +- **Hub 2.12.0:** New install offers the Website; release sync for `website@` tags and `apps/website/WHATS-NEW.md`; its env template; the Website's price (R99) and the storage add-on (R20 per extra 5 GB, sent to the site with the licence as its storage limit, and the "Get more storage" request with its email to Joshua) in `frontend/src/lib/tiers.ts` and `backend/src/utils/billing/tiers.js`, in @@ -317,13 +317,13 @@ only freed when neither the working copy nor the last 10 published versions use | Repo | Change | Version | |------|--------|---------| | `crosscode-platform` `apps/website` | New (§1–§11), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `website@1.0.0` | -| `crosscode-platform` `packages/contracts` | `branding.style` (`fontPairing`, `corners`) on `crosscode.church/1`, the font pairing ids, a `website` part of the church export | `contracts@1.15.0` | +| `crosscode-platform` `packages/contracts` | `branding.style` (`fontPairing`, `corners`) on `crosscode.church/1`, the font pairing ids, a `website` part of the church export | `contracts@1.16.0` | | `crosscode-platform` `packages/ui` | Fonts (self-hosted), the theme from the profile (colours, fonts, corners as CSS variables), `ChurchFooter`, links between products, the public site's building blocks | workspace | | `crosscode-platform` `packages/seo` | `Church`, `VideoObject`, `PodcastEpisode`, `BreadcrumbList` builders, the generated share image | workspace | | `crosscode-platform` `apps/accounts` | `branding.style` in the church profile, the shared fonts and footer, the Website's admins saving the profile | `accounts@1.7.0` | | `crosscode-platform` `apps/events` | Public pages with the shared fonts, corners and footer | `events@3.7.0` | | `crosscode-platform` `scripts/` | `products/website.sh`, `website.env.template.json`, bats tests | — | -| `events-hub` | Website in New install, its releases, env template, prices and storage add-on, FastPanel email | Hub `v2.11.0` | +| `events-hub` | Website in New install, its releases, env template, prices and storage add-on, FastPanel email | Hub `v2.12.0` | | `crosscode-site` | Church Website on sale (ROADMAP §9): its page, prices, a page per template, screenshots of the demo church, FAQ, `SoftwareApplication` JSON-LD | `v1.7.0` | ## 13. Testing @@ -349,8 +349,8 @@ only freed when neither the working copy nor the last 10 published versions use ## 14. Releasing and rolling it out -1. `contracts@1.15.0`, then `accounts@1.7.0` (the profile's brand style), then `events@3.7.0`. -2. Hub `v2.11.0` (vendored contracts 1.15.0) deployed. +1. `contracts@1.16.0`, then `accounts@1.7.0` (the profile's brand style), then `events@3.7.0`. +2. Hub `v2.12.0` (vendored contracts 1.16.0) deployed. 3. `website@1.0.0` tagged after the e2e, Lighthouse and VM runs. 4. **Hope Family Church:** Accounts 1.7.0 and Events 3.7.0 first, then New install → Website. The site shows Coming soon while the church builds it, and goes live with its first publish. diff --git a/package-lock.json b/package-lock.json index a3049a5..7ae8a1a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -109,7 +109,7 @@ }, "apps/agent": { "name": "@crosscode/agent", - "version": "1.3.1", + "version": "1.4.0", "license": "UNLICENSED", "dependencies": { "@crosscode/contracts": "*", @@ -21276,7 +21276,7 @@ }, "packages/contracts": { "name": "@crosscode/contracts", - "version": "1.14.0", + "version": "1.15.0", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 468749d..cb023e3 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/contracts", - "version": "1.14.0", + "version": "1.15.0", "description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads", "license": "UNLICENSED", "type": "commonjs", diff --git a/packages/contracts/schemas/agent-job.json b/packages/contracts/schemas/agent-job.json index b37f768..3c54e3c 100644 --- a/packages/contracts/schemas/agent-job.json +++ b/packages/contracts/schemas/agent-job.json @@ -1675,6 +1675,320 @@ "args" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.agent-job/1" + }, + "id": { + "type": "string", + "pattern": "^job_[A-Za-z0-9_-]{8,64}$" + }, + "serverId": { + "type": "string", + "pattern": "^srv_[A-Za-z0-9_-]{8,64}$" + }, + "config": { + "anyOf": [ + { + "type": "object", + "properties": { + "alg": { + "type": "string", + "const": "x25519-hkdf-sha256-aes-256-gcm" + }, + "epk": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + }, + "iv": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{16}$" + }, + "ciphertext": { + "type": "string", + "maxLength": 200000, + "pattern": "^[A-Za-z0-9_-]+$" + } + }, + "required": [ + "alg", + "epk", + "iv", + "ciphertext" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "notBefore": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "frp-read" + }, + "args": { + "type": "object", + "properties": { + "path": { + "type": "string", + "maxLength": 255, + "allOf": [ + { + "pattern": "^\\/(?!.*\\/\\.\\.?(\\/|$))[A-Za-z0-9._/-]+$" + }, + { + "pattern": "\\/frp[A-Za-z0-9._-]*\\.(ini|toml)$" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "schema", + "id", + "serverId", + "notBefore", + "expiresAt", + "signature", + "type", + "args" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.agent-job/1" + }, + "id": { + "type": "string", + "pattern": "^job_[A-Za-z0-9_-]{8,64}$" + }, + "serverId": { + "type": "string", + "pattern": "^srv_[A-Za-z0-9_-]{8,64}$" + }, + "config": { + "anyOf": [ + { + "type": "object", + "properties": { + "alg": { + "type": "string", + "const": "x25519-hkdf-sha256-aes-256-gcm" + }, + "epk": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + }, + "iv": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{16}$" + }, + "ciphertext": { + "type": "string", + "maxLength": 200000, + "pattern": "^[A-Za-z0-9_-]+$" + } + }, + "required": [ + "alg", + "epk", + "iv", + "ciphertext" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "notBefore": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "frp-write" + }, + "args": { + "type": "object", + "properties": { + "path": { + "type": "string", + "maxLength": 255, + "allOf": [ + { + "pattern": "^\\/(?!.*\\/\\.\\.?(\\/|$))[A-Za-z0-9._/-]+$" + }, + { + "pattern": "\\/frp[A-Za-z0-9._-]*\\.(ini|toml)$" + } + ] + }, + "content": { + "type": "string", + "minLength": 1, + "maxLength": 64000 + }, + "restart": { + "type": "boolean" + } + }, + "required": [ + "path", + "content", + "restart" + ], + "additionalProperties": false + } + }, + "required": [ + "schema", + "id", + "serverId", + "notBefore", + "expiresAt", + "signature", + "type", + "args" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.agent-job/1" + }, + "id": { + "type": "string", + "pattern": "^job_[A-Za-z0-9_-]{8,64}$" + }, + "serverId": { + "type": "string", + "pattern": "^srv_[A-Za-z0-9_-]{8,64}$" + }, + "config": { + "anyOf": [ + { + "type": "object", + "properties": { + "alg": { + "type": "string", + "const": "x25519-hkdf-sha256-aes-256-gcm" + }, + "epk": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + }, + "iv": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{16}$" + }, + "ciphertext": { + "type": "string", + "maxLength": 200000, + "pattern": "^[A-Za-z0-9_-]+$" + } + }, + "required": [ + "alg", + "epk", + "iv", + "ciphertext" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "notBefore": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "probe-ports" + }, + "args": { + "type": "object", + "properties": { + "ports": { + "minItems": 1, + "maxItems": 50, + "type": "array", + "items": { + "type": "integer", + "minimum": 1024, + "maximum": 65535 + } + } + }, + "required": [ + "ports" + ], + "additionalProperties": false + } + }, + "required": [ + "schema", + "id", + "serverId", + "notBefore", + "expiresAt", + "signature", + "type", + "args" + ], + "additionalProperties": false } ] } diff --git a/packages/contracts/schemas/agent-report.json b/packages/contracts/schemas/agent-report.json index 0f8e8ba..dce7048 100644 --- a/packages/contracts/schemas/agent-report.json +++ b/packages/contracts/schemas/agent-report.json @@ -31,6 +31,9 @@ "uninstall", "purge", "update-agent", + "frp-read", + "frp-write", + "probe-ports", "check-ports", "status" ] diff --git a/packages/contracts/schemas/agent-stats.json b/packages/contracts/schemas/agent-stats.json index 901bcc0..511bec9 100644 --- a/packages/contracts/schemas/agent-stats.json +++ b/packages/contracts/schemas/agent-stats.json @@ -280,6 +280,17 @@ "type": "null" } ] + }, + "frpConfigPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 255 + }, + { + "type": "null" + } + ] } }, "required": [ diff --git a/packages/contracts/src/agent.ts b/packages/contracts/src/agent.ts index 5da3966..9a37f10 100644 --- a/packages/contracts/src/agent.ts +++ b/packages/contracts/src/agent.ts @@ -81,6 +81,25 @@ export const isSecretEnvName = (name: string): boolean => SECRET_ENV_NAME.test(n /** At most this many changes in one `env-set` job. */ export const ENV_SET_MAX = 50; +/** The first agent that runs `frp-read`, `frp-write` and `probe-ports` jobs (an older one refuses the unknown types). */ +export const FRP_JOBS_MIN_AGENT = "1.4.0"; + +/** + * Where frps (central server) or frpc (church server) keeps its config: an absolute path to a file + * whose name starts with `frp` and ends in `.ini` or `.toml` (`/etc/frp/frps.toml`). + */ +export const frpConfigPathSchema = serverPathSchema.regex(/\/frp[A-Za-z0-9._-]*\.(ini|toml)$/, "Expected the path of frps's or frpc's config: a file named frp….ini or frp….toml"); + +/** The longest frp config the Hub reads or writes. */ +export const FRP_CONFIG_MAX = 64_000; + +/** + * Secret values in an frp config (token, passwords) never leave the server: `frp-read` shows them + * as this, and `frp-write` puts the server's own value back where it finds it. A secret can't be + * changed from the Hub. + */ +export const FRP_HIDDEN = "***hidden***"; + /** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */ export const jobArgsSchemas = { /** `crosscode install --products … --frp --json` */ @@ -151,6 +170,24 @@ export const jobArgsSchemas = { purge: z.strictObject({ church: shortNameSchema }), /** The agent updates itself to that tag. */ "update-agent": z.strictObject({ version: agentTagSchema }), + /** + * frps's config (central server) or frpc's (church server), secrets hidden: an {@link frpReadResultSchema}. + * With `path`, the agent uses (and remembers) that file instead of the one it finds itself. + */ + "frp-read": z.strictObject({ path: frpConfigPathSchema.optional() }), + /** + * Replaces frps's or frpc's config: secrets put back from the file on the server, checked with + * `frps verify` / `frpc verify`, a backup kept, then (with `restart`) the service restarted. When + * it doesn't come back, the old file is put back (`rolled-back`). `path` must be the file the + * agent uses now (what the last `frp-read` showed). + */ + "frp-write": z.strictObject({ path: frpConfigPathSchema, content: z.string().min(1).max(FRP_CONFIG_MAX), restart: z.boolean() }), + /** + * Before an install: which of these ports are free here? On the central server: nothing listens + * on it and frps's allow_ports has it. On a church server: nothing listens on it and frpc's config + * doesn't use it. The result is a {@link probePortsResultSchema}. + */ + "probe-ports": z.strictObject({ ports: z.array(portSchema).min(1).max(50) }), /** Central server only: are these ports allowed, open and bound to 127.0.0.1? */ "check-ports": z.strictObject({ ports: z.array(portSchema).min(1).max(50) }), /** `crosscode status [] --json` */ @@ -163,12 +200,13 @@ export const jobTypeSchema = z.enum(JOB_TYPES as [JobType, ...JobType[]]); export type JobArgs = z.infer<(typeof jobArgsSchemas)[T]>; /** The only jobs a central agent runs (§3). */ -export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "update-agent"]; +export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "update-agent", "frp-read", "frp-write", "probe-ports"]; /** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */ export const JOB_TIME_LIMIT_MINUTES: Record = { install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, "env-read": 2, "env-set": 20, export: 20, uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3, + "frp-read": 2, "frp-write": 5, "probe-ports": 2, }; /** Config sealed to the server's X25519 key (`sealConfig` in `@crosscode/contracts/signing`). */ @@ -213,6 +251,7 @@ function jobOf(type: T) { export const agentJobSchema = z.discriminatedUnion("type", [ jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"), jobOf("env-read"), jobOf("env-set"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"), + jobOf("frp-read"), jobOf("frp-write"), jobOf("probe-ports"), ]); export type AgentJob = z.infer; export type UnsignedAgentJob = Omit; @@ -280,9 +319,9 @@ export const processStatSchema = z.object({ }); export const centralStatSchema = z.object({ - /** `proxy_bind_addr` in frps.ini, null when it isn't set (tunnels then open on every address). */ + /** `proxy_bind_addr` (frps.ini) or `proxyBindAddr` (frps.toml), null when it isn't set (tunnels then open on every address). */ proxyBindAddr: z.string().max(100).nullable(), - /** `allow_ports` in frps.ini as written, e.g. `20000-29999`. */ + /** `allow_ports` as written (`20000-29999`); frps.toml's `allowPorts` is written the same way. */ allowPorts: z.string().max(2000).nullable(), frpsRunning: z.boolean().nullable(), }); @@ -298,6 +337,8 @@ export const agentStatsSchema = z.object({ frpcRunning: z.boolean().nullable(), processes: z.array(processStatSchema).max(200), central: centralStatSchema.nullable().optional(), + /** Agent 1.4.0+: the frps (central) or frpc (church) config the agent uses, null when it found none. */ + frpConfigPath: z.string().max(255).nullable().optional(), }); export type AgentStats = z.infer; @@ -395,6 +436,42 @@ export const envReadResultSchema = z.object({ }); export type EnvReadResult = z.infer; +// --------------------------------------------------------------------------------------------- +// frp config and free ports (contracts 1.15.0, agent 1.4.0) +// --------------------------------------------------------------------------------------------- + +/** How the agent found the frp config: set from the Hub, the systemd unit's `-c`, or a usual place. */ +export const FRP_CONFIG_SOURCES = ["hub", "systemd", "usual-place"] as const; + +/** The `result` of an `frp-read` report (and of an `frp-write` that went through). */ +export const frpReadResultSchema = z.object({ + /** `frps` on the central server, `frpc` on a church server. */ + service: z.enum(["frps", "frpc"]), + path: z.string().max(255).nullable(), + source: z.enum(FRP_CONFIG_SOURCES).nullable(), + found: z.boolean(), + format: z.enum(["ini", "toml"]).nullable(), + /** The file with each secret value replaced by {@link FRP_HIDDEN}. */ + content: z.string().max(FRP_CONFIG_MAX).nullable(), + /** The names of the hidden values (`token`, `auth.token`, `webServer.password` …). */ + hidden: z.array(z.string().max(100)).max(50), + /** frps only (null on a church server): what the Hub checks. */ + proxyBindAddr: z.string().max(100).nullable(), + allowPorts: z.string().max(2000).nullable(), + serviceRunning: z.boolean().nullable(), + /** Where the agent looked, when it found nothing. */ + looked: z.array(z.string().max(255)).max(20).optional(), + readAt: dateTimeSchema, +}); +export type FrpReadResult = z.infer; + +/** The `result` of a `probe-ports` report. */ +export const probePortsResultSchema = z.object({ + ports: z.array(z.object({ port: portSchema, free: z.boolean(), reason: z.string().max(200).nullable() })).max(50), + configPath: z.string().max(255).nullable(), +}); +export type ProbePortsResult = z.infer; + /** The variables a layer must provide for a template, that it doesn't (the Hub's check before a job). */ export function missingRequired(template: EnvTemplate, layer: "server" | "defaults", values: Record): string[] { const missing: string[] = []; diff --git a/packages/contracts/tests/agent.test.ts b/packages/contracts/tests/agent.test.ts index 5ba6e60..82c8b11 100644 --- a/packages/contracts/tests/agent.test.ts +++ b/packages/contracts/tests/agent.test.ts @@ -240,3 +240,38 @@ describe("env templates", () => { expect(agent.invalidValues({ TRUST_PROXY: "loopback" })).toEqual({}); }); }); + +describe("frp config and free ports (1.15.0)", () => { + const read = (a: Record) => agent.jobArgsSchemas["frp-read"].safeParse(a).success; + const write = (a: Record) => agent.jobArgsSchemas["frp-write"].safeParse({ path: "/etc/frp/frps.toml", content: "bindPort = 7000\n", restart: true, ...a }).success; + it("read the config the agent finds, or one at a path", () => { + expect(read({})).toBe(true); + expect(read({ path: "/etc/frp/frps.toml" })).toBe(true); + expect(read({ path: "/usr/local/frp/frpc.ini" })).toBe(true); + for (const path of ["/etc/shadow", "etc/frp/frps.ini", "/etc/frp/../shadow/frps.ini", "/etc/frp/frps.ini; rm -rf /", "/etc/frp/frps.service", "/etc/frp/server.toml"]) expect(read({ path })).toBe(false); + expect(read({ path: "/etc/frp/frps.ini", extra: 1 })).toBe(false); + }); + it("write one, with content and whether to restart", () => { + expect(write({})).toBe(true); + expect(write({ content: "" })).toBe(false); + expect(write({ content: "x".repeat(agent.FRP_CONFIG_MAX + 1) })).toBe(false); + expect(write({ path: "/etc/passwd" })).toBe(false); + expect(write({ restart: "yes" })).toBe(false); + }); + it("probe ports", () => { + expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [20000, 20001] }).success).toBe(true); + expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [] }).success).toBe(false); + expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [80] }).success).toBe(false); + }); + it("the central agent runs all three", () => { + expect(agent.CENTRAL_JOB_TYPES).toEqual(expect.arrayContaining(["frp-read", "frp-write", "probe-ports"])); + expect(agent.JOB_TIME_LIMIT_MINUTES["frp-write"]).toBeGreaterThan(0); + }); + it("results", () => { + expect(agent.frpReadResultSchema.safeParse({ + service: "frps", path: "/etc/frp/frps.toml", source: "systemd", found: true, format: "toml", content: `auth.token = "${agent.FRP_HIDDEN}"\n`, hidden: ["auth.token"], + proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999", serviceRunning: true, readAt: "2026-11-21T10:00:00.000Z", + }).success).toBe(true); + expect(agent.probePortsResultSchema.safeParse({ ports: [{ port: 20000, free: false, reason: "in use" }], configPath: null }).success).toBe(true); + }); +});