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>
This commit is contained in:
2026-11-21 11:08:29 +02:00
co-authored by Claude Opus 5.5
parent 0aed4f72b3
commit 0acc61d4d8
18 changed files with 586 additions and 23 deletions
+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,