Files
events-hub/backend/src/utils/servers.js
T
joshuaandClaude Opus 5.5 14dd608e37 Hub 2.10.0: emails laid out as Events' and Accounts'; FastPanel ^~ /api/
- src/utils/emailLayout.js: one layout for every Hub email (Cross Code
  header with the logo, heading, button with the link under it, notes,
  tables, job steps, code blocks, footer), HTML and plain text from the
  same blocks, everything escaped. mail.sendMail attaches the logo.
- Every email moved onto it: job reports, alerts, update requests, the
  SMTP test, notices, and all emails to site admins. Billing keeps its own.
- The FastPanel email and the install page give the backend as nginx config
  with location ^~ /api/ (FastPanel's static-file rule took /api/...png).
- Proxy done checks /api/proxy-check.png doesn't reach the frontend.
- deployment.md: ^~ for the Hub's own /api/ too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:40:55 +02:00

293 lines
18 KiB
JavaScript

/**
* Servers and their agents (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md): joining with a
* one-time token, checking the agent's signed requests, the server's configuration (encrypted),
* stats, the port list and server alerts. The agent polls; the Hub never connects to a server.
*/
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { agent } = require('@crosscode/contracts');
const signing = require('@crosscode/contracts/signing');
const prisma = require('../config/db');
const { encrypt, decrypt } = require('./crypto');
const { getSettings } = require('./settings');
const { sendMail } = require('./mail');
const { render } = require('./emailLayout');
const JOIN_TOKEN_MINUTES = 60;
const POLL_SECONDS = 30;
const STATS_SECONDS = 60;
const MIN = 60 * 1000;
const DAY = 24 * 60 * MIN;
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
const newId = prefix => `${prefix}_${crypto.randomBytes(12).toString('base64url')}`;
const hashToken = token => crypto.createHash('sha256').update(String(token)).digest('hex');
// ─── The Hub's job-signing key (not the licence key) ─────────────────────────
let jobKey = null;
/** { privateKeyPem, publicKey (raw base64url) } from HUB_JOB_SIGNING_KEY(_FILE). */
function jobSigningKey() {
if (jobKey) return jobKey;
let pem = (process.env.HUB_JOB_SIGNING_KEY || '').replace(/\\n/g, '\n').trim();
if (!pem && process.env.HUB_JOB_SIGNING_KEY_FILE) pem = fs.readFileSync(path.resolve(process.env.HUB_JOB_SIGNING_KEY_FILE), 'utf8');
if (!pem) throw fail(503, 'NO_JOB_KEY', 'No job-signing key: set HUB_JOB_SIGNING_KEY_FILE (npm run generate-keys -- --job).');
if (crypto.createPrivateKey(pem).asymmetricKeyType !== 'ed25519') throw fail(503, 'NO_JOB_KEY', 'The job-signing key must be Ed25519.');
jobKey = { privateKeyPem: pem, publicKey: signing.publicKeyOf(pem) };
return jobKey;
}
function resetJobKeyForTests() { jobKey = null; }
// ─── Joining ──────────────────────────────────────────────────────────────────
async function createJoinToken({ name, mode = 'church', adminId = null }, now = new Date()) {
const clean = String(name || '').trim().slice(0, 100);
if (!clean) throw fail(400, 'BAD_REQUEST', 'Give the server a name.');
if (!['church', 'central'].includes(mode)) throw fail(400, 'BAD_REQUEST', 'mode is church or central.');
jobSigningKey(); // can't join servers without it
const token = crypto.randomBytes(32).toString('base64url');
const expiresAt = new Date(now.getTime() + JOIN_TOKEN_MINUTES * MIN);
await prisma.serverJoinToken.create({ data: { tokenHash: hashToken(token), name: clean, mode, expiresAt, createdById: adminId } });
return { token, expiresAt, mode, name: clean };
}
/** The install command shown with a token. */
function joinCommand(token, mode, hubUrl = process.env.HUB_PUBLIC_URL || process.env.PUBLIC_URL || 'https://hub.crosscode.co.za') {
const script = 'https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh';
return `curl -fsSL ${script} | sudo bash -s -- --hub ${hubUrl.replace(/\/$/, '')} --token ${token}${mode === 'central' ? ' --central' : ''}`;
}
/** POST /api/agent/v1/join: the token is the proof; it works once, within the hour. */
async function join(body, now = new Date()) {
const parsed = agent.joinRequestSchema.safeParse(body);
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not a join request.');
const req = parsed.data;
const row = await prisma.serverJoinToken.findUnique({ where: { tokenHash: hashToken(req.token) } });
if (!row || row.usedAt || row.expiresAt < now) throw fail(403, 'BAD_TOKEN', 'This join token is unknown, used or expired. Make a new one in the Hub (Servers → Add server).');
if (row.mode !== req.mode) throw fail(400, 'WRONG_MODE', `This token is for a ${row.mode} server.`);
const { publicKey } = jobSigningKey();
const server = await prisma.$transaction(async tx => {
const used = await tx.serverJoinToken.updateMany({ where: { id: row.id, usedAt: null }, data: { usedAt: now } });
if (used.count !== 1) throw fail(403, 'BAD_TOKEN', 'This join token was just used.');
const created = await tx.server.create({ data: { id: newId('srv'), name: row.name, mode: req.mode, hostname: req.hostname, ed25519Key: req.publicKeys.ed25519, x25519Key: req.publicKeys.x25519, agentVersion: req.agentVersion, lastSeenAt: now } });
await tx.serverJoinToken.update({ where: { id: row.id }, data: { serverId: created.id } });
return created;
});
return { serverId: server.id, hubJobKey: publicKey, pollSeconds: POLL_SECONDS, statsSeconds: STATS_SECONDS };
}
/**
* Express middleware for signed agent requests: the server's Ed25519 key over timestamp + raw body.
* Sets req.server. A removed server is refused.
*/
async function requireAgent(req, res, next) {
try {
const id = String(req.headers[agent.AGENT_HEADERS.server] || '');
const server = /^srv_[A-Za-z0-9_-]{8,64}$/.test(id) ? await prisma.server.findUnique({ where: { id } }) : null;
if (!server || server.removedAt) return res.status(404).json({ code: 'SERVER_NOT_FOUND', message: 'This server isn\'t joined to the Hub (or was removed).' });
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(req.rawBody ?? '', 'utf8');
const v = signing.verifyAgentRequest({ publicKey: server.ed25519Key, timestamp: req.headers[agent.AGENT_HEADERS.timestamp], signature: req.headers[agent.AGENT_HEADERS.signature], rawBody: raw });
if (!v.ok) return res.status(401).json({ code: v.code, message: v.code === 'STALE_REQUEST' ? 'The server\'s clock is more than 5 minutes off.' : 'Bad signature.' });
req.server = server;
next();
} catch (e) {
next(e);
}
}
// ─── Configuration (§5) ───────────────────────────────────────────────────────
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
function serverConfig(server) {
if (!server?.config) return {};
try { return JSON.parse(decrypt(server.config)); } catch { return {}; }
}
function cleanEnvValues(values, what) {
if (!values || typeof values !== 'object' || Array.isArray(values)) throw fail(400, 'BAD_REQUEST', `${what}: expected NAME → value.`);
const out = {};
for (const [k, v] of Object.entries(values)) {
if (!ENV_NAME.test(k)) throw fail(400, 'BAD_REQUEST', `${what}: ${k} isn't a variable name (A-Z, 0-9, _).`);
const s = v == null ? '' : String(v);
if (/[\r\n]/.test(s) || s.length > 4000) throw fail(400, 'BAD_REQUEST', `${what}: ${k} can't have newlines or be over 4000 characters.`);
if (s.trim() !== '') out[k] = s.trim();
}
return out;
}
async function setServerConfig(serverId, values) {
const clean = cleanEnvValues(values, 'Server configuration');
if (clean.DB_ADMIN_URL && !/^postgres(ql)?:\/\//.test(clean.DB_ADMIN_URL)) throw fail(400, 'BAD_REQUEST', 'DB_ADMIN_URL is a postgresql:// URL.');
await prisma.server.update({ where: { id: serverId }, data: { config: Object.keys(clean).length ? encrypt(JSON.stringify(clean)) : null } });
return clean;
}
/** Install defaults (Settings → Install defaults): the same for every install. */
async function installDefaults() {
const s = await getSettings();
try { return JSON.parse(s.install_defaults || '{}'); } catch { return {}; }
}
// ─── Stats (§10) ──────────────────────────────────────────────────────────────
function summariseStats(stats) {
const ram = stats.ram.totalBytes > 0 ? (stats.ram.usedBytes / stats.ram.totalBytes) * 100 : 0;
const disk = stats.disks.reduce((m, d) => Math.max(m, d.totalBytes > 0 ? (d.usedBytes / d.totalBytes) * 100 : 0), 0);
return { cpu: stats.cpu.percent, ram, disk, load1: stats.cpu.load1 };
}
async function recordStats(server, body, now = new Date()) {
const parsed = agent.agentStatsSchema.safeParse(body);
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not crosscode.agent-stats/1.');
const stats = parsed.data;
const s = summariseStats(stats);
await prisma.$transaction([
prisma.serverStat.create({ data: { serverId: server.id, at: now, granularity: 'minute', cpuPercent: s.cpu, cpuPeak: s.cpu, ramUsedPercent: s.ram, ramPeak: s.ram, ramUsedBytes: BigInt(Math.round(stats.ram.usedBytes)), ramTotalBytes: BigInt(Math.round(stats.ram.totalBytes)), diskUsedPercent: s.disk, load1: s.load1 } }),
prisma.server.update({ where: { id: server.id }, data: { lastStats: stats, lastSeenAt: now, agentVersion: stats.versions.agent } }),
]);
rememberRestarts(server.id, stats, now);
}
/** Minutes older than 7 days become hours (average and peak); hours older than 90 days go. */
async function rollupStats(now = new Date(), db = prisma) {
const minuteCutoff = new Date(now.getTime() - 7 * DAY);
const hourCutoff = new Date(now.getTime() - 90 * DAY);
await db.$executeRawUnsafe(`
INSERT INTO "ServerStat" ("id", "serverId", "at", "granularity", "cpuPercent", "cpuPeak", "ramUsedPercent", "ramPeak", "ramUsedBytes", "ramTotalBytes", "diskUsedPercent", "load1")
SELECT gen_random_uuid()::text, "serverId", date_trunc('hour', "at"), 'hour', avg("cpuPercent"), max("cpuPeak"), avg("ramUsedPercent"), max("ramPeak"),
avg("ramUsedBytes")::bigint, max("ramTotalBytes"), max("diskUsedPercent"), avg("load1")
FROM "ServerStat" WHERE "granularity" = 'minute' AND "at" < $1
GROUP BY "serverId", date_trunc('hour', "at")`, minuteCutoff);
const minutes = await db.serverStat.deleteMany({ where: { granularity: 'minute', at: { lt: minuteCutoff } } });
const hours = await db.serverStat.deleteMany({ where: { granularity: 'hour', at: { lt: hourCutoff } } });
return { minutes: minutes.count, hours: hours.count };
}
// PM2 restart counts seen over the last 10 minutes, per server (the Hub is one process).
const restartHistory = new Map();
function rememberRestarts(serverId, stats, now) {
const list = (restartHistory.get(serverId) || []).filter(e => now - e.at <= 10 * MIN);
list.push({ at: now, restarts: Object.fromEntries(stats.processes.map(p => [p.name, p.restarts])) });
restartHistory.set(serverId, list);
}
function restartsInTenMinutes(serverId) {
const list = restartHistory.get(serverId) || [];
if (list.length < 2) return [];
const first = list[0].restarts;
const last = list[list.length - 1].restarts;
return Object.entries(last).filter(([name, n]) => first[name] != null && n - first[name] > 5).map(([name, n]) => `${name} restarted ${n - first[name]} times in 10 minutes`);
}
// ─── Alerts (§10) ─────────────────────────────────────────────────────────────
/**
* Whether the agent is busy with a job the Hub handed it, still within that job's time limit (and
* the 10 minutes the Hub allows on top, as in jobs.poll). Agents before 1.1.1 neither poll nor send
* stats while a job runs (an install or update can take 30 minutes), so silence then isn't the
* agent being down. Once the limit has passed, the job is failed and silence counts again.
*/
function busyWithJob(job, now = new Date()) {
if (!job || job.status !== 'delivered' || !job.deliveredAt) return false;
const limit = ((agent.JOB_TIME_LIMIT_MINUTES[job.type] || 30) + 10) * MIN;
return now - new Date(job.deliveredAt) < limit;
}
/** The problems a server has now: [{ type, level, message }]. Pure, for tests. `runningJob`: the job it's running, if any. */
function serverProblems(server, recent, restarts, now = new Date(), runningJob = null) {
const out = [];
if ((!server.lastSeenAt || now - new Date(server.lastSeenAt) > 5 * MIN) && !busyWithJob(runningJob, now)) {
out.push({ type: 'agent_silent', level: 'critical', message: server.lastSeenAt ? `The agent hasn't been heard from since ${new Date(server.lastSeenAt).toISOString()}` : 'The agent has never reported' });
}
const st = server.lastStats;
if (st) {
for (const d of st.disks || []) {
const used = d.totalBytes > 0 ? (d.usedBytes / d.totalBytes) * 100 : 0;
if (used > 85) out.push({ type: `disk:${d.mount}`, level: 'warning', message: `Disk ${d.mount} is ${Math.round(used)}% full` });
}
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' });
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' });
if (st.central.frpsRunning === false) out.push({ type: 'frps_down', level: 'critical', message: 'frps isn\'t running: no church site can be reached' });
}
}
for (const r of restarts) out.push({ type: `restarts:${r.split(' ')[0]}`, level: 'warning', message: r });
return out;
}
async function runServerAlerts(now = new Date()) {
const settings = await getSettings();
const servers = await prisma.server.findMany({ where: { removedAt: null }, include: { alerts: { where: { resolvedAt: null } } } });
const opened = [];
const cleared = [];
for (const server of servers) {
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);
const open = new Map(server.alerts.map(a => [a.type, a]));
for (const p of current) {
if (open.has(p.type)) continue;
await prisma.serverAlert.create({ data: { serverId: server.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
opened.push({ level: p.level, text: `${server.name}: ${p.message}` });
}
const types = new Set(current.map(p => p.type));
for (const [type, a] of open) {
if (types.has(type)) continue;
await prisma.serverAlert.update({ where: { id: a.id }, data: { resolvedAt: now } });
cleared.push(`${server.name}: ${a.message}`);
}
}
if ((opened.length || cleared.length) && settings.alert_email) {
const subject = opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'server alerts cleared';
const email = render({
heading: opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'Server alerts cleared',
blocks: [
...opened.map(o => ({ note: { kind: o.level === 'critical' ? 'danger' : 'warning', text: o.text } })),
cleared.length ? { note: { kind: 'success', title: 'Cleared', text: cleared.join('\n') } } : null,
{ button: { label: 'Open Servers', url: `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/servers` } },
],
footer: 'Sent by the Cross Code Hub to the alert address in Settings.',
});
await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: ${subject}`, ...email }).catch(e => console.warn('[servers] alert email failed:', e?.message));
}
return { opened: opened.length, cleared: cleared.length };
}
// ─── The port list (§6) ───────────────────────────────────────────────────────
async function portRange() {
const s = await getSettings();
const from = parseInt(s.port_range_start, 10) || 20000;
const to = parseInt(s.port_range_end, 10) || 29999;
return { from, to };
}
/** Two free ports (web, api) for a deployment, in one transaction (unique across all servers). */
async function allocatePorts(tx, serverId, now = new Date()) {
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));
const free = [];
for (let p = from; p <= to && free.length < 2; p++) if (!taken.has(p)) free.push(p);
if (free.length < 2) throw fail(409, 'NO_PORTS', `No free ports left between ${from} and ${to} (Settings → Servers).`);
const [web, api] = free;
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await tx.port.upsert({ where: { port }, update: { serverId, role, releasedAt: null, deploymentId: null, note: null }, create: { port, serverId, role } });
}
return { web, api };
}
module.exports = {
busyWithJob,
POLL_SECONDS, STATS_SECONDS, newId, hashToken, jobSigningKey, resetJobKeyForTests,
createJoinToken, joinCommand, join, requireAgent,
serverConfig, setServerConfig, cleanEnvValues, installDefaults,
summariseStats, recordStats, rollupStats, serverProblems, runServerAlerts, restartsInTenMinutes,
portRange, allocatePorts,
};