Files
events-hub/backend/src/utils/jobs.js
T
joshuaandClaude Opus 5.5 915ae82416 Fix installs stuck as "Uninstalling"; remove a failed install's record
An uninstall whose export failed was cancelled, but its install stayed
"uninstalling" for good. It now goes back to live (or waiting for the
proxy), like a failed or hand-cancelled uninstall.

Uninstall is refused for a failed install (nothing of it is on the
server, so the export always failed) and for one still installing. A
failed install's page offers "Remove the record" instead, which also
clears records already stuck from before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:44:17 +02:00

682 lines
46 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Jobs for server agents (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md §4, §7–9, §11):
* installs, scheduled / emergency / batch updates with notice to the church, adopting existing
* installs, uninstall with an encrypted export, and the reports that come back.
*
* A job row is made when it's planned; the signed job (crosscode.agent-job/1, with the config
* sealed to the server's key) is only built when the agent picks it up, so it always carries the
* current server configuration. Each server gets one job at a time. A job whose time window
* passes before the agent picks it up is `missed`: it never runs late without a new notice.
*/
const dns = require('dns').promises;
const { agent } = require('@crosscode/contracts');
const signing = require('@crosscode/contracts/signing');
const prisma = require('../config/db');
const { decrypt } = require('./crypto');
const { verifyCode } = require('./totp');
const { sendMail } = require('./mail');
const { getSettings } = require('./settings');
const { PRODUCT_NAMES } = require('./products');
const { generateLicence } = require('./licences');
const { unmetRequirementsFor } = require('./releases');
const { compareVersions } = require('./alerts');
const servers = require('./servers');
const { missingFor } = require('./envTemplates');
const MIN = 60 * 1000;
const HOUR = 60 * MIN;
const DAY = 24 * HOUR;
const WINDOW_MIN = 15;
const SCHEDULE_MIN_HOURS = 4;
const EMERGENCY_MIN_MINUTES = 15;
const AGENT_ONLINE_MS = 2 * MIN;
const EXPORT_DAYS = 30;
const SHORT_NAME = /^[a-z][a-z0-9-]{1,30}$/;
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
const fail = (status, code, message) => Object.assign(new Error(message), { status, code });
const hubUrl = () => (process.env.FRONTEND_URL || '').replace(/\/$/, '');
const sast = d => new Date(d).toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' });
// Report statuses → job statuses.
const FINAL = { succeeded: 'succeeded', failed: 'failed', 'rolled-back': 'rolled_back', refused: 'refused', expired: 'expired' };
const DONE = ['succeeded', 'failed', 'rolled_back', 'refused', 'expired', 'missed', 'cancelled'];
// ─── Making jobs ──────────────────────────────────────────────────────────────
/** Types whose job brings the .env values (sealed to the server). */
const NEEDS_CONFIG = new Set(['install', 'deploy', 'adopt', 'add-product']);
async function makeJob(db, { serverId, type, args, deploymentId = null, notBefore = new Date(), windowMinutes = WINDOW_MIN, status = 'queued', scheduled = false, emergency = false, reason = null, batchId = null, batchOrder = null, noticeId = null, createdById = null }) {
const parsed = agent.jobArgsSchemas[type]?.safeParse(args);
if (!parsed?.success) throw fail(400, 'BAD_JOB', `The ${type} job's arguments aren't valid: ${parsed?.error.issues[0]?.message || 'unknown type'}.`);
return db.job.create({
data: {
id: servers.newId('job'), serverId, type, args: parsed.data, deploymentId, status, notBefore,
expiresAt: new Date(notBefore.getTime() + windowMinutes * MIN), scheduled, emergency, reason, batchId, batchOrder, noticeId, createdById,
},
});
}
/** The .env values for a deployment's job, by layer (§5). */
async function jobConfig(server, deployment) {
const config = { server: servers.serverConfig(server), defaults: await servers.installDefaults(), install: {} };
if (deployment) {
const licence = deployment.licenceId ? await prisma.licence.findUnique({ where: { id: deployment.licenceId } }) : null;
const values = {};
if (deployment.timezone) values.APP_TIMEZONE = deployment.timezone;
if (licence?.key) values.HUB_LICENCE_KEY = licence.key;
if (deployment.adminName) values.HUB_ADMIN_NAME = deployment.adminName;
if (deployment.adminEmail) values.HUB_ADMIN_EMAIL = deployment.adminEmail;
config.install[deployment.product] = values;
}
return agent.jobConfigSchema.parse(config);
}
/** The signed job the agent receives. */
async function signedJob(job, server) {
const deployment = job.deploymentId ? await prisma.deployment.findUnique({ where: { id: job.deploymentId } }) : null;
const unsigned = {
schema: 'crosscode.agent-job/1', id: job.id, serverId: server.id, type: job.type, args: job.args,
config: NEEDS_CONFIG.has(job.type) ? signing.sealConfig(await jobConfig(server, deployment), server.x25519Key) : null,
notBefore: job.notBefore.toISOString(), expiresAt: job.expiresAt.toISOString(),
};
return signing.signJob(unsigned, servers.jobSigningKey().privateKeyPem);
}
// ─── Poll and reports (agent API) ─────────────────────────────────────────────
/** POST /api/agent/v1/poll: the next job due for this server, one at a time. */
async function poll(server, body, now = new Date()) {
const parsed = agent.pollRequestSchema.safeParse(body);
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not a poll request.');
await prisma.server.update({ where: { id: server.id }, data: { lastSeenAt: now, agentVersion: parsed.data.agentVersion } });
const running = await prisma.job.findFirst({ where: { serverId: server.id, status: 'delivered' } });
if (running) {
const limit = (agent.JOB_TIME_LIMIT_MINUTES[running.type] || 30) + 10;
if (now - running.deliveredAt < limit * MIN) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
await finish(running, { status: 'failed', message: `No report within ${limit} minutes of handing it to the agent.` }, now);
}
const next = await prisma.job.findFirst({
where: { serverId: server.id, status: 'queued', notBefore: { lte: new Date(now.getTime() + 30 * 1000) }, expiresAt: { gt: now } },
orderBy: [{ notBefore: 'asc' }, { createdAt: 'asc' }],
});
if (!next) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
const claimed = await prisma.job.updateMany({ where: { id: next.id, status: 'queued' }, data: { status: 'delivered', deliveredAt: now } });
if (claimed.count !== 1) return { jobs: [], pollSeconds: servers.POLL_SECONDS };
return { jobs: [await signedJob(next, server)], pollSeconds: servers.POLL_SECONDS };
}
/** POST /api/agent/v1/report. The export key is used for the email, never stored. */
async function receiveReport(server, body, now = new Date()) {
const parsed = agent.agentReportSchema.safeParse(body);
if (!parsed.success) throw fail(400, 'BAD_REQUEST', 'Not crosscode.agent-report/1.');
const report = parsed.data;
if (report.serverId !== server.id) throw fail(403, 'WRONG_SERVER', 'That report is for another server.');
const job = await prisma.job.findUnique({ where: { id: report.jobId } });
if (!job || job.serverId !== server.id) throw fail(404, 'JOB_NOT_FOUND', 'Unknown job.');
if (DONE.includes(job.status)) return { ok: true, already: true };
const exportKey = typeof report.result?.key === 'string' ? report.result.key : null;
const stored = { ...report, result: { ...report.result, key: undefined } };
await finish(job, { status: FINAL[report.status] || 'failed', message: report.message || null, report: stored, exportKey }, now);
return { ok: true };
}
/** A job is done: record it, then what follows from it. */
async function finish(job, { status, message = null, report = null, exportKey = null }, now = new Date()) {
const updated = await prisma.job.update({ where: { id: job.id }, data: { status, message, report: report ?? undefined, finishedAt: now } });
try {
await afterJob(updated, { exportKey }, now);
} catch (e) {
console.error(`[jobs] after ${job.id} (${job.type}):`, e);
}
return updated;
}
async function afterJob(job, { exportKey }, now) {
const deployment = job.deploymentId ? await prisma.deployment.findUnique({ where: { id: job.deploymentId }, include: { server: true, customer: true, install: true } }) : null;
const ok = job.status === 'succeeded';
if (job.noticeId) await endNotice(job.noticeId, now);
switch (job.type) {
case 'install':
case 'add-product':
if (!deployment) break;
if (ok) {
const version = job.report?.result?.versions?.[deployment.product] || null;
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'waiting_for_proxy', version: version ? String(version).replace(/^.*@/, '') : null } });
await queueCentralCheck([deployment.webPort, deployment.apiPort], now);
await emailJoshua(`Installed: ${deployment.shortName} (${PRODUCT_NAMES[deployment.product]})`, `${jobReportText(job)}\n\n${await fastPanelText(deployment)}`);
} else {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'failed' } });
await prisma.port.deleteMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } } });
await emailJoshua(`Install failed: ${deployment.shortName}`, jobReportText(job));
}
break;
case 'deploy':
case 'adopt': {
if (!deployment) break;
const target = job.type === 'adopt' ? job.args.version : (job.args.versions || [])[0];
if (ok && target) await prisma.deployment.update({ where: { id: deployment.id }, data: { version: target.replace(/^.*@/, ''), status: deployment.status === 'failed' ? 'live' : deployment.status } });
if (job.scheduled) {
const name = PRODUCT_NAMES[deployment.product];
if (ok) await emailSiteAdmin(deployment, `${name} was updated`, `${name} at ${deployment.domain} was updated${target ? ` to ${target.replace(/^.*@/, '')}` : ''}. Everything is running again.`);
else await emailSiteAdmin(deployment, `${name} update didn't go through`, `The planned update of ${name} at ${deployment.domain} didn't go through, so the site is running the previous version. Nothing else changed; we'll be in touch about a new time.`);
}
await emailJoshua(`${job.type === 'adopt' ? 'Adopt' : 'Update'} ${ok ? 'done' : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job));
break;
}
case 'export':
if (!deployment) break;
if (ok && exportKey) {
const link = `${hubUrl()}/download/${job.args.exportId}#${exportKey}`;
const exp = await prisma.export.findUnique({ where: { id: job.args.exportId } });
await emailSiteAdmin(deployment, 'Your church\'s data from Cross Code', [
`Here is all of ${deployment.customer?.name || 'your church'}'s data from ${PRODUCT_NAMES[deployment.product]}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.`,
'', link, '',
`The link works until ${exp ? sast(exp.expiresAt) : `${EXPORT_DAYS} days from now`}. The file is encrypted, and only this link (the part after #) can open it: we can't read it, and we can't send the link again, so keep this email.`,
].join('\n'));
} else if (!ok) {
await emailJoshua(`Export failed: ${deployment.shortName}`, jobReportText(job));
}
break;
case 'uninstall':
if (!deployment) break;
if (ok) {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'removed', removedAt: now } });
await prisma.port.updateMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } }, data: { releasedAt: now, deploymentId: deployment.id } });
if (deployment.installId) await prisma.install.update({ where: { id: deployment.installId }, data: { releasedAt: now } });
await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 });
await emailJoshua(`Uninstalled: ${deployment.shortName}`, `${jobReportText(job)}\n\nRemove the FastPanel site ${deployment.domain} (ports ${deployment.webPort}, ${deployment.apiPort}).\nThe final backup is kept on the server for ${EXPORT_DAYS} days, then purged.`);
} else {
await prisma.deployment.update({ where: { id: deployment.id }, data: { status: statusBeforeUninstall(deployment) } });
await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReportText(job));
}
break;
case 'purge':
if (ok && deployment) {
const exports = await prisma.export.findMany({ where: { deploymentId: deployment.id, deletedAt: null } });
for (const e of exports) await prisma.export.update({ where: { id: e.id }, data: { data: null, deletedAt: now } });
}
break;
case 'check-ports':
if (!ok) await emailJoshua('Central server check: ports not ready', `${job.message || ''}\n\n${JSON.stringify(job.report?.result || {}, null, 2)}`);
break;
default:
break;
}
if (job.batchId) await advanceBatch(job, now);
}
// ─── Batches (§8): one at a time, stop at the first failure ───────────────────
async function advanceBatch(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') {
const next = rest[0];
await prisma.job.update({ where: { id: next.id }, data: { status: 'queued', notBefore: now, expiresAt: new Date(now.getTime() + WINDOW_MIN * MIN) } });
return;
}
for (const j of rest) {
await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: `Not run: ${job.id} before it in the same batch didn't succeed.`, finishedAt: now } });
if (j.noticeId) await endNotice(j.noticeId, now);
// An uninstall that won't run (its export failed): the install is still there. Before 2.3.2 it
// stayed "uninstalling" for good.
if (j.deployment && j.type === 'uninstall') {
await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: statusBeforeUninstall(j.deployment) } });
}
if (j.deployment && j.scheduled && j.type === 'deploy') {
await emailSiteAdmin(j.deployment, `${PRODUCT_NAMES[j.deployment.product]} update postponed`, `The planned update of ${PRODUCT_NAMES[j.deployment.product]} at ${j.deployment.domain} has been postponed. Your site keeps running as it is; we'll let you know the new time.`);
}
}
await emailJoshua('Batch stopped', `${jobReportText(job)}\n\n${rest.length} job(s) after it were cancelled and their churches told the update is postponed.`);
}
// ─── The scheduler (every 30 s) ───────────────────────────────────────────────
async function tick(now = new Date()) {
// Missed: its window passed before the agent picked it up. Nothing runs late.
const missed = await prisma.job.findMany({ where: { status: 'queued', expiresAt: { lte: now } }, include: { server: true } });
for (const job of missed) {
const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'missed', message: `The agent on ${job.server.name} didn't pick it up between ${job.notBefore.toISOString()} and ${job.expiresAt.toISOString()}.`, finishedAt: now } });
if (job.noticeId) await endNotice(job.noticeId, now);
await emailJoshua(`Missed job: ${job.type} on ${job.server.name}`, `${updated.message}\nNothing ran. A new time needs a new notice to the church.\n\n${hubUrl()}/jobs/${job.id}`);
if (job.batchId) await advanceBatch(updated, now);
if ((job.type === 'install' || job.type === 'add-product') && job.deploymentId) {
await prisma.deployment.update({ where: { id: job.deploymentId }, data: { status: 'failed' } });
}
}
// Reminders an hour before a scheduled update.
const soon = await prisma.job.findMany({ where: { scheduled: true, remindedAt: null, status: { in: ['queued', 'scheduled'] }, notBefore: { lte: new Date(now.getTime() + HOUR), gt: now } }, include: { deployment: { include: { install: true } } } });
for (const job of soon) {
await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } });
if (job.deployment && job.type !== 'uninstall') {
await emailSiteAdmin(job.deployment, `Reminder: ${PRODUCT_NAMES[job.deployment.product]} update at ${sast(job.notBefore)}`, `A reminder that ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} will be updated on ${sast(job.notBefore)}. The site will be unavailable for a few minutes.`);
}
}
// Purges: Joshua is told 3 days before the kept backup is deleted.
const purges = await prisma.job.findMany({ where: { type: 'purge', status: 'queued', remindedAt: null, notBefore: { lte: new Date(now.getTime() + 3 * DAY) } }, include: { deployment: true } });
for (const job of purges) {
await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } });
await emailJoshua(`Purge in 3 days: ${job.args.church}`, `${job.args.church}'s kept backup and its encrypted export will be deleted on ${sast(job.notBefore)}. To keep them 30 days longer, open the job: ${hubUrl()}/jobs/${job.id}`);
}
// Exports past their date.
await prisma.export.updateMany({ where: { deletedAt: null, expiresAt: { lte: now } }, data: { data: null, deletedAt: now } });
return { missed: missed.length, reminded: soon.length };
}
// ─── Emails ───────────────────────────────────────────────────────────────────
async function emailJoshua(subject, text) {
const { alert_email: to } = await getSettings();
if (to) await sendMail({ to, subject: `Cross Code Hub: ${subject}`, text }).catch(e => console.warn('[jobs] email failed:', e?.message));
}
function siteAdminEmail(deployment) {
return deployment.adminEmail || deployment.install?.adminContact?.email || null;
}
async function emailSiteAdmin(deployment, subject, text) {
const to = siteAdminEmail(deployment);
if (!to) return;
const hello = deployment.adminName || deployment.install?.adminContact?.name;
await sendMail({ to, subject, text: `${hello ? `Hi ${hello},\n\n` : ''}${text}\n\nCross Code` }).catch(e => console.warn('[jobs] email failed:', e?.message));
}
function jobReportText(job) {
const r = job.report || {};
const steps = (r.steps || []).map(s => ` ${s.outcome === 'ok' ? '✓' : s.outcome === 'failed' ? '✗' : '•'} ${s.name}${s.detail ? ` (${s.detail})` : ''}`).join('\n');
const tail = job.status === 'succeeded' ? '' : `\n\nLast log lines:\n${(r.log || []).slice(-30).join('\n')}`;
return `${job.type} ${job.id}: ${job.status}${job.message ? `\n${job.message}` : ''}\n\n${steps}${tail}\n\n${hubUrl()}/jobs/${job.id}`;
}
async function centralIp() {
return (await getSettings()).central_server_ip || '';
}
/** Whether the domain's DNS points at the central server: true, false, or null (not known). */
async function dnsPointsAtCentral(domain) {
const ip = await centralIp();
if (!ip) return null;
try {
return (await dns.resolve4(domain)).includes(ip);
} catch {
return false;
}
}
/** The FastPanel email (§11): what Joshua sets up by hand; nothing is done automatically. */
async function fastPanelText(d) {
const dnsOk = await dnsPointsAtCentral(d.domain);
const ip = await centralIp();
return [
`Set up in FastPanel: ${d.domain} (${d.customer?.name || d.shortName}, ${PRODUCT_NAMES[d.product]})`,
'',
`1. Add the site ${d.domain}.`,
'2. Proxy:',
` /api → http://127.0.0.1:${d.apiPort} (backend)`,
` everything else → http://127.0.0.1:${d.webPort} (frontend)`,
' Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.',
' Allow uploads up to 25 MB.',
'3. Turn on Let\'s Encrypt for the site.',
`4. DNS: ${d.domain} → ${ip || '<central server IP>'} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'})`,
`5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/installs/${d.id}`,
].join('\n');
}
// ─── Notices (banners) ────────────────────────────────────────────────────────
async function addNotice(deployment, { title, message, endsAt, level = 'maintenance' }, now) {
let installId = deployment.installId;
// Registered before registration made the link (Hub 2.1.0 builds before the VM test).
if (!installId && deployment.licenceId) {
const install = await prisma.install.findFirst({ where: { licenceId: deployment.licenceId } });
if (install) {
installId = install.id;
await prisma.deployment.update({ where: { id: deployment.id }, data: { installId } }).catch(() => {});
}
}
if (!installId) return null;
const n = await prisma.notice.create({ data: { title, message, level, allInstalls: false, installIds: [installId], showBanner: true, startsAt: now, endsAt } });
return n.id;
}
async function endNotice(noticeId, now) {
await prisma.notice.updateMany({ where: { id: noticeId, OR: [{ endsAt: null }, { endsAt: { gt: now } }] }, data: { endsAt: now } }).catch(() => {});
}
// ─── Admin actions ────────────────────────────────────────────────────────────
/** 2FA again for uninstalls and emergency updates (§4). */
function requireTotp(admin, code) {
if (!admin?.totpEnabled || !admin.totpSecret) throw fail(403, 'TOTP_REQUIRED', 'Two-factor isn\'t set up for your account.');
if (!verifyCode(decrypt(admin.totpSecret), String(code || '').replace(/\s/g, ''))) throw fail(403, 'BAD_TOTP', 'That two-factor code isn\'t right.');
}
/** Heard from in the last 2 minutes, or busy with a job the Hub handed it (`runningJob`, within its time limit). */
function agentOnline(server, now = new Date(), runningJob = null) {
return (!!server.lastSeenAt && now - new Date(server.lastSeenAt) < AGENT_ONLINE_MS) || servers.busyWithJob(runningJob, now);
}
/** The latest release of a product, or the one asked for (it must exist). */
async function releaseFor(product, version) {
const releases = await prisma.release.findMany({ where: { product } });
if (!releases.length) throw fail(409, 'NO_RELEASE', `There are no ${PRODUCT_NAMES[product]} releases yet (Releases page).`);
if (version) {
const r = releases.find(x => x.version === version);
if (!r) throw fail(400, 'NO_RELEASE', `There's no ${PRODUCT_NAMES[product]} release ${version}.`);
return r;
}
return releases.sort((a, b) => compareVersions(b.version, a.version))[0];
}
/** Checks before a job is made (§7.2): agent online, configuration complete for the release. */
async function preflight(server, product, version, now) {
if (server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.');
if (server.mode !== 'church') throw fail(400, 'NOT_A_CHURCH_SERVER', 'Church sites go on church servers, not the central one.');
const running = await prisma.job.findFirst({ where: { serverId: server.id, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
if (!agentOnline(server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${server.name} isn't online (last heard ${server.lastSeenAt ? server.lastSeenAt.toISOString() : 'never'}).`);
const missing = await missingFor(product, version, servers.serverConfig(server), await servers.installDefaults());
const parts = [];
if (missing.server.length) parts.push(`${server.name}'s configuration needs ${missing.server.join(', ')}`);
if (missing.defaults.length) parts.push(`Install defaults need ${missing.defaults.join(', ')}`);
if (parts.length) throw fail(409, 'CONFIG_MISSING', `${parts.join('; ')} (Servers → ${server.name} → Configuration).`);
}
/** Products the Hub can install so far (Accounts from Hub 2.3.0, docs/ACCOUNTS-1.0-PLAN.md §9). */
const INSTALLABLE = new Set(['events', 'accounts']);
/**
* New install (§7): licence, ports, the install job. A church already on that server (the same
* short name, another product) gets the product added next to its others (an `add-product` job,
* `crosscode add`), e.g. Accounts next to Events.
*/
async function newInstall(input, admin, now = new Date()) {
const product = input.product || 'events';
if (!INSTALLABLE.has(product)) throw fail(400, 'BAD_REQUEST', `${PRODUCT_NAMES[product] || product} can't be installed from the Hub yet.`);
const shortName = String(input.shortName || '').trim();
if (!SHORT_NAME.test(shortName)) throw fail(400, 'BAD_REQUEST', 'The short name is 2–31 characters: a-z, 0-9 and -, starting with a letter.');
const domain = String(input.domain || '').trim().toLowerCase();
if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', 'Give the domain the site is served on, like events.hope.co.za.');
const adminEmail = String(input.adminEmail || '').trim();
if (adminEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(adminEmail)) throw fail(400, 'BAD_REQUEST', 'The site admin\'s email isn\'t valid.');
const [customer, server] = await Promise.all([
prisma.customer.findUnique({ where: { id: String(input.customerId || '') } }),
prisma.server.findUnique({ where: { id: String(input.serverId || '') } }),
]);
if (!customer) throw fail(404, 'NOT_FOUND', 'Customer not found.');
if (!server) throw fail(404, 'NOT_FOUND', 'Server not found.');
const release = await releaseFor(product, input.version || null);
await preflight(server, product, release.version, now);
// The church's other products: the same short name means the same church folder on one server.
const siblings = await prisma.deployment.findMany({ where: { shortName, status: { notIn: ['removed', 'failed'] } } });
if (siblings.some(s => s.product === product)) throw fail(409, 'SHORT_NAME_TAKEN', `${shortName} already has ${PRODUCT_NAMES[product]}.`);
if (siblings.some(s => s.customerId !== customer.id)) throw fail(409, 'SHORT_NAME_TAKEN', `The short name ${shortName} is already used by another customer.`);
if (siblings.some(s => s.serverId !== server.id)) throw fail(409, 'OTHER_SERVER', `${shortName}'s other products are on another server; a church's products go on one server.`);
if (siblings.some(s => s.status !== 'live' && s.status !== 'waiting_for_proxy')) throw fail(409, 'BUSY', `Wait until ${shortName}'s other install has finished.`);
const add = siblings.length > 0;
// The name is free again after a failed install (its ports were already freed) or an uninstall.
// A failed install's record goes; a removed one keeps its history under another name (the
// database allows one install per short name and product). Found in the VM test.
await prisma.deployment.deleteMany({ where: { shortName, product, status: 'failed' } });
for (const old of await prisma.deployment.findMany({ where: { shortName, product, status: 'removed' } })) {
await prisma.deployment.update({ where: { id: old.id }, data: { shortName: `${shortName}~removed-${old.id.slice(0, 8)}` } });
}
const warnings = [];
const dnsOk = await dnsPointsAtCentral(domain);
if (dnsOk === false) warnings.push(`${domain} doesn't point at the central server yet (the install still runs).`);
const deployment = await prisma.$transaction(async tx => {
let licence = await tx.licence.findFirst({ where: { customerId: customer.id, product, status: { not: 'revoked' } }, include: { install: true } });
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${customer.name}'s ${PRODUCT_NAMES[product]} licence is already used by ${licence.install.url}.`);
if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product, now })).licence;
const ports = await servers.allocatePorts(tx, server.id, now);
const d = await tx.deployment.create({
data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product, shortName, domain, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, status: 'installing' },
});
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: d.id } });
await makeJob(tx, add
? {
serverId: server.id, type: 'add-product', deploymentId: d.id, createdById: admin?.id || null, notBefore: now,
args: { church: shortName, product, version: `${product}@${release.version}`, domain, ports },
}
: {
serverId: server.id, type: 'install', deploymentId: d.id, createdById: admin?.id || null, notBefore: now,
args: { church: shortName, products: [product], versions: { [product]: `${product}@${release.version}` }, domains: { [product]: domain }, ports: { [product]: ports } },
});
return d;
});
return { deployment, warnings };
}
/** Proxy done (§7.8): check the public addresses, then Live and the welcome email. */
async function proxyDone(deploymentId, now = new Date(), fetcher = fetch) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, customer: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
const problems = [];
const get = async url => {
try { return await fetcher(url, { redirect: 'manual', signal: AbortSignal.timeout(15000) }); } catch (e) { problems.push(`${url}: ${e?.message || 'no answer'}`); return null; }
};
const site = await get(`https://${d.domain}/`);
if (site && !(site.status >= 200 && site.status < 400)) problems.push(`https://${d.domain}/ answered ${site.status}.`);
const health = await get(`https://${d.domain}/api/health`);
let reported = null;
if (health) {
try { reported = await health.json(); } catch { problems.push(`https://${d.domain}/api/health didn't answer with JSON (is /api sent to port ${d.apiPort}?).`); }
if (reported && d.version && reported.version !== d.version) problems.push(`The backend reports version ${reported.version}, expected ${d.version}.`);
}
if (problems.length) return { live: false, problems };
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'live', liveAt: now } });
await emailSiteAdmin(d, `Your ${PRODUCT_NAMES[d.product]} site is ready`, [
`${d.customer?.name || 'Your church'}'s ${PRODUCT_NAMES[d.product]} site is ready at https://${d.domain}.`,
'', `To start, open https://${d.domain}/setup: it creates your admin account and walks you through the settings.`,
].join('\n'));
return { live: true, problems: [] };
}
function scheduleWarnings(at, deployment) {
const warnings = [];
const local = new Date(at.getTime() + 2 * HOUR);
if (local.getUTCDay() === 0 && local.getUTCHours() >= 6 && local.getUTCHours() < 13) warnings.push('That\'s Sunday morning, when churches use their sites most.');
const upcoming = deployment.install?.stats?.events?.upcoming;
if (upcoming > 0) warnings.push(`${deployment.shortName} has ${upcoming} upcoming event(s): check none runs then.`);
return warnings;
}
/**
* Scheduled, emergency or batch update (§8). One deployment: a single job; several: a batch that
* runs them one at a time from `at` and stops at the first failure. Each church gets one email
* and a banner now, and a reminder an hour before.
*/
async function scheduleUpdate({ deploymentIds, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
const when = new Date(at);
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
if (emergency) {
if (!reason || !String(reason).trim()) throw fail(400, 'BAD_REQUEST', 'An emergency update needs a reason (it goes in the email and banner).');
requireTotp(admin, totp);
if (when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice.`);
} else if (when - now < SCHEDULE_MIN_HOURS * HOUR) {
throw fail(400, 'TOO_SOON', `Updates are planned at least ${SCHEDULE_MIN_HOURS} hours ahead (or as an emergency update).`);
}
const ids = [...new Set((deploymentIds || []).map(String))];
if (!ids.length) throw fail(400, 'BAD_REQUEST', 'Choose at least one install.');
const deployments = await prisma.deployment.findMany({ where: { id: { in: ids } }, include: { server: true, install: true, customer: true } });
if (deployments.length !== ids.length) throw fail(404, 'NOT_FOUND', 'One of the installs wasn\'t found.');
const products = new Set(deployments.map(d => d.product));
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product.');
const product = [...products][0];
const release = await releaseFor(product, version);
const warnings = [];
for (const d of deployments) {
if (d.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName} isn't live (${d.status}).`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
if (d.install) {
const unmet = await unmetRequirementsFor(d.install, release);
if (unmet.length) throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${release.version} needs ${unmet.map(u => `${u.product} ${u.version}`).join(', ')} first.`);
}
const missing = await missingFor(product, release.version, servers.serverConfig(d.server), await servers.installDefaults());
if (missing.server.length || missing.defaults.length) throw fail(409, 'CONFIG_MISSING', `${d.shortName}: set ${[...missing.server, ...missing.defaults].join(', ')} first.`);
warnings.push(...scheduleWarnings(when, d));
}
const batchId = deployments.length > 1 ? servers.newId('batch') : null;
const name = PRODUCT_NAMES[product];
const jobs = [];
for (const [i, d] of deployments.entries()) {
const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`;
const message = `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`;
const noticeId = await addNotice(d, { title, message, endsAt: new Date(when.getTime() + 2 * HOUR), level: emergency ? 'warning' : 'maintenance' }, now);
jobs.push(await makeJob(prisma, {
serverId: d.serverId, type: 'deploy', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, emergency, reason,
batchId, batchOrder: batchId ? i : null, status: !batchId || i === 0 ? 'queued' : 'scheduled', notBefore: when, noticeId,
args: { church: d.shortName, products: [product], versions: [`${product}@${release.version}`] },
}));
const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : '';
await emailSiteAdmin(d, `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`);
}
return { jobs, batchId, warnings: [...new Set(warnings)] };
}
/** Cancel a job that hasn't been handed out yet; the church is told and the banner ends. */
async function cancelJob(jobId, admin, now = new Date()) {
const job = await prisma.job.findUnique({ where: { id: jobId }, include: { deployment: { include: { install: true } } } });
if (!job) throw fail(404, 'NOT_FOUND', 'Not found.');
if (!['queued', 'scheduled'].includes(job.status)) throw fail(409, 'NOT_CANCELLABLE', `This job is ${job.status}.`);
const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'cancelled', finishedAt: now, message: `Cancelled by ${admin?.name || 'an admin'}.` } });
if (job.noticeId) await endNotice(job.noticeId, now);
if (job.scheduled && job.deployment && job.type === 'deploy') {
await emailSiteAdmin(job.deployment, `${PRODUCT_NAMES[job.deployment.product]} update cancelled`, `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled. Your site keeps running as it is.`);
}
if (job.batchId) await advanceBatch(updated, now);
if (job.type === 'uninstall' && job.deployment) await prisma.deployment.update({ where: { id: job.deployment.id }, data: { status: statusBeforeUninstall(job.deployment) } });
return updated;
}
/** What an install goes back to when its uninstall doesn't happen: it's still on the server. */
function statusBeforeUninstall(d) {
return d.liveAt || d.installId ? 'live' : 'waiting_for_proxy';
}
/**
* Whether an install never made it onto the server, so its record can simply be removed: its
* install failed (the server already removed what it made) and nothing is planned for it. Also
* one that was planned for uninstall after its install failed, from before 2.3.2 (stuck as
* "uninstalling" when the export found nothing to export).
*/
async function neverInstalled(d) {
if (!['failed', 'uninstalling'].includes(d.status) || d.liveAt || d.installId) return false;
const open = await prisma.job.count({ where: { deploymentId: d.id, status: { in: ['scheduled', 'queued', 'delivered'] } } });
if (open) return false;
if (d.status === 'failed') return true;
const install = await prisma.job.findFirst({ where: { deploymentId: d.id, type: { in: ['install', 'add-product'] } }, orderBy: { createdAt: 'desc' } });
return !!install && install.status !== 'succeeded';
}
/** Remove a failed install's record: there's nothing on the server to export or uninstall. */
async function removeFailedInstall(deploymentId) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (!(await neverInstalled(d))) throw fail(409, 'NOT_FAILED', 'Only a failed install\'s record can be removed; a working install is uninstalled.');
await prisma.port.deleteMany({ where: { port: { in: [d.webPort, d.apiPort] }, deploymentId: d.id, releasedAt: null } });
await prisma.deployment.delete({ where: { id: d.id } });
return d;
}
/**
* Uninstall (§9): 2FA, typing the short name, at least 4 hours ahead. A batch of two: the export
* (encrypted, emailed to the site admin), then the uninstall, which only runs if the export worked.
*/
async function scheduleUninstall({ deploymentId, at, totp, confirm }, admin, now = new Date()) {
requireTotp(admin, totp);
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`);
if (['removed', 'uninstalling'].includes(d.status)) throw fail(409, 'ALREADY', `It's already ${d.status}.`);
if (d.status === 'failed') throw fail(409, 'NOT_INSTALLED', 'Its install failed, so nothing of it is on the server: remove the record instead.');
if (d.status === 'installing') throw fail(409, 'BUSY', 'Wait until the install has finished.');
const when = new Date(at || now.getTime() + 7 * DAY);
if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
const exportId = servers.newId('exp');
const batchId = servers.newId('batch');
const noticeId = await addNotice(d, { title: `${PRODUCT_NAMES[d.product]} is closing`, message: `This site closes on ${sast(when)}. Your admin gets a download of all your data by email first.`, endsAt: new Date(when.getTime() + 2 * HOUR), level: 'warning' }, now);
await prisma.export.create({ data: { id: exportId, deploymentId: d.id, expiresAt: new Date(when.getTime() + EXPORT_DAYS * DAY) } });
const exportJob = await makeJob(prisma, { serverId: d.serverId, type: 'export', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 0, notBefore: when, args: { church: d.shortName, exportId } });
const uninstallJob = await makeJob(prisma, { serverId: d.serverId, type: 'uninstall', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 1, status: 'scheduled', notBefore: when, noticeId, args: { church: d.shortName } });
await prisma.deployment.update({ where: { id: d.id }, data: { status: 'uninstalling' } });
await emailSiteAdmin(d, `${PRODUCT_NAMES[d.product]} at ${d.domain} closes on ${sast(when)}`, `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed on ${sast(when)}. Shortly before, you'll get an email with a link to download all your data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.`);
return { exportJob, uninstallJob };
}
/** An agent's encrypted export (PUT /api/agent/v1/exports/:id). */
async function receiveExport(server, exportId, buffer) {
const exp = await prisma.export.findUnique({ where: { id: exportId }, include: { deployment: true } });
if (!exp || !exp.deployment || exp.deployment.serverId !== server.id) throw fail(404, 'NOT_FOUND', 'Unknown export.');
if (exp.deletedAt) throw fail(410, 'GONE', 'This export was deleted.');
if (!buffer?.length || buffer.length > 2 * 1024 ** 3) throw fail(400, 'BAD_REQUEST', 'Empty or too large.');
await prisma.export.update({ where: { id: exportId }, data: { data: buffer, bytes: buffer.length } });
}
/** Link an install that's already on a server (crosscode adopt, or installed by hand) (§14.3). */
async function linkDeployment(input, admin) {
const server = await prisma.server.findUnique({ where: { id: String(input.serverId || '') } });
const install = await prisma.install.findUnique({ where: { id: String(input.installId || '') }, include: { deployment: true } });
if (!server || !install) throw fail(404, 'NOT_FOUND', 'Server or install not found.');
if (install.deployment) throw fail(409, 'ALREADY_LINKED', 'That install is already linked.');
const shortName = String(input.shortName || '').trim();
if (!SHORT_NAME.test(shortName)) throw fail(400, 'BAD_REQUEST', 'The short name is just a name (a-z, 0-9 and -, like hope), not a folder: the site lives, or will after adopt, in /var/www/sites/<name>.');
const web = parseInt(input.webPort, 10);
const api = parseInt(input.apiPort, 10);
if (!(web > 0 && api > 0 && web !== api)) throw fail(400, 'BAD_REQUEST', 'Give the site\'s two ports (web and api).');
const domain = new URL(install.url).hostname;
return prisma.$transaction(async tx => {
const d = await tx.deployment.create({
data: { serverId: server.id, customerId: install.customerId, licenceId: install.licenceId, installId: install.id, product: install.product, shortName, domain, webPort: web, apiPort: api, version: install.version, timezone: install.timezone, status: 'live', liveAt: new Date(), adminName: install.adminContact?.name || null, adminEmail: install.adminContact?.email || null },
});
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await tx.port.upsert({ where: { port }, update: { serverId: server.id, deploymentId: d.id, role, releasedAt: null, note: 'existing install' }, create: { port, serverId: server.id, deploymentId: d.id, role, note: 'existing install' } });
}
return d;
});
}
/** Move a linked 2.1.x install onto the monorepo with `crosscode adopt`, at a time with notice. */
async function scheduleAdopt({ deploymentId, eventsDir, version, address, at }, admin, now = new Date()) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
// The church's address (crosscode adopt --address): crosscode can only work it out from an
// events.<address> domain, so any other domain (events-demo.crosscode.co.za) needs it given.
let church = String(address || '').trim().toLowerCase();
if (!church && d.domain.startsWith('events.')) church = d.domain.slice('events.'.length);
if (!church) throw fail(400, 'ADDRESS_NEEDED', `${d.domain} doesn't start with "events.", so give the church's address (like hope.co.za).`);
if (!DOMAIN.test(church)) throw fail(400, 'BAD_REQUEST', 'The church\'s address is a domain, like hope.co.za.');
const when = new Date(at);
if (Number.isNaN(when.getTime()) || when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', `Plan it at least ${SCHEDULE_MIN_HOURS} hours ahead.`);
const release = await releaseFor(d.product, version || null);
const noticeId = await addNotice(d, { title: 'Planned maintenance', message: `${PRODUCT_NAMES[d.product]} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two.`, endsAt: new Date(when.getTime() + 2 * HOUR) }, now);
const job = await makeJob(prisma, { serverId: d.serverId, type: 'adopt', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, notBefore: when, noticeId, args: { church: d.shortName, eventsDir: String(eventsDir || ''), version: `${d.product}@${release.version}`, address: church } });
await emailSiteAdmin(d, `Planned maintenance on ${sast(when)}`, `${PRODUCT_NAMES[d.product]} at ${d.domain} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two; nothing changes for your team.`);
return job;
}
/** check-ports on every central server (§7.6). */
async function queueCentralCheck(ports, now = new Date()) {
const centrals = await prisma.server.findMany({ where: { mode: 'central', removedAt: null } });
for (const c of centrals) await makeJob(prisma, { serverId: c.id, type: 'check-ports', args: { ports }, notBefore: now });
return centrals.length;
}
/** Any job by hand (status, restart): no notice, runs at once. */
async function runNow({ serverId, type, args, deploymentId = null }, admin, now = new Date()) {
if (!['status', 'restart', 'check-ports', 'update-agent'].includes(type)) throw fail(400, 'BAD_REQUEST', `${type} jobs are made from their own pages.`);
return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now });
}
module.exports = {
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
};