diff --git a/CHANGELOG.md b/CHANGELOG.md index bc04ced..2dd8bbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,25 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.20.0] - 2026-11-23 + +No migration. `GET /api/admin/ports` and a server's `frp` state carry more fields; nothing is removed. + +### Added + +- **The port list says what each port is for**: the church, the product and web or API, linked to the + install, with its domain (and "uninstalled, free from …" once it's gone). Ports held for an + install's port check say so. +- **A church server's hand-written frpc tunnels are listed as taken**, named after the tunnel + (`frpc tunnel "games-night" on church-1`), each time its frp config is read. A tunnel taken out of + frpc is taken off the list at the next read. Ports of installs and ports marked by hand are left + as they are. +- **frps's allow_ports is checked against the port list.** It must allow the Hub's port range and + every listed port outside it, so installs never need an frps restart. When it doesn't, the + central server gets an alert (and the alert email) naming the missing ports and the value to set, + the frp config card says so, and **Edit → Use the Hub's allow_ports** puts that value in the file + (INI or TOML) to save with a restart. + ## [2.19.0] - 2026-11-23 **Migration:** a new table, `AgentRelease`. No API change for existing calls. diff --git a/backend/package-lock.json b/backend/package-lock.json index 89e7f8c..aac3022 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "2.19.0", + "version": "2.20.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.19.0", + "version": "2.20.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", diff --git a/backend/package.json b/backend/package.json index 06004d8..0398d0e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.19.0", + "version": "2.20.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js index 021f659..b1c58f6 100644 --- a/backend/src/routes/servers.js +++ b/backend/src/routes/servers.js @@ -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 }); })); diff --git a/backend/src/utils/frpPorts.js b/backend/src/utils/frpPorts.js new file mode 100644 index 0000000..2effc62 --- /dev/null +++ b/backend/src/utils/frpPorts.js @@ -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 }; diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index 5187a83..cc5269a 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -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, diff --git a/backend/src/utils/servers.js b/backend/src/utils/servers.js index b1039ec..53ea50b 100644 --- a/backend/src/utils/servers.js +++ b/backend/src/utils/servers.js @@ -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, }; diff --git a/backend/tests/frpPorts.test.js b/backend/tests/frpPorts.test.js new file mode 100644 index 0000000..8df9dac --- /dev/null +++ b/backend/tests/frpPorts.test.js @@ -0,0 +1,62 @@ +// Hub 2.20.0: frps's allow_ports against the port list, and frpc's hand-written tunnels. +const f = require('../src/utils/frpPorts'); + +describe('ranges', () => { + test('parses, merges and formats', () => { + expect(f.parseRanges('3000, 20000-29999,3001,bad,5-4')).toEqual([[3000, 3001], [20000, 29999]]); + expect(f.formatRanges([[5, 5], [1, 3], [4, 4], [10, 12]])).toBe('1-5,10-12'); + }); + + test('needed: the range and listed ports outside it (not freed ones)', () => { + const rows = [{ port: 3000 }, { port: 20005 }, { port: 8182 }, { port: 5000, releasedAt: new Date() }]; + expect(f.formatRanges(f.neededRanges(rows, { from: 20000, to: 29999 }))).toBe('3000,8182,20000-29999'); + }); + + test('missing: what allow_ports leaves out; none when every port is allowed', () => { + const needed = f.parseRanges('3000,8182,20000-29999'); + expect(f.formatRanges(f.missingRanges('3000,20000-20007', needed))).toBe('8182,20008-29999'); + expect(f.formatRanges(f.missingRanges('1-65535', needed))).toBe(''); + expect(f.missingRanges(null, needed)).toEqual([]); + expect(f.missingRanges(' ', needed)).toEqual([]); + expect(f.formatRanges(f.missingRanges('20100-20200', f.parseRanges('20000-20300')))).toBe('20000-20099,20201-20300'); + }); + + test('suggested keeps what is allowed now and adds what is missing', () => { + expect(f.suggestedAllowPorts('3000,7000,20000-20007', f.parseRanges('3000,8182,20000-29999'))).toBe('3000,7000,8182,20000-29999'); + }); +}); + +describe('withAllowPorts', () => { + test('INI: replaces it in [common], or adds it there', () => { + const ini = '[common]\r\nbind_port = 7000\r\nallow_ports = 3000\r\n\r\n[x]\r\nallow_ports = 1\r\n'; + expect(f.withAllowPorts(ini, 'ini', '3000,20000-29999')).toBe('[common]\r\nbind_port = 7000\r\nallow_ports = 3000,20000-29999\r\n\r\n[x]\r\nallow_ports = 1\r\n'); + expect(f.withAllowPorts('[common]\nbind_port = 7000\n', 'ini', '1-2')).toBe('[common]\nallow_ports = 1-2\nbind_port = 7000\n'); + }); + + test('TOML: replaces a one-line or several-line allowPorts, or adds it before the first table', () => { + expect(f.withAllowPorts('bindPort = 7000\nallowPorts = [{ single = 3000 }]\n', 'toml', '3000,20000-29999')) + .toBe('bindPort = 7000\nallowPorts = [{ single = 3000 }, { start = 20000, end = 29999 }]\n'); + expect(f.withAllowPorts('bindPort = 7000\nallowPorts = [\n { single = 3000 },\n { start = 1, end = 2 }\n]\nproxyBindAddr = "127.0.0.1"\n', 'toml', '5')) + .toBe('bindPort = 7000\nallowPorts = [{ single = 5 }]\nproxyBindAddr = "127.0.0.1"\n'); + expect(f.withAllowPorts('bindPort = 7000\n[auth]\ntoken = "x"\n', 'toml', '5')) + .toBe('bindPort = 7000\nallowPorts = [{ single = 5 }]\n[auth]\ntoken = "x"\n'); + }); +}); + +describe('frpcTunnels', () => { + test('INI: each section but [common], by its remote_port', () => { + const ini = '[common]\nserver_port = 7000\nadmin_port = 7400\n\n[events-frontend]\ntype = tcp\nlocal_port = 3000\nremote_port = 3000\n\n# >>> crosscode:hope:events\n[hope-events-web]\nremote_port = 20000\n[no-port]\ntype = tcp\n'; + expect(f.frpcTunnels(ini, 'ini')).toEqual([{ name: 'events-frontend', port: 3000 }, { name: 'hope-events-web', port: 20000 }]); + }); + + test('TOML: [[proxies]] by name and remotePort', () => { + const toml = 'serverPort = 7000\n[auth]\ntoken = "x"\n\n[[proxies]]\nname = "events-frontend"\ntype = "tcp"\nlocalPort = 3000\nremotePort = 3000 # web\n\n[[visitors]]\nname = "v"\nremotePort = 9\n'; + expect(f.frpcTunnels(toml, 'toml')).toEqual([{ name: 'events-frontend', port: 3000 }]); + }); + + test('tunnel notes', () => { + expect(f.tunnelNote('games-night', 'church-1')).toBe('frpc tunnel "games-night" on church-1'); + expect(f.isTunnelNote(f.tunnelNote('a', 'b'))).toBe(true); + expect(f.isTunnelNote('by hand')).toBe(false); + }); +}); diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js index 2b338dd..48d44ed 100644 --- a/backend/tests/servers.test.js +++ b/backend/tests/servers.test.js @@ -1115,3 +1115,53 @@ describe('a second product while another is being uninstalled (2.12.0)', () => { expect(mockMails.some(m => m.subject.includes('Uninstalled: hope') && m.text.includes('folder and app user'))).toBe(true); }); }); + +describe('frps allow_ports and port labels (Hub 2.20.0)', () => { + const frpcIni = [ + '[common]', 'server_port = 7000', 'token = ••••••', '', + '[events-frontend]', 'type = tcp', 'local_port = 3000', 'remote_port = 3000', '', + '[games-night]', 'type = tcp', 'local_port = 3201', 'remote_port = 3201', '', + '# >>> crosscode:hope:events', '[hope-events-web]', 'type = tcp', 'local_port = 20000', 'remote_port = 20000', '# <<< crosscode:hope:events', '', + ].join('\n'); + const read = content => ({ service: 'frpc', path: '/etc/frp/frpc.ini', source: 'systemd', found: true, format: 'ini', content, hidden: ['token'], proxyBindAddr: null, allowPorts: null, serviceRunning: true, readAt: NOW.toISOString() }); + + test("a church server's hand-written tunnels are listed as taken, and taken off when they go", async () => { + const { server } = await joinServer(); + await db.port.create({ data: { port: 20000, serverId: server.id, role: 'web', deploymentId: 'dep-1' } }); + await db.port.create({ data: { port: 3201, role: 'taken', note: 'mine' } }); + await jobs.listFrpcTunnels(server.id, read(frpcIni), NOW); + const rows = Object.fromEntries((await db.port.findMany({})).map(r => [r.port, r])); + expect(rows[3000]).toMatchObject({ role: 'taken', serverId: server.id, note: 'frpc tunnel "events-frontend" on church-1' }); + expect(rows[3201].note).toBe('mine'); // marked by hand: left as it is + expect(rows[20000]).toMatchObject({ role: 'web', deploymentId: 'dep-1' }); // an install's + + await jobs.listFrpcTunnels(server.id, read(frpcIni.replace('remote_port = 3000', 'remote_port = 3005')), NOW); + const after = (await db.port.findMany({})).map(r => r.port).sort((a, b) => a - b); + expect(after).toEqual([3005, 3201, 20000]); + + // A central server's frps config lists nothing. + const central = (await joinServer('central', 'central-1')).server; + await jobs.listFrpcTunnels(central.id, read('[common]\n[x]\nremote_port = 4444\n'), NOW); + expect(await db.port.findUnique({ where: { port: 4444 } })).toBeNull(); + }); + + test('the central server is warned when allow_ports leaves out the range or a listed port', async () => { + const central = (await joinServer('central', 'central-1')).server; + await db.port.create({ data: { port: 3000, role: 'taken', note: 'frpc tunnel "events-frontend" on church-1' } }); + await db.port.create({ data: { port: 5000, role: 'taken', releasedAt: NOW } }); + const check = await servers.allowPortsCheck('3000,20000-20007'); + expect(check).toMatchObject({ needed: '3000,20000-29999', missing: '20008-29999', suggested: '3000,20000-29999' }); + expect((await servers.allowPortsCheck('3000,20000-29999')).missing).toBe(''); + expect((await servers.allowPortsCheck(null)).missing).toBe(''); + + await db.server.update({ where: { id: central.id }, data: { lastSeenAt: NOW, lastStats: { disks: [], frpConfigPath: '/etc/frp/frps.ini', central: { proxyBindAddr: '127.0.0.1', allowPorts: '20000-29999', frpsRunning: true } } } }); + await servers.runServerAlerts(NOW); + const alert = await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } }); + expect(alert.message).toContain("doesn't allow 3000"); + expect(alert.message).toContain('Set it to 3000,20000-29999'); + + await db.server.update({ where: { id: central.id }, data: { lastStats: { disks: [], frpConfigPath: '/etc/frp/frps.ini', central: { proxyBindAddr: '127.0.0.1', allowPorts: '3000,20000-29999', frpsRunning: true } } } }); + await servers.runServerAlerts(NOW); + expect((await db.serverAlert.findFirst({ where: { serverId: central.id, type: 'allow_ports' } })).resolvedAt).toEqual(NOW); + }); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f6851fd..1d94eca 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.19.0", + "version": "2.20.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.19.0", + "version": "2.20.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index 98f7ae0..3732dd4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.19.0", + "version": "2.20.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/servers/settings/page.tsx b/frontend/src/app/(hub)/servers/settings/page.tsx index 7416f8b..51210e6 100644 --- a/frontend/src/app/(hub)/servers/settings/page.tsx +++ b/frontend/src/app/(hub)/servers/settings/page.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; import { Plus, Trash2 } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { fmtDate } from "@/lib/format"; @@ -9,7 +10,30 @@ import { Field, Fields, FormError, Loading, Modal, ModalButtons, PageMessage, Pa import { ServersNav } from "@/components/servers"; type Msg = { type: "ok" | "err"; text: string } | null; -type Port = { port: number; role: string; note: string | null; releasedAt: string | null; deploymentId: string | null; server: { id: string; name: string } | null }; +type Port = { + port: number; role: string; note: string | null; releasedAt: string | null; deploymentId: string | null; server: { id: string; name: string } | null; + deployment: { id: string; shortName: string; product: string; productName: string; domain: string; status: string } | null; +}; + +const ROLE: Record = { web: "web", api: "API" }; + +/** Hub 2.20.0: what a port is used for: the install and its part, a port check, or something else. */ +function PortUse({ p }: { p: Port }) { + const d = p.deployment; + const freeFrom = p.releasedAt ? fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false) : null; + if (d && (p.role === "web" || p.role === "api")) { + return ( +
+ {d.shortName} · {d.productName} {ROLE[p.role]} +
{d.domain}{freeFrom ? ` · uninstalled, free from ${freeFrom}` : d.status !== "live" ? ` · ${d.status}` : ""}
+
+ ); + } + if (freeFrom) return <>free from {freeFrom}; + if (p.role === "candidate") return held for an install's port check; + if (p.role === "taken") return <>taken{p.note ? "" : " (by hand)"}; + return <>{ROLE[p.role] || p.role}; +} type Defaults = { defaults: [string, string][]; range: { from: string; to: string }; ip: string }; @@ -124,12 +148,12 @@ export default function ServerSettingsPage() {

Port list

-

Every port frps opens on the central server must be unique across servers. Mark ports used by anything else (today's tunnels written by hand) as taken.

+

Every port frps opens on the central server must be unique across servers. A church server's frpc tunnels written by hand are listed as taken each time its frp config is read (Servers → the server → frp config → Read now); mark anything else as taken by hand. frps's allow_ports must cover the port range and every listed port outside it: the central server's page warns when it doesn't.

{!ports ? : ( {portsPaged.rows.map(p => ( - + ))}
PortUseServerNote
{p.port}{p.releasedAt ? `free from ${fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false)}` : p.role}{p.server?.name || "–"}{p.note}
{p.port}{p.server?.name || "–"}{p.note} {(p.role === "taken" || p.releasedAt) && }
diff --git a/frontend/src/components/FrpConfig.tsx b/frontend/src/components/FrpConfig.tsx index cb9f4c0..9e2d0ef 100644 --- a/frontend/src/components/FrpConfig.tsx +++ b/frontend/src/components/FrpConfig.tsx @@ -29,6 +29,8 @@ export type FrpState = { last: { id: string; type: string; status: string; message: string | null; finishedAt: string | null } | null; minAgent: string; hidden: string; + /** Hub 2.20.0, central servers: what allow_ports must cover, what it leaves out, and the file fixed. */ + allowPorts?: { needed: string; missing: string; suggested: string | null; fixedContent: string | null } | null; }; type Msg = { type: "ok" | "err"; text: string } | null; @@ -64,6 +66,12 @@ function FrpEditModal({ serverId, frp, read, onClose, onSent }: { serverId: stri return ( Edit {read.path}} onClose={onClose} dirty={edited} wide>
+ {frp.allowPorts?.fixedContent && ( +
+ allow_ports leaves out {frp.allowPorts.missing}. The Hub's value: {frp.allowPorts.suggested} + +
+ )}