Merge branch 'feat/frp-config-and-port-probe'

This commit is contained in:
2026-11-21 11:08:41 +02:00
18 changed files with 586 additions and 23 deletions
+28
View File
@@ -5,6 +5,34 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [2.11.0] - 2026-11-21
Needs agent 1.4.0 on the servers (`agent@1.4.0`) for the new parts; vendors contracts 1.15.0.
Migration `20261121110000_server_frp_config` (two columns on `Server`).
### Added
- **Ports checked on both servers before an install.** A new install reserves a few candidate
ports and asks every central server and the church server which are free (`probe-ports`): on
the central server, nothing listens on it and frps's allow_ports has it; on the church server,
nothing listens on it and frpc's config doesn't use it. The install waits until both have
answered, then runs on the first pair free on both (an Accounts-first batch gets two pairs). Busy
ports go in the port list as taken. Too few free: another round with new ports, three at most;
then, or when a check fails or is missed, the install is called off, its ports freed, and an
email says why. The central agent must be online to start an install. With an agent older than
1.4.0 on either server, the install runs as before, with a warning.
- **frp config on each server's page.** Where frps's (central) or frpc's (church) config is (set a
path, or let the agent find it), what's in it, and changing it in the Hub: secrets never leave
the server (shown as `***hidden***`, kept on save), the new file is checked with `frp* verify`,
a backup is kept, frp is restarted, and the old file goes back if frp doesn't start (an email
then). Two-factor, as for uninstalls. New: `POST /api/admin/servers/:id/frp/read` and `/frp/write`.
### Changed
- The central server's alerts name the file the agent reads (frps.toml too) instead of
"frps.ini", and a server whose agent finds no frp config gets an alert saying to set where it is
(instead of "proxy_bind_addr not set", which was only because the file wasn't where it looked).
## [2.10.0] - 2026-11-20
### Changed
+6 -6
View File
@@ -1,16 +1,16 @@
{
"name": "events-hub-backend",
"version": "2.10.0",
"version": "2.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "2.10.0",
"version": "2.11.0",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.13.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.15.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -609,9 +609,9 @@
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.13.0",
"resolved": "file:vendor/crosscode-contracts-1.13.0.tgz",
"integrity": "sha512-k5A9HPnwEtk94YPPt3v+8IZeJrg2uLZpd2JoFyogzscq1n7TyQxOsy1IdjJXcYlybQbAE5mBDkOVlqxgdsfghg==",
"version": "1.15.0",
"resolved": "file:vendor/crosscode-contracts-1.15.0.tgz",
"integrity": "sha512-NZI53pUP1SpYcWRwH3OeGSvwmf9+v5EPkSG2hwPnhCPUsKYnCHLW/aUCJUHKAB+oQRnJ6SRGR2kxEEnc/8OD+A==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "2.10.0",
"version": "2.11.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -20,7 +20,7 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.13.0.tgz",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.15.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -0,0 +1,4 @@
-- Hub 2.11.0: where frps (central server) or frpc (church server) keeps its config, set from the
-- Hub, and the last read of that file (secrets hidden by the agent).
ALTER TABLE "Server" ADD COLUMN "frpConfigPath" TEXT;
ALTER TABLE "Server" ADD COLUMN "frpConfig" JSONB;
+4
View File
@@ -485,6 +485,10 @@ model Server {
joinedAt DateTime @default(now())
removedAt DateTime?
notes String?
// Hub 2.11.0: the frps (central) or frpc (church) config path set here (null: the agent finds it),
// and the last frp-read result (crosscode.agent frpReadResult, secrets hidden on the server).
frpConfigPath String?
frpConfig Json?
stats ServerStat[]
jobs Job[]
deployments Deployment[]
+32
View File
@@ -64,6 +64,8 @@ function serverSummary(s, now = new Date()) {
versions: st?.versions || null,
frpcRunning: st?.frpcRunning ?? null,
central: st?.central || null,
// Agent 1.4.0+: the frp config it uses (null: none found; undefined: an older agent).
frpConfigPath: st?.frpConfigPath ?? (st && 'frpConfigPath' in st ? null : undefined),
deployments: s.deployments ? s.deployments.filter(d => d.status !== 'removed').length : undefined,
alerts: s.alerts ? s.alerts.map(a => ({ type: a.type, level: a.level, message: a.message, createdAt: a.createdAt })) : undefined,
};
@@ -103,9 +105,39 @@ router.get('/servers/:id', wrap(async (req, res) => {
jobs: recentJobs,
alerts: s.alerts,
ports: s.ports,
frp: await frpState(s),
}));
}));
// ─── frp's config (Hub 2.11.0, agent 1.4.0) ───────────────────────────────────
/** The frp card on a server's page: the path set here, the last read, and a read or change on its way. */
async function frpState(s) {
const pending = await prisma.job.findFirst({ where: { serverId: s.id, type: { in: ['frp-read', 'frp-write'] }, status: { in: ['queued', 'delivered'] } }, orderBy: { createdAt: 'desc' }, select: { id: true, type: true, status: true } });
const last = await prisma.job.findFirst({ where: { serverId: s.id, type: { in: ['frp-read', 'frp-write'] }, status: { notIn: ['queued', 'delivered', 'scheduled'] } }, orderBy: { createdAt: 'desc' }, select: { id: true, type: true, status: true, message: true, finishedAt: true } });
return {
service: s.mode === 'central' ? 'frps' : 'frpc',
path: s.frpConfigPath,
read: s.frpConfig || null,
pending,
last,
minAgent: agent.FRP_JOBS_MIN_AGENT,
hidden: agent.FRP_HIDDEN,
};
}
router.post('/servers/:id/frp/read', wrap(async (req, res) => {
const job = await jobs.readFrp(req.params.id, req.body && 'path' in req.body ? { path: req.body.path } : {}, req.admin);
if (req.body && 'path' in req.body) await audit(req, 'server_frp_path_set', req.params.id, { path: req.body.path || null });
res.status(201).json({ job });
}));
router.post('/servers/:id/frp/write', wrap(async (req, res) => {
const job = await jobs.writeFrp(req.params.id, { content: req.body?.content, restart: req.body?.restart !== false, totp: req.body?.totp }, req.admin);
await audit(req, 'server_frp_config_changed', req.params.id, { path: job.args.path, restart: job.args.restart });
res.status(201).json({ job });
}));
router.patch('/servers/:id', wrap(async (req, res) => {
const data = {};
if (req.body?.name != null) data.name = String(req.body.name).trim().slice(0, 100) || undefined;
+204 -7
View File
@@ -271,6 +271,19 @@ async function afterJob(job, { exportKey }, now) {
case 'status':
if (ok) await linkFromStatus(job, now);
break;
case 'frp-read':
case 'frp-write': {
// What the agent found (secrets hidden on the server), for the server's page.
const r = job.report?.result;
if (agent.frpReadResultSchema.safeParse(r).success) {
await prisma.server.update({ where: { id: job.serverId }, data: { frpConfig: { ...r, jobId: job.id } } });
}
if (job.type === 'frp-write' && !ok) {
const server = await prisma.server.findUnique({ where: { id: job.serverId } });
await emailJoshua(`frp config change ${job.status.replace('_', ' ')}: ${server?.name || job.serverId}`, jobReport(job, `The frp config change on ${server?.name || 'a server'}: ${job.status.replace('_', ' ')}`, job.status === 'rolled_back' ? 'frp didn\'t start with the new config, so the old one was put back.' : 'The config on the server is as it was.'));
}
break;
}
default:
break;
}
@@ -280,6 +293,7 @@ async function afterJob(job, { exportKey }, now) {
// ─── Batches (§8): one at a time, stop at the first failure ───────────────────
async function advanceBatch(job, now) {
if (job.type === 'probe-ports') return portsProbed(job, now);
const rest = await prisma.job.findMany({ where: { batchId: job.batchId, status: 'scheduled' }, orderBy: { batchOrder: 'asc' }, include: { deployment: { include: { install: true } } } });
if (!rest.length) return;
if (job.status === 'succeeded') {
@@ -623,13 +637,27 @@ async function newInstall(input, admin, now = new Date()) {
const dnsFirst = await dnsPointsAtCentral(first.domain);
if (dnsFirst === false) warnings.push(`${first.domain} doesn't point at the central server yet (the install still runs).`);
}
// Hub 2.11.0: the ports are checked on the central server and this one before the install runs.
const probe = await probeServers(server, now);
if (probe.skip) warnings.push(probe.skip);
const probing = probe.servers.length > 0;
const deployment = await prisma.$transaction(async tx => {
const batchId = first || probing ? servers.newId('batch') : null;
const candidates = probing ? await servers.reservePorts(tx, server.id, Math.min(50, (first ? 4 : 2) + PROBE_SPARE), probeNote(batchId), now) : null;
let nextCandidate = 0;
const portsFor = async () => {
if (!candidates) return servers.allocatePorts(tx, server.id, now);
// For now: the first free pair. They change if a server says one is in use.
const [web, api] = candidates.slice(nextCandidate, nextCandidate += 2);
for (const [port, role] of [[web, 'web'], [api, 'api']]) await tx.port.update({ where: { port }, data: { role } });
return { web, api };
};
const make = async (p, dom) => {
let licence = await tx.licence.findFirst({ where: { customerId: customer.id, product: p, status: { not: 'revoked' } }, include: { install: true } });
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${customer.name}'s ${PRODUCT_NAMES[p]} licence is already used by ${licence.install.url}.`);
if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product: p, now })).licence;
const ports = await servers.allocatePorts(tx, server.id, now);
const ports = await portsFor();
const d = await tx.deployment.create({
data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product: p, shortName, domain: dom, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, status: 'installing' },
});
@@ -637,30 +665,199 @@ async function newInstall(input, admin, now = new Date()) {
return { d, ports };
};
// Accounts first (an install job), then the product next to it once that succeeded (a batch).
const batchId = first ? servers.newId('batch') : null;
// While the ports are checked, every install waits (scheduled) until the checks are back.
if (first) {
const a = await make('accounts', first.domain);
await makeJob(tx, {
serverId: server.id, type: siblings.length ? 'add-product' : 'install', deploymentId: a.d.id, createdById: admin?.id || null, notBefore: now, batchId, batchOrder: 0,
...(probing ? { status: 'scheduled' } : {}),
args: siblings.length
? { church: shortName, product: 'accounts', version: `accounts@${first.release.version}`, domain: first.domain, ports: a.ports }
: { church: shortName, products: ['accounts'], versions: { accounts: `accounts@${first.release.version}` }, domains: { accounts: first.domain }, ports: { accounts: a.ports } },
});
}
const { d, ports } = await make(product, domain);
const order = batchId ? { batchId, batchOrder: first ? 1 : 0, ...(first || probing ? { status: 'scheduled' } : {}) } : {};
await makeJob(tx, add
? {
serverId: server.id, type: 'add-product', deploymentId: d.id, createdById: admin?.id || null, notBefore: now,
...(batchId ? { batchId, batchOrder: 1, status: 'scheduled' } : {}),
serverId: server.id, type: 'add-product', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, ...order,
args: { church: shortName, product, version: `${product}@${release.version}`, domain, ports },
}
: {
serverId: server.id, type: 'install', deploymentId: d.id, createdById: admin?.id || null, notBefore: now,
serverId: server.id, type: 'install', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, ...order,
args: { church: shortName, products: [product], versions: { [product]: `${product}@${release.version}` }, domains: { [product]: domain }, ports: { [product]: ports } },
});
if (probing) {
for (const s of probe.servers) {
await makeJob(tx, { serverId: s.id, type: 'probe-ports', args: { ports: candidates }, batchId, reason: probeRound(1), createdById: admin?.id || null, notBefore: now });
}
}
return d;
});
return { deployment, warnings, ...(first ? { alsoInstalling: { product: 'accounts', domain: first.domain, version: first.release.version } } : {}) };
return { deployment, warnings, checkingPorts: probing, ...(first ? { alsoInstalling: { product: 'accounts', domain: first.domain, version: first.release.version } } : {}) };
}
// ─── Ports checked before an install (Hub 2.11.0, agent 1.4.0) ────────────────
//
// An install reserves a few candidate ports and asks the central server and the church server
// which are free (probe-ports). When both answer, it takes the first pair free on both: the
// install's ports, the frp tunnel's on both ends. Ports found in use are kept in the port list as
// taken, so they're never handed out again. If too few are free, it tries more (3 rounds).
/** Spare candidates beyond the two each install needs, so a busy port doesn't need another round. */
const PROBE_SPARE = 8;
const PROBE_ROUNDS = 3;
const probeNote = batchId => `probe:${batchId}`;
const probeRound = n => `ports round ${n}`;
/** The servers that check the ports: every central server and the church server, or why not. */
async function probeServers(server, now) {
const centrals = await prisma.server.findMany({ where: { mode: 'central', removedAt: null } });
const all = [...centrals, server];
const old = all.filter(s => compareVersions(s.agentVersion || '0.0.0', agent.FRP_JOBS_MIN_AGENT) < 0);
if (old.length) {
return { servers: [], skip: `The ports weren't checked on the servers first: ${old.map(s => `${s.name} (agent ${s.agentVersion || 'unknown'})`).join(', ')} need${old.length === 1 ? 's' : ''} agent ${agent.FRP_JOBS_MIN_AGENT} or later. The install still runs.` };
}
for (const c of centrals) {
const running = await prisma.job.findFirst({ where: { serverId: c.id, status: 'delivered' } });
if (!agentOnline(c, now, running)) throw fail(409, 'CENTRAL_OFFLINE', `The agent on the central server ${c.name} isn't online, so the ports can't be checked there first (last heard ${c.lastSeenAt ? c.lastSeenAt.toISOString() : 'never'}).`);
}
return { servers: all };
}
/** The install jobs waiting on a port check, in order. */
const waitingInstalls = batchId => prisma.job.findMany({ where: { batchId, status: 'scheduled', type: { in: ['install', 'add-product'] } }, orderBy: { batchOrder: 'asc' }, include: { deployment: true } });
/** A port check didn't work out: nothing is installed, the ports are free again. */
async function probeFailed(job, why, now) {
const rest = await prisma.job.findMany({ where: { batchId: job.batchId, status: { in: ['scheduled', 'queued'] } }, include: { deployment: true } });
for (const j of rest) {
await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: `Not run: ${why}`, finishedAt: now } });
if (j.deployment && (j.type === 'install' || j.type === 'add-product')) {
await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: 'failed' } });
await prisma.port.deleteMany({ where: { port: { in: [j.deployment.webPort, j.deployment.apiPort] }, role: { in: ['web', 'api', 'candidate'] } } });
}
}
await prisma.port.deleteMany({ where: { note: probeNote(job.batchId), role: { in: ['web', 'api', 'candidate'] } } });
const names = rest.filter(j => j.deployment).map(j => j.deployment.domain);
await emailJoshua(`Install not started: ${names.join(', ') || job.batchId}`, {
heading: 'The install didn\'t start',
sub: 'The ports couldn\'t be checked first.',
blocks: [
{ note: { kind: 'danger', title: 'Nothing was installed', text: why } },
{ p: 'Its ports are free again. Start the install again once the servers are ready.' },
{ button: { label: 'Open the check', url: `${hubUrl()}/jobs/${job.id}` } },
],
});
}
/** After each probe-ports report: once every server of this round has answered, choose the ports. */
async function portsProbed(job, now) {
const round = await prisma.job.findMany({ where: { batchId: job.batchId, type: 'probe-ports', reason: job.reason }, include: { server: true } });
if (round.some(j => !DONE.includes(j.status))) return;
const waiting = await waitingInstalls(job.batchId);
if (!waiting.length) return; // cancelled meanwhile
const bad = round.find(j => j.status !== 'succeeded');
if (bad) return probeFailed(bad, `the port check on ${bad.server.name} was ${bad.status.replace('_', ' ')}${bad.message ? `: ${bad.message}` : '.'}`, now);
const asked = job.args.ports;
const busy = new Map(); // port → "server: reason"
for (const j of round) {
const result = agent.probePortsResultSchema.safeParse(j.report?.result);
if (!result.success) return probeFailed(j, `${j.server.name}'s port check came back in a form the Hub doesn't know.`, now);
const answered = new Map(result.data.ports.map(p => [p.port, p]));
for (const port of asked) {
const p = answered.get(port);
if (!p) busy.set(port, `${j.server.name}: not checked`);
else if (!p.free && !busy.has(port)) busy.set(port, `${j.server.name}: ${p.reason || 'in use'}`);
}
}
const free = asked.filter(p => !busy.has(p));
const serverId = waiting[0].serverId;
// Busy ports stay in the port list as taken, so they're never handed out.
for (const [port, why] of busy) {
await prisma.port.upsert({ where: { port }, update: { role: 'taken', deploymentId: null, note: `Found in use before an install (${now.toISOString().slice(0, 10)}): ${why}`.slice(0, 500) }, create: { port, serverId, role: 'taken', note: `Found in use before an install: ${why}`.slice(0, 500) } });
}
if (free.length < waiting.length * 2) {
const n = Number(String(job.reason || '').replace(/\D/g, '')) || 1;
if (n >= PROBE_ROUNDS) return probeFailed(job, `no two ports were free on every server after ${n} checks (${[...busy].slice(0, 10).map(([p, w]) => `${p} (${w})`).join('; ')}).`, now);
let more;
try {
more = await prisma.$transaction(tx => servers.reservePorts(tx, serverId, Math.min(50 - free.length, waiting.length * 2 + PROBE_SPARE), probeNote(job.batchId), now));
} catch (e) {
return probeFailed(job, e.message, now);
}
const ports = [...free, ...more].slice(0, 50);
for (const j of round) await makeJob(prisma, { serverId: j.serverId, type: 'probe-ports', args: { ports }, batchId: job.batchId, reason: probeRound(n + 1), createdById: job.createdById, notBefore: now });
return;
}
// Each install gets the next two free ports.
let i = 0;
const used = new Set();
for (const j of waiting) {
const [web, api] = free.slice(i, i += 2);
used.add(web).add(api);
const d = j.deployment;
if (d) {
await prisma.deployment.update({ where: { id: d.id }, data: { webPort: web, apiPort: api } });
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await prisma.port.upsert({ where: { port }, update: { serverId, role, deploymentId: d.id, releasedAt: null, note: null }, create: { port, serverId, role, deploymentId: d.id } });
}
}
const args = j.type === 'install'
? { ...j.args, ports: Object.fromEntries(Object.keys(j.args.ports).map(k => [k, { web, api }])) }
: { ...j.args, ports: { web, api } };
const parsed = agent.jobArgsSchemas[j.type].safeParse(args);
if (!parsed.success) return probeFailed(job, `the install's arguments with ports ${web} and ${api} aren't valid.`, now);
await prisma.job.update({ where: { id: j.id }, data: { args: parsed.data } });
}
// The candidates not used are free again.
await prisma.port.deleteMany({ where: { note: probeNote(job.batchId), role: { in: ['candidate', 'web', 'api'] }, port: { notIn: [...used] } } });
const firstJob = waiting[0];
await prisma.job.update({ where: { id: firstJob.id }, data: { status: 'queued', notBefore: now, expiresAt: new Date(now.getTime() + WINDOW_MIN * MIN) } });
}
// ─── frp's config from the Hub (Hub 2.11.0, agent 1.4.0) ──────────────────────
async function frpServer(serverId) {
const s = await prisma.server.findUnique({ where: { id: serverId } });
if (!s || s.removedAt) throw fail(404, 'NOT_FOUND', 'Server not found.');
if (compareVersions(s.agentVersion || '0.0.0', agent.FRP_JOBS_MIN_AGENT) < 0) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${s.name} is ${s.agentVersion || 'an unknown version'}; reading and changing frp's config needs ${agent.FRP_JOBS_MIN_AGENT} or later (update the agent first).`);
}
return s;
}
/**
* Read frps's (central) or frpc's (church) config. `path` given: the Hub keeps it for this server
* and the agent uses that file from now on (an empty one: the agent finds the file itself).
*/
async function readFrp(serverId, { path } = {}, admin = null, now = new Date()) {
const s = await frpServer(serverId);
let use = s.frpConfigPath;
if (path !== undefined) {
const clean = String(path || '').trim();
if (clean && !agent.frpConfigPathSchema.safeParse(clean).success) throw fail(400, 'BAD_REQUEST', 'Give the full path of the config file, like /etc/frp/frps.toml (a file named frp….ini or frp….toml).');
await prisma.server.update({ where: { id: s.id }, data: { frpConfigPath: clean || null } });
use = clean || null;
}
return makeJob(prisma, { serverId: s.id, type: 'frp-read', args: use ? { path: use } : {}, createdById: admin?.id || null, notBefore: now });
}
/** Replace frp's config with `content` (as the last read showed it, secrets hidden): two-factor, as for uninstalls. */
async function writeFrp(serverId, { content, restart = true, totp }, admin, now = new Date()) {
requireTotp(admin, totp);
const s = await frpServer(serverId);
const last = s.frpConfig;
if (!last?.found || !last.path) throw fail(409, 'READ_FIRST', 'Read the config first: the Hub writes to the file it last read.');
const pending = await prisma.job.findFirst({ where: { serverId: s.id, type: 'frp-write', status: { in: ['queued', 'delivered'] } } });
if (pending) throw fail(409, 'BUSY', 'A change to the config is already on its way.');
const text = String(content ?? '');
if (!text.trim()) throw fail(400, 'BAD_REQUEST', 'The config can\'t be empty.');
if (text.length > agent.FRP_CONFIG_MAX) throw fail(400, 'BAD_REQUEST', `The config is longer than ${agent.FRP_CONFIG_MAX} characters.`);
return makeJob(prisma, { serverId: s.id, type: 'frp-write', args: { path: last.path, content: text, restart: !!restart }, createdById: admin?.id || null, notBefore: now });
}
/** `events.hope.co.za` → `accounts.hope.co.za`: the first label swapped (ROADMAP-v3 decision 6). */
@@ -1268,7 +1465,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
}
module.exports = {
readEnv, setEnv, envState,
readEnv, setEnv, envState, readFrp, writeFrp, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
+27 -1
View File
@@ -209,8 +209,13 @@ function serverProblems(server, recent, restarts, now = new Date(), runningJob =
}
if (recent.length >= 5 && recent.slice(0, 5).every(r => r.ramUsedPercent > 90)) out.push({ type: 'ram_high', level: 'warning', message: `RAM over 90% for 5 minutes (${Math.round(recent[0].ramUsedPercent)}% now)` });
if (server.mode === 'church' && st.frpcRunning === false) out.push({ type: 'frpc_down', level: 'critical', message: 'frpc isn\'t running: the server\'s sites can\'t be reached' });
// Agent 1.4.0+ says which frp config it uses (null: it found none). Older agents only read /etc/frp/frps.ini.
const configMissing = st.frpConfigPath === null;
const service = server.mode === 'central' ? 'frps' : 'frpc';
if (configMissing) out.push({ type: 'frp_config_missing', level: server.mode === 'central' ? 'critical' : 'warning', message: `${service}'s config wasn't found on the server: set where it is (Servers → ${server.name} → frp config)` });
if (server.mode === 'central' && st.central) {
if (!st.central.proxyBindAddr || !['127.0.0.1', '::1'].includes(st.central.proxyBindAddr)) out.push({ type: 'proxy_bind_addr', level: 'critical', message: 'frps.ini has no proxy_bind_addr = 127.0.0.1: tunnels can be reached straight from the internet' });
const file = st.frpConfigPath || 'frps.ini';
if (!configMissing && (!st.central.proxyBindAddr || !['127.0.0.1', '::1'].includes(st.central.proxyBindAddr))) out.push({ type: 'proxy_bind_addr', level: 'critical', message: `${file} has no proxy_bind_addr = 127.0.0.1 (proxyBindAddr in frps.toml): tunnels can be reached straight from the internet` });
if (st.central.frpsRunning === false) out.push({ type: 'frps_down', level: 'critical', message: 'frps isn\'t running: no church site can be reached' });
}
}
@@ -282,7 +287,28 @@ async function allocatePorts(tx, serverId, now = new Date()) {
return { web, api };
}
/**
* Hub 2.11.0: `count` free ports reserved for an install's port check (role `candidate`, the note
* names the check), so no other install takes them while the servers are asked. `skip`: ports not
* to hand out (already known to be busy).
*/
async function reservePorts(tx, serverId, count, note, now = new Date(), skip = []) {
const { from, to } = await portRange();
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext('hub:ports'))`;
const reuseAfter = new Date(now.getTime() - 30 * DAY);
const rows = await tx.port.findMany({ where: { port: { gte: from, lte: to } } });
const taken = new Set([...rows.filter(r => !r.releasedAt || r.releasedAt > reuseAfter).map(r => r.port), ...skip]);
const free = [];
for (let p = from; p <= to && free.length < count; p++) if (!taken.has(p)) free.push(p);
if (free.length < Math.min(count, 2)) throw fail(409, 'NO_PORTS', `No free ports left between ${from} and ${to} (Settings → Servers).`);
for (const port of free) {
await tx.port.upsert({ where: { port }, update: { serverId, role: 'candidate', releasedAt: null, deploymentId: null, note }, create: { port, serverId, role: 'candidate', note } });
}
return free;
}
module.exports = {
reservePorts,
busyWithJob,
POLL_SECONDS, STATS_SECONDS, newId, hashToken, jobSigningKey, resetJobKeyForTests,
createJoinToken, joinCommand, join, requireAgent,
+128
View File
@@ -828,3 +828,131 @@ describe("an install's .env from the Hub (2.8.0)", () => {
expect(await db.job.findMany({})).toEqual([]);
});
});
describe('ports checked on both servers before an install (2.11.0)', () => {
const probeReport = (job, free, reasons = {}) => signedReport(job, 'succeeded', { result: { configPath: '/etc/frp/x.toml', ports: job.args.ports.map(p => ({ port: p, free: free(p), reason: free(p) ? null : reasons[p] || 'in use' })) } });
async function setup() {
const { server } = await joinServer('church', 'church-1');
const { server: central } = await joinServer('central', 'central-1');
for (const s of [server, central]) await db.server.update({ where: { id: s.id }, data: { agentVersion: '1.4.0', lastSeenAt: NOW } });
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
return { server: await db.server.findUnique({ where: { id: server.id } }), central: await db.server.findUnique({ where: { id: central.id } }) };
}
const probesOf = async () => db.job.findMany({ where: { type: 'probe-ports' } });
test('the install waits for both checks, then runs on the first pair free on both', async () => {
const { server, central } = await setup();
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.checkingPorts).toBe(true);
const install = (await db.job.findMany({ where: { type: 'install' } }))[0];
expect(install.status).toBe('scheduled');
const probes = await probesOf();
expect(probes.map(p => p.serverId).sort()).toEqual([server.id, central.id].sort());
expect(probes[0].args.ports).toHaveLength(2 + jobs.PROBE_SPARE);
// Reserved: no other install gets them meanwhile.
expect(await db.port.count({ where: { role: 'candidate' } })).toBe(jobs.PROBE_SPARE);
// The church server can't use 20000; the central server can't use 20003.
const cp = probes.find(p => p.serverId === central.id);
const sp = probes.find(p => p.serverId === server.id);
await jobs.receiveReport(central, probeReport(cp, p => p !== 20003, { 20003: 'In use: something listens on 0.0.0.0.' }), NOW);
expect((await db.job.findUnique({ where: { id: install.id } })).status).toBe('scheduled');
await jobs.receiveReport(server, probeReport(sp, p => p !== 20000), NOW);
const after = await db.job.findUnique({ where: { id: install.id } });
expect(after.status).toBe('queued');
expect(after.args.ports).toEqual({ events: { web: 20001, api: 20002 } });
expect(await db.deployment.findUnique({ where: { id: out.deployment.id } })).toMatchObject({ webPort: 20001, apiPort: 20002 });
expect((await db.port.findUnique({ where: { port: 20000 } })).role).toBe('taken');
expect((await db.port.findUnique({ where: { port: 20003 } })).note).toMatch(/central-1/);
expect(await db.port.count({ where: { role: 'candidate' } })).toBe(0);
const [job] = (await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.4.0', mode: 'church', runningJobId: null }, NOW)).jobs;
expect(job.type).toBe('install');
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
});
test('too few free: another round with new ports; a check that fails stops the install', async () => {
const { server, central } = await setup();
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
for (const p of await probesOf()) await jobs.receiveReport(p.serverId === server.id ? server : central, probeReport(p, () => false), NOW);
const round2 = (await probesOf()).filter(p => p.reason === 'ports round 2');
expect(round2).toHaveLength(2);
expect(round2[0].args.ports.every(p => p >= 20010)).toBe(true);
await jobs.receiveReport(central, signedReport(round2.find(p => p.serverId === central.id), 'failed', { message: 'boom' }), NOW);
await jobs.receiveReport(server, probeReport(round2.find(p => p.serverId === server.id), () => true), NOW);
expect((await db.deployment.findUnique({ where: { id: out.deployment.id } })).status).toBe('failed');
expect((await db.job.findMany({ where: { type: 'install' } }))[0].status).toBe('cancelled');
expect(await db.port.count({ where: { role: { in: ['candidate', 'web', 'api'] } } })).toBe(0);
expect(mockMails.some(m => /Install not started/.test(m.subject))).toBe(true);
});
test('Accounts first: both installs get ports from the same check, and run one after the other', async () => {
const { server, central } = await setup();
await db.release.create({ data: { id: 'r3', product: 'events', version: '3.0.0', notes: '- 3', releasedAt: NOW, requires: [{ product: 'accounts', version: '1.0.0' }] } });
await db.release.create({ data: { id: 'a1', product: 'accounts', version: '1.0.0', notes: '- 1', releasedAt: NOW } });
await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'events.grace.co.za' }, admin, NOW);
for (const p of await probesOf()) await jobs.receiveReport(p.serverId === server.id ? server : central, probeReport(p, () => true), NOW);
const installs = await db.job.findMany({ where: { type: { in: ['install', 'add-product'] } }, orderBy: { batchOrder: 'asc' } });
expect(installs.map(j => j.status)).toEqual(['queued', 'scheduled']);
expect(installs[0].args.ports.accounts).toEqual({ web: 20000, api: 20001 });
expect(installs[1].args.ports).toEqual({ web: 20002, api: 20003 });
});
test('older agents: the install runs as before, with a warning', async () => {
const { server } = await setup();
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.3.1' } });
const out = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(out.checkingPorts).toBe(false);
expect(out.warnings.join(' ')).toMatch(/agent 1.4.0 or later/);
expect((await db.job.findMany({ where: { type: 'install' } }))[0].status).toBe('queued');
});
test('the central agent offline: refused', async () => {
const { server, central } = await setup();
await db.server.update({ where: { id: central.id }, data: { lastSeenAt: new Date(NOW.getTime() - H) } });
await expect(jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'CENTRAL_OFFLINE' });
});
});
describe("frp's config from the Hub (2.11.0)", () => {
async function central(version = '1.4.0') {
const { server } = await joinServer('central', 'central-1');
return db.server.update({ where: { id: server.id }, data: { agentVersion: version } });
}
const readResult = { service: 'frps', path: '/usr/local/frp/frps.toml', source: 'hub', found: true, format: 'toml', content: 'bindPort = 7000\nauth.token = "***hidden***"\n', hidden: ['auth.token'], proxyBindAddr: '127.0.0.1', allowPorts: '20000-29999', serviceRunning: true, readAt: NOW.toISOString() };
test('set the path, read, then change it with two-factor', async () => {
const s = await central();
await expect(jobs.readFrp(s.id, { path: '/etc/shadow' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
const read = await jobs.readFrp(s.id, { path: '/usr/local/frp/frps.toml' }, admin, NOW);
expect(read.args).toEqual({ path: '/usr/local/frp/frps.toml' });
expect((await db.server.findUnique({ where: { id: s.id } })).frpConfigPath).toBe('/usr/local/frp/frps.toml');
await expect(jobs.writeFrp(s.id, { content: 'x', totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ code: 'READ_FIRST' });
await jobs.receiveReport(s, signedReport(read, 'succeeded', { result: readResult }), NOW);
expect((await db.server.findUnique({ where: { id: s.id } })).frpConfig).toMatchObject({ path: '/usr/local/frp/frps.toml', found: true });
await expect(jobs.writeFrp(s.id, { content: 'bindPort = 7001\n', totp: '000000' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_TOTP' });
const write = await jobs.writeFrp(s.id, { content: 'bindPort = 7001\n', restart: true, totp: totpNow() }, admin, NOW);
expect(write.args).toEqual({ path: '/usr/local/frp/frps.toml', content: 'bindPort = 7001\n', restart: true });
await expect(jobs.writeFrp(s.id, { content: 'bindPort = 7002\n', totp: totpNow() }, admin, NOW)).rejects.toMatchObject({ code: 'BUSY' });
await jobs.receiveReport(s, signedReport(write, 'rolled-back', { result: readResult, message: 'frps did not start' }), NOW);
expect(mockMails.some(m => /frp config change rolled back/.test(m.subject))).toBe(true);
});
test('older agents are refused', async () => {
const s = await central('1.3.1');
await expect(jobs.readFrp(s.id, {}, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD' });
});
test('alerts name the file, and a config not found', () => {
const base = { mode: 'central', name: 'central-1', lastSeenAt: NOW };
const wrongBind = servers.serverProblems({ ...base, lastStats: { disks: [], frpConfigPath: '/usr/local/frp/frps.toml', central: { proxyBindAddr: null, frpsRunning: true } } }, [], [], NOW);
expect(wrongBind.map(p => p.type)).toEqual(['proxy_bind_addr']);
expect(wrongBind[0].message).toMatch(/\/usr\/local\/frp\/frps.toml/);
const missing = servers.serverProblems({ ...base, lastStats: { disks: [], frpConfigPath: null, central: { proxyBindAddr: null, frpsRunning: true } } }, [], [], NOW);
expect(missing.map(p => p.type)).toEqual(['frp_config_missing']);
});
});
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.10.0",
"version": "2.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.10.0",
"version": "2.11.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.10.0",
"version": "2.11.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+1 -1
View File
@@ -18,7 +18,7 @@ const FILTERS = [
{ key: "cancelled", label: "Cancelled" },
];
const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "env-read", "env-set", "restart", "status", "check-ports", "update-agent"];
const TYPES = ["", "install", "add-product", "deploy", "adopt", "adopt-undo", "export", "uninstall", "purge", "seed-demo", "env-read", "env-set", "restart", "status", "check-ports", "probe-ports", "frp-read", "frp-write", "update-agent"];
const PRODUCTS = [{ key: "", label: "Every product" }, { key: "events", label: "Cross Events" }, { key: "accounts", label: "Accounts" }];
/** Every job sent to a server's agent, newest first, a page at a time (§11: the full report is on each job). */
+6 -1
View File
@@ -9,6 +9,7 @@ import { ago, bytes, fmtDate } from "@/lib/format";
import { useServerPaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
import { FrpConfig, type FrpState } from "@/components/FrpConfig";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
@@ -20,6 +21,7 @@ type Detail = {
jobs: Job[];
alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[];
ports: { port: number; role: string; note: string | null; releasedAt: string | null }[];
frp: FrpState;
};
/** The settings a church server's jobs need (§5); others can be added. */
@@ -125,7 +127,8 @@ export default function ServerPage() {
<p className="mt-2">{s.versions?.os}</p>
<p>Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}</p>
{s.mode === "church" && <p>frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : <b className="text-red-700">not running</b>}</p>}
{s.central && <p>frps.ini: proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
{s.frpConfigPath !== undefined && <p>{s.mode === "central" ? "frps" : "frpc"} config: {s.frpConfigPath ? <span className="font-mono">{s.frpConfigPath}</span> : <b className="text-red-700">not found</b>}</p>}
{s.central && <p>proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
</div>
<div className="card space-y-2 text-sm">
<h2 className="font-medium">Actions</h2>
@@ -138,6 +141,8 @@ export default function ServerPage() {
{s.mode === "church" && <ConfigEditor key={JSON.stringify(d.config)} id={s.id} config={d.config} onSaved={m => { setMsg(m); load(); }} />}
{d.frp && <FrpConfig serverId={s.id} agentVersion={s.agentVersion} frp={d.frp} onChange={m => { setMsg(m); load(); }} />}
{s.mode === "church" && (
<div className="card overflow-x-auto">
<h2 className="font-medium">Sites on this server</h2>
@@ -51,9 +51,14 @@ export default function InstallsPage() {
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment; warnings: string[]; alsoInstalling?: { product: string; domain: string; version: string } }>("/api/admin/deployments", { method: "POST", body: { ...form, version: form.version || undefined, accountsDomain: form.accountsDomain || undefined } });
const r = await api<{ deployment: Deployment; warnings: string[]; checkingPorts?: boolean; alsoInstalling?: { product: string; domain: string; version: string } }>("/api/admin/deployments", { method: "POST", body: { ...form, version: form.version || undefined, accountsDomain: form.accountsDomain || undefined } });
// Hub 2.5.0: Cross Events 3.x for a church without Accounts installs Accounts first.
const notes = [...(r.alsoInstalling ? [`Accounts ${r.alsoInstalling.version} is installed first at ${r.alsoInstalling.domain}; Cross Events follows when it has finished.`] : []), ...r.warnings];
const notes = [
// Hub 2.11.0: the ports are checked on the central server and this one first.
...(r.checkingPorts ? ["The ports are being checked on the central server and this server first; the install starts on ports free on both (about a minute)."] : []),
...(r.alsoInstalling ? [`Accounts ${r.alsoInstalling.version} is installed first at ${r.alsoInstalling.domain}; Cross Events follows when it has finished.`] : []),
...r.warnings,
];
router.push(`/servers/installs/${r.deployment.id}${notes.length ? `?warn=${encodeURIComponent(notes.join(" "))}` : ""}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
+132
View File
@@ -0,0 +1,132 @@
"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>
);
}
+2
View File
@@ -14,6 +14,8 @@ export type ServerSummary = {
versions: { os: string; node: string; postgres: string | null; frpc: string | null; agent: string } | null;
frpcRunning: boolean | null;
central: { proxyBindAddr: string | null; allowPorts: string | null; frpsRunning: boolean | null } | null;
/** Agent 1.4.0+: the frp config it uses (null: none found). */
frpConfigPath?: string | null;
deployments?: number;
alerts?: { type: string; level: string; message: string; createdAt: string }[];
lastDay?: { cpuAvg: number | null; ramAvg: number | null; cpuPeak: number | null; ramPeak: number | null } | null;