Files
events-hub/frontend/src/components/FrpConfig.tsx
T
joshuaandClaude Opus 5.5 0acc61d4d8 Hub 2.11.0: ports checked on both servers before an install; frp config on each server's page
- A new install reserves candidate ports, asks the central and church servers which are free
  (probe-ports), and runs on the first pair free on both (3 rounds, then called off).
- Each server's page reads and changes frps's / frpc's config (agent 1.4.0): secrets stay on the
  server, two-factor, verify, backup, restart, put back if frp doesn't start.
- Alerts name the config file the agent uses; a missing config gets its own alert.
- Vendors contracts 1.15.0. Migration 20261121110000_server_frp_config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:08:29 +02:00

133 lines
7.9 KiB
TypeScript

"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { RefreshCw, Save } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { StatusPill } from "@/components/servers";
/**
* frps's config (central server) or frpc's (church server) from the Hub (2.11.0, agent 1.4.0):
* where the file is, what's in it (secrets hidden on the server), and changing it. A change is
* checked with `frp* verify` on the server, a backup is kept, and the old file goes back when frp
* doesn't start with the new one.
*/
export type FrpRead = {
service: "frps" | "frpc"; path: string | null; source: "hub" | "systemd" | "usual-place" | null; found: boolean; format: "ini" | "toml" | null;
content: string | null; hidden: string[]; proxyBindAddr: string | null; allowPorts: string | null; serviceRunning: boolean | null;
looked?: string[]; readAt: string; jobId?: string;
};
export type FrpState = {
service: "frps" | "frpc";
path: string | null;
read: FrpRead | null;
pending: { id: string; type: string; status: string } | null;
last: { id: string; type: string; status: string; message: string | null; finishedAt: string | null } | null;
minAgent: string;
hidden: string;
};
type Msg = { type: "ok" | "err"; text: string } | null;
const SOURCE: Record<string, string> = { hub: "set here", systemd: "from the systemd unit", "usual-place": "found in a usual place" };
/** Compares dotted versions: is `have` at least `need`? */
function atLeast(have: string | null, need: string): boolean {
const a = (have || "0").split(".").map(Number);
const b = need.split(".").map(Number);
for (let i = 0; i < 3; i++) if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
return true;
}
export function FrpConfig({ serverId, agentVersion, frp, onChange }: { serverId: string; agentVersion: string | null; frp: FrpState; onChange: (m: Msg) => void }) {
const read = frp.read;
const [path, setPath] = useState(frp.path || read?.path || "");
const [content, setContent] = useState(read?.content ?? "");
const [restart, setRestart] = useState(true);
const [totp, setTotp] = useState("");
const [busy, setBusy] = useState(false);
const supported = atLeast(agentVersion, frp.minAgent);
const edited = !!read?.found && content !== (read.content ?? "");
// A new read replaces what's in the editor.
useEffect(() => { setContent(read?.content ?? ""); }, [read?.readAt, read?.content]);
useEffect(() => { setPath(frp.path || read?.path || ""); }, [frp.path, read?.path]);
const go = async (url: string, body: Record<string, unknown>, ok: string) => {
setBusy(true);
try {
await api(url, { method: "POST", body });
onChange({ type: "ok", text: ok });
setTotp("");
} catch (e) { onChange({ type: "err", text: errorText(e) }); }
setBusy(false);
};
const readNow = (withPath: boolean) => go(`/api/admin/servers/${serverId}/frp/read`, withPath ? { path: path.trim() } : {}, "Asked the agent to read the config: it shows here within a minute (reload the page).");
const save = (e: React.FormEvent) => {
e.preventDefault();
if (!read?.path || !window.confirm(`Replace ${read.path} on the server${restart ? ` and restart ${frp.service}` : ""}? Every church site's tunnel drops for a few seconds while ${frp.service} restarts.`)) return;
go(`/api/admin/servers/${serverId}/frp/write`, { content, restart, totp }, `Sent: the agent checks it with ${frp.service} verify, keeps a backup${restart ? `, restarts ${frp.service}` : ""}, and puts the old file back if ${frp.service} doesn't start.`);
};
return (
<div className="card space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="font-medium">frp config ({frp.service})</h2>
{frp.pending && <span className="text-xs text-slate-500">{frp.pending.type === "frp-write" ? "A change" : "A read"} is on its way: <Link className="text-indigo-700 hover:underline" href={`/jobs/${frp.pending.id}`}>{frp.pending.status}</Link></span>}
</div>
{!supported && <p className="text-sm text-amber-700">The agent here is {agentVersion || "an unknown version"}; reading and changing frp&apos;s config needs agent {frp.minAgent} or later. Update the agent first.</p>}
<div>
<label className="label" htmlFor="frp-path">Where the file is</label>
<div className="flex flex-wrap gap-2">
<input id="frp-path" className="input flex-1 font-mono" value={path} onChange={e => setPath(e.target.value)} placeholder={`Found by the agent (e.g. /etc/frp/${frp.service}.toml)`} disabled={!supported} />
<button type="button" className="btn-secondary" disabled={!supported || busy || path.trim() === (frp.path || "")} onClick={() => readNow(true)}>Use this path</button>
<button type="button" className="btn-secondary" disabled={!supported || busy} onClick={() => readNow(false)}><RefreshCw className="h-4 w-4" /> Read now</button>
</div>
<p className="mt-1 text-xs text-slate-500">
Empty: the agent finds it itself (the <code>-c</code> in {frp.service}&apos;s systemd unit, else /etc/frp and other usual places).
{frp.service === "frpc" && " Installs on this server add their tunnels to this file."}
</p>
</div>
{read && (
<div className="text-sm">
{read.found ? (
<p>
<span className="font-mono">{read.path}</span> ({read.format}, {SOURCE[read.source || ""] || "found"}) · read {fmtDate(read.readAt)} ·{" "}
{read.service} {read.serviceRunning === null ? "unknown" : read.serviceRunning ? "running" : <b className="text-red-700">not running</b>}
{read.service === "frps" && <> · proxy_bind_addr {read.proxyBindAddr || <b className="text-red-700">not set</b>} · allow_ports {read.allowPorts || "any"}</>}
</p>
) : (
<p className="text-red-700">
No {read.service} config found{read.path ? <> at <span className="font-mono">{read.path}</span></> : ""}.
{read.looked?.length ? <> Looked in: <span className="font-mono text-xs">{read.looked.join(", ")}</span>.</> : null} Set where it is above.
</p>
)}
</div>
)}
{frp.last && frp.last.status !== "succeeded" && (
<p className="text-sm text-red-700">Last {frp.last.type === "frp-write" ? "change" : "read"}: <StatusPill status={frp.last.status} /> {frp.last.message} <Link className="text-indigo-700 hover:underline" href={`/jobs/${frp.last.id}`}>Open</Link></p>
)}
{read?.found && (
<form className="space-y-2" onSubmit={save}>
<textarea className="input h-80 w-full font-mono text-xs" spellCheck={false} value={content} onChange={e => setContent(e.target.value)} aria-label={`${frp.service} config`} />
<p className="text-xs text-slate-500">
Secret values ({read.hidden.length ? read.hidden.join(", ") : "none here"}) never leave the server: they show as <code>{frp.hidden}</code> and the server&apos;s own value is put back when you save. Secrets are changed on the server, not here.
</p>
<div className="flex flex-wrap items-end gap-3">
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={restart} onChange={e => setRestart(e.target.checked)} /> Restart {frp.service} afterwards</label>
<div><label className="label" htmlFor="frp-totp">Two-factor code</label><input id="frp-totp" className="input w-36" inputMode="numeric" autoComplete="one-time-code" required value={totp} onChange={e => setTotp(e.target.value)} /></div>
<button className="btn-primary" disabled={!edited || busy || !!frp.pending}><Save className="h-4 w-4" /> Save on the server</button>
{edited && <button type="button" className="btn-secondary" onClick={() => setContent(read.content ?? "")}>Undo my changes</button>}
</div>
</form>
)}
</div>
);
}