Hub 2.20.0: port list labels; frps allow_ports checked against it
- GET /api/admin/ports names each port's install (church, product, web/API, domain); the port list shows it, linked to the install, and says which ports are held for a port check. - A church server's hand-written frpc tunnels are listed as taken (note: frpc tunnel "<name>" on <server>) on each frp-read/frp-write, and taken off when they leave the file. - Central servers: allow_ports must cover the port range and every listed port outside it. An allow_ports alert names what's missing and the value to set; the frp card warns, and Edit has "Use the Hub's allow_ports" (INI or TOML). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,8 @@ const { audit } = require('../utils/audit');
|
||||
const { getSettings, setSettings } = require('../utils/settings');
|
||||
const servers = require('../utils/servers');
|
||||
const jobs = require('../utils/jobs');
|
||||
const frpPorts = require('../utils/frpPorts');
|
||||
const { PRODUCT_NAMES } = require('../utils/products');
|
||||
const { latestAgentVersion } = require('../utils/releases');
|
||||
const { pageOf, paged } = require('../utils/paging');
|
||||
|
||||
@@ -126,6 +128,21 @@ async function frpState(s) {
|
||||
last,
|
||||
minAgent: agent.FRP_JOBS_MIN_AGENT,
|
||||
hidden: agent.FRP_HIDDEN,
|
||||
allowPorts: await allowPortsState(s),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hub 2.20.0, central servers: what allow_ports must cover (the port range and listed ports
|
||||
* outside it), what the last read file leaves out, and that file with it fixed (for the editor).
|
||||
*/
|
||||
async function allowPortsState(s) {
|
||||
if (s.mode !== 'central') return null;
|
||||
const read = s.frpConfig?.found ? s.frpConfig : null;
|
||||
const check = await servers.allowPortsCheck(read ? read.allowPorts : (s.lastStats?.central?.allowPorts ?? null));
|
||||
return {
|
||||
...check,
|
||||
fixedContent: read && check.missing ? frpPorts.withAllowPorts(read.content, read.format, check.suggested) : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -315,7 +332,14 @@ router.post('/jobs/:id/extend', wrap(async (req, res) => {
|
||||
// ─── The port list and install defaults ───────────────────────────────────────
|
||||
|
||||
router.get('/ports', wrap(async (req, res) => {
|
||||
const [ports, range] = await Promise.all([prisma.port.findMany({ orderBy: { port: 'asc' }, include: { server: { select: { id: true, name: true } } } }), servers.portRange()]);
|
||||
const [rows, range] = await Promise.all([prisma.port.findMany({ orderBy: { port: 'asc' }, include: { server: { select: { id: true, name: true } } } }), servers.portRange()]);
|
||||
// Hub 2.20.0: which install each port is for (Port has no relation to Deployment).
|
||||
const ids = [...new Set(rows.map(r => r.deploymentId).filter(Boolean))];
|
||||
const deployments = new Map((ids.length ? await prisma.deployment.findMany({ where: { id: { in: ids } } }) : []).map(d => [d.id, d]));
|
||||
const ports = rows.map(r => {
|
||||
const d = r.deploymentId ? deployments.get(r.deploymentId) : null;
|
||||
return { ...r, deployment: d ? { id: d.id, shortName: d.shortName, product: d.product, productName: PRODUCT_NAMES[d.product] || d.product, domain: d.domain, status: d.status } : null };
|
||||
});
|
||||
res.json({ ports, range });
|
||||
}));
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Hub 2.20.0: frps's allow_ports and the port list.
|
||||
*
|
||||
* The central server's frps allows the Hub's whole port range (so installs never need an frps
|
||||
* restart) plus every listed port outside it (tunnels written by hand). The Hub warns when
|
||||
* allow_ports doesn't cover them and suggests the value; a church server's hand-written frpc
|
||||
* tunnels are listed as taken from its frp config, so the Hub never hands their ports out.
|
||||
*/
|
||||
|
||||
/** "3000,20000-29999" → [[3000, 3000], [20000, 29999]] (merged, sorted). */
|
||||
function parseRanges(text) {
|
||||
const out = [];
|
||||
for (const part of String(text || '').split(',')) {
|
||||
const m = /^\s*(\d+)\s*(?:-\s*(\d+))?\s*$/.exec(part);
|
||||
if (!m) continue;
|
||||
const a = Number(m[1]);
|
||||
const b = m[2] === undefined ? a : Number(m[2]);
|
||||
if (a <= b) out.push([a, b]);
|
||||
}
|
||||
return merge(out);
|
||||
}
|
||||
|
||||
function merge(ranges) {
|
||||
const sorted = ranges.map(r => [...r]).sort((x, y) => x[0] - y[0]);
|
||||
const out = [];
|
||||
for (const r of sorted) {
|
||||
const last = out[out.length - 1];
|
||||
if (last && r[0] <= last[1] + 1) last[1] = Math.max(last[1], r[1]);
|
||||
else out.push(r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const formatRanges = ranges => merge(ranges).map(([a, b]) => (a === b ? String(a) : `${a}-${b}`)).join(',');
|
||||
|
||||
/** The ports frps must allow: the Hub's range and every listed port (not freed) outside it. */
|
||||
function neededRanges(rows, range) {
|
||||
const out = [[range.from, range.to]];
|
||||
for (const r of rows) if (!r.releasedAt && (r.port < range.from || r.port > range.to)) out.push([r.port, r.port]);
|
||||
return merge(out);
|
||||
}
|
||||
|
||||
/** What `allowPorts` leaves out of `needed` (null or empty allow_ports allows every port). */
|
||||
function missingRanges(allowPorts, needed) {
|
||||
if (!allowPorts || !String(allowPorts).trim()) return [];
|
||||
const allowed = parseRanges(allowPorts);
|
||||
const out = [];
|
||||
for (const [a, b] of needed) {
|
||||
let from = a;
|
||||
for (const [x, y] of allowed) {
|
||||
if (y < from || x > b) continue;
|
||||
if (x > from) out.push([from, x - 1]);
|
||||
from = Math.max(from, y + 1);
|
||||
if (from > b) break;
|
||||
}
|
||||
if (from <= b) out.push([from, b]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The value to suggest: what's allowed now, with what's missing added. */
|
||||
const suggestedAllowPorts = (allowPorts, needed) => formatRanges([...parseRanges(allowPorts), ...needed]);
|
||||
|
||||
/** frps's config with allow_ports (INI) or allowPorts (TOML) set to `value` (added when it has none). */
|
||||
function withAllowPorts(content, format, value) {
|
||||
const eol = content.includes('\r\n') ? '\r\n' : '\n';
|
||||
const lines = content.split(/\r?\n/);
|
||||
if (format === 'ini') {
|
||||
let inCommon = false;
|
||||
let commonAt = -1;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const t = lines[i].trim();
|
||||
if (/^\[[^\]]+\]/.test(t)) { inCommon = /^\[common\]/.test(t); if (inCommon) commonAt = i; continue; }
|
||||
if (inCommon && /^allow_ports\s*=/.test(t)) { lines[i] = `allow_ports = ${value}`; return lines.join(eol); }
|
||||
}
|
||||
if (commonAt < 0) return `[common]${eol}allow_ports = ${value}${eol}${content}`;
|
||||
lines.splice(commonAt + 1, 0, `allow_ports = ${value}`);
|
||||
return lines.join(eol);
|
||||
}
|
||||
const toml = `allowPorts = [${parseRanges(value).map(([a, b]) => (a === b ? `{ single = ${a} }` : `{ start = ${a}, end = ${b} }`)).join(', ')}]`;
|
||||
// An existing allowPorts, on one line or several.
|
||||
const start = lines.findIndex(l => /^\s*allowPorts\s*=/.test(l));
|
||||
if (start >= 0) {
|
||||
let end = start;
|
||||
let depth = 0;
|
||||
for (let i = start; i < lines.length; i++) {
|
||||
for (const c of lines[i].replace(/#.*$/, '')) { if (c === '[') depth++; else if (c === ']') depth--; }
|
||||
end = i;
|
||||
if (depth <= 0) break;
|
||||
}
|
||||
lines.splice(start, end - start + 1, toml);
|
||||
return lines.join(eol);
|
||||
}
|
||||
// Top-level keys come before the first table.
|
||||
const firstTable = lines.findIndex(l => /^\s*\[/.test(l));
|
||||
lines.splice(firstTable < 0 ? lines.length : firstTable, 0, toml);
|
||||
return lines.join(eol);
|
||||
}
|
||||
|
||||
/** A church server's frpc tunnels from its config: [{ name, port }] (the remote port). */
|
||||
function frpcTunnels(content, format) {
|
||||
const out = [];
|
||||
let inProxy = false;
|
||||
let name = null;
|
||||
let port = null;
|
||||
const flush = () => { if (inProxy && name && port) out.push({ name, port }); name = null; port = null; };
|
||||
for (const raw of String(content || '').split(/\r?\n/)) {
|
||||
const t = raw.trim();
|
||||
if (!t || t.startsWith('#') || t.startsWith(';')) continue;
|
||||
const header = /^\[(\[)?\s*([^\]]+?)\s*\]\]?/.exec(t);
|
||||
if (header) {
|
||||
flush();
|
||||
// INI: each section but [common] is a tunnel, named by it. TOML: [[proxies]], named by `name`.
|
||||
if (format === 'ini') { inProxy = header[2] !== 'common'; name = header[2]; }
|
||||
else inProxy = !!header[1] && header[2] === 'proxies';
|
||||
continue;
|
||||
}
|
||||
if (!inProxy) continue;
|
||||
const kv = /^([A-Za-z_.]+)\s*=\s*(.*)$/.exec(t);
|
||||
if (!kv) continue;
|
||||
const value = kv[2].replace(/\s+#.*$/, '').trim().replace(/^["']|["']$/g, '');
|
||||
if (format !== 'ini' && kv[1] === 'name') name = value;
|
||||
if (/^(remote_port|remotePort)$/.test(kv[1]) && /^\d+$/.test(value)) port = Number(value);
|
||||
}
|
||||
flush();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The note on a port taken by a hand-written frpc tunnel (kept in step with the server's frpc config). */
|
||||
const TUNNEL_NOTE = 'frpc tunnel ';
|
||||
const tunnelNote = (name, serverName) => `${TUNNEL_NOTE}"${name}" on ${serverName}`.slice(0, 500);
|
||||
const isTunnelNote = note => typeof note === 'string' && note.startsWith(TUNNEL_NOTE);
|
||||
|
||||
module.exports = { parseRanges, formatRanges, neededRanges, missingRanges, suggestedAllowPorts, withAllowPorts, frpcTunnels, tunnelNote, isTunnelNote };
|
||||
@@ -24,6 +24,7 @@ const { unmetRequirements, unmetRequirementsFor, agentTag } = require('./release
|
||||
const { searchTerm } = require('./paging');
|
||||
const { compareVersions } = require('./alerts');
|
||||
const servers = require('./servers');
|
||||
const frpPorts = require('./frpPorts');
|
||||
const { missingFor, invalidFor } = require('./envTemplates');
|
||||
|
||||
const MIN = 60 * 1000;
|
||||
@@ -289,6 +290,7 @@ async function afterJob(job, { exportKey }, now) {
|
||||
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 } } });
|
||||
await listFrpcTunnels(job.serverId, r, now);
|
||||
}
|
||||
if (job.type === 'frp-write' && !ok) {
|
||||
const server = await prisma.server.findUnique({ where: { id: job.serverId } });
|
||||
@@ -302,6 +304,32 @@ async function afterJob(job, { exportKey }, now) {
|
||||
if (job.batchId) await advanceBatch(job, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hub 2.20.0: a church server's frpc tunnels in the port list. A tunnel whose port isn't listed
|
||||
* (written by hand, not an install) is listed as taken, named after the tunnel, so the Hub never
|
||||
* hands its port out and frps's allow_ports is checked for it. One that's gone from the file is
|
||||
* taken off the list again. Ports of installs and ports marked by hand are left as they are.
|
||||
*/
|
||||
async function listFrpcTunnels(serverId, read, now = new Date()) {
|
||||
const server = await prisma.server.findUnique({ where: { id: serverId } });
|
||||
if (!server || server.mode !== 'church' || !read.found || !read.content) return;
|
||||
const tunnels = frpPorts.frpcTunnels(read.content, read.format);
|
||||
const ports = new Set(tunnels.map(t => t.port));
|
||||
const rows = new Map((await prisma.port.findMany({ where: { port: { in: [...ports] } } })).map(r => [r.port, r]));
|
||||
for (const t of tunnels) {
|
||||
const row = rows.get(t.port);
|
||||
const note = frpPorts.tunnelNote(t.name, server.name);
|
||||
if (!row || row.releasedAt) {
|
||||
await prisma.port.upsert({ where: { port: t.port }, update: { serverId, role: 'taken', deploymentId: null, releasedAt: null, note }, create: { port: t.port, serverId, role: 'taken', note, createdAt: now } });
|
||||
} else if (row.role === 'taken' && (!row.note || (frpPorts.isTunnelNote(row.note) && row.serverId === serverId && row.note !== note))) {
|
||||
await prisma.port.update({ where: { port: t.port }, data: { note, serverId } });
|
||||
}
|
||||
}
|
||||
const listed = await prisma.port.findMany({ where: { serverId, role: 'taken', releasedAt: null } });
|
||||
const gone = listed.filter(r => frpPorts.isTunnelNote(r.note) && !ports.has(r.port)).map(r => r.port);
|
||||
if (gone.length) await prisma.port.deleteMany({ where: { port: { in: gone } } });
|
||||
}
|
||||
|
||||
// ─── Batches (§8): one at a time, stop at the first failure ───────────────────
|
||||
|
||||
async function advanceBatch(job, now) {
|
||||
@@ -1626,7 +1654,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
readEnv, setEnv, envState, readFrp, writeFrp, portsProbed, probeServers, PROBE_SPARE,
|
||||
readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, 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, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
|
||||
|
||||
@@ -14,6 +14,7 @@ const { encrypt, decrypt } = require('./crypto');
|
||||
const { getSettings } = require('./settings');
|
||||
const { sendMail } = require('./mail');
|
||||
const { render } = require('./emailLayout');
|
||||
const frpPorts = require('./frpPorts');
|
||||
|
||||
const JOIN_TOKEN_MINUTES = 60;
|
||||
const POLL_SECONDS = 30;
|
||||
@@ -232,6 +233,10 @@ async function runServerAlerts(now = new Date()) {
|
||||
const recent = await prisma.serverStat.findMany({ where: { serverId: server.id, granularity: 'minute', at: { gt: new Date(now.getTime() - 6 * MIN) } }, orderBy: { at: 'desc' }, take: 5 });
|
||||
const running = await prisma.job.findFirst({ where: { serverId: server.id, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
|
||||
const current = serverProblems(server, recent, restartsInTenMinutes(server.id), now, running);
|
||||
if (server.mode === 'central' && server.lastStats?.central) {
|
||||
const p = allowPortsProblem(server, await allowPortsCheck(server.lastStats.central.allowPorts ?? null));
|
||||
if (p) current.push(p);
|
||||
}
|
||||
const open = new Map(server.alerts.map(a => [a.type, a]));
|
||||
for (const p of current) {
|
||||
if (open.has(p.type)) continue;
|
||||
@@ -287,6 +292,25 @@ async function allocatePorts(tx, serverId, now = new Date()) {
|
||||
return { web, api };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hub 2.20.0: does frps's allow_ports cover the Hub's range and every listed port outside it?
|
||||
* `allowPorts` as the central agent reports it (null: every port allowed).
|
||||
*/
|
||||
async function allowPortsCheck(allowPorts) {
|
||||
const range = await portRange();
|
||||
const rows = await prisma.port.findMany({ where: { releasedAt: null } });
|
||||
const needed = frpPorts.neededRanges(rows, range);
|
||||
const missing = frpPorts.missingRanges(allowPorts, needed);
|
||||
return { needed: frpPorts.formatRanges(needed), missing: frpPorts.formatRanges(missing), suggested: missing.length ? frpPorts.suggestedAllowPorts(allowPorts, needed) : allowPorts };
|
||||
}
|
||||
|
||||
/** The alert for a central server whose allow_ports leaves listed ports out (null when it doesn't). */
|
||||
function allowPortsProblem(server, check) {
|
||||
if (!check.missing) return null;
|
||||
const file = server.lastStats?.frpConfigPath || 'frps.ini';
|
||||
return { type: 'allow_ports', level: 'warning', message: `allow_ports in ${file} doesn't allow ${check.missing}: frps refuses tunnels on those ports. Set it to ${check.suggested} (Servers → ${server.name} → frp config → Edit → Use the Hub's allow_ports)` };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -314,5 +338,5 @@ module.exports = {
|
||||
createJoinToken, joinCommand, join, requireAgent,
|
||||
serverConfig, setServerConfig, cleanEnvValues, installDefaults,
|
||||
summariseStats, recordStats, rollupStats, serverProblems, runServerAlerts, restartsInTenMinutes,
|
||||
portRange, allocatePorts,
|
||||
portRange, allocatePorts, allowPortsCheck, allowPortsProblem,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user