/** * 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 { render } = require('./emailLayout'); const { getSettings } = require('./settings'); const { PRODUCT_NAMES } = require('./products'); const { generateLicence } = require('./licences'); const { unmetRequirements, unmetRequirementsFor, agentTag } = require('./releases'); const { searchTerm } = require('./paging'); const { compareVersions } = require('./alerts'); const servers = require('./servers'); const { missingFor, invalidFor } = 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; // The crosscode script's order (Accounts first: the others sign in through it). const PRODUCT_ORDER = ['accounts', 'events', 'website', 'app']; 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); const fp = await fastPanelSteps(deployment); await emailJoshua(`Installed: ${deployment.shortName} (${PRODUCT_NAMES[deployment.product]})`, { heading: `${deployment.domain} is installed`, sub: 'Now set it up in FastPanel.', blocks: [ { note: { kind: 'success', title: `${PRODUCT_NAMES[deployment.product]} installed on ${deployment.server?.name || 'the server'}`, text: `Ports ${deployment.webPort} (frontend) and ${deployment.apiPort} (backend). It goes live when you click "Proxy done".` } }, { h: `${fp.heading} (${fp.sub})` }, { numbered: fp.steps }, { button: { label: 'Proxy done: check and go live', url: fp.link } }, { divider: true }, { h: 'The install' }, ...jobReportBlocks(job, { button: false }), ], }); } 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}`, jobReport(job, `${deployment.domain} wasn't installed`, 'Its ports are free again. The steps and the last log lines are below.')); } 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]; const version = target ? target.replace(/^.*@/, '') : null; if (ok) { await emailSiteAdmin(deployment, `${name} was updated`, { heading: `${name} was updated`, blocks: [ { note: { kind: 'success', title: 'Everything is running again', text: `${name} at ${deployment.domain} was updated${version ? ` to ${version}` : ''}.` } }, { button: { label: `Open ${name}`, url: `https://${deployment.domain}` } }, ], }); } else { await emailSiteAdmin(deployment, `${name} update didn't go through`, { heading: 'The update didn\'t go through', blocks: [ { note: { kind: 'warning', title: 'Your site is running as before', text: `The planned update of ${name} at ${deployment.domain} didn't go through, so the site is running the previous version. Nothing else changed.` } }, { p: 'We\'ll be in touch about a new time.' }, ], }); } } await emailJoshua(`${job.type === 'adopt' ? 'Adopt' : 'Update'} ${ok ? 'done' : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReport(job, `${job.type === 'adopt' ? 'Adopt' : 'Update'} of ${deployment.domain} ${ok ? 'done' : job.status.replace('_', ' ')}`, target ? `To ${target}.` : undefined)); break; } case 'seed-demo': if (!deployment) break; await emailJoshua(`Demo data ${ok ? `(${job.args.profile}) loaded` : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReport(job, ok ? `Demo data loaded on ${deployment.domain}` : `Demo data on ${deployment.domain}: ${job.status.replace('_', ' ')}`, `Profile: ${job.args.profile}.`)); 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', { heading: 'Your data is ready to download', blocks: [ { p: `Here is all of ${deployment.customer?.name || 'your church'}'s data from ${(job.args.products || [deployment.product]).map(p => PRODUCT_NAMES[p]).join(' and ')}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.` }, { button: { label: 'Download your data', url: link } }, { note: { kind: 'warning', title: 'Keep this email', text: `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.` } }, ], }); } else if (!ok) { await emailJoshua(`Export failed: ${deployment.shortName}`, jobReport(job, `The export of ${deployment.domain} failed`)); } break; case 'env-set': // 2.8.0: read the file again, so the install's page shows what's there now (also after a put-back). if (deployment && ['succeeded', 'rolled_back'].includes(job.status)) { await makeJob(prisma, { serverId: deployment.serverId, type: 'env-read', args: { church: deployment.shortName, product: deployment.product }, deploymentId: deployment.id, createdById: job.createdById, notBefore: now }); } if (deployment && !ok) await emailJoshua(`.env change ${job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReport(job, `The .env change on ${deployment.domain}: ${job.status.replace('_', ' ')}`, job.status === 'rolled_back' ? 'The site didn\'t answer afterwards, so the file was put back.' : undefined)); break; case 'uninstall': if (!deployment) break; if (ok) { // Hub 2.12.0: with `products` (agent 1.5.0) only those went. Without it the agent removed // the whole church, so its other products on this server are gone too (before 2.12.0 // they stayed "live" here, and their own uninstall failed later). // A run can name several products (one joined to another's uninstall). When the script // reports nothing left of the church (`remaining` empty: the last product went, so the // church's folder and app user went too), every product of it here is gone. const whole = !job.args?.products; const all = [deployment, ...(await churchSiblings(deployment))]; const remaining = job.report?.result?.remaining; const churchGone = whole || (Array.isArray(remaining) && remaining.length === 0); const gone = churchGone ? all : all.filter(x => job.args.products.includes(x.product)); for (const g of gone) await markRemoved(g, now, { except: job.id, why: `Not needed: ${g.domain} was uninstalled by ${job.id}.` }); await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName, ...(whole ? {} : { products: job.args.products }) }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 }); await emailJoshua(`Uninstalled: ${deployment.shortName}${whole ? '' : ` (${job.args.products.map(p => PRODUCT_NAMES[p]).join(' and ')})`}`, { heading: `${gone.map(g => g.domain).join(' and ')} ${gone.length === 1 ? 'is' : 'are'} uninstalled`, sub: 'One thing left to do by hand.', blocks: [ ...gone.map(g => ({ note: { kind: 'warning', title: 'Remove the FastPanel site', text: `${g.domain} (ports ${g.webPort} and ${g.apiPort}).` } })), ...(churchGone ? [{ p: `Nothing of ${deployment.shortName} is left on ${deployment.server?.name || 'the server'}: its folder and app user were removed too.` }] : []), { p: `The final backup is kept on the server for ${EXPORT_DAYS} days, then purged.` }, ...jobReportBlocks(job), ], }); } else { await uninstallNotRun(job, deployment); await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReport(job, `${deployment.domain} wasn't uninstalled`, 'The site is as it was.')); } 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', { heading: 'The central server\'s ports aren\'t ready', blocks: [ { note: { kind: 'danger', title: 'frps check failed', text: job.message || 'No reason given.' } }, { code: JSON.stringify(job.report?.result || {}, null, 2), label: 'What the central agent found' }, { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, ], }); } break; case 'status': if (ok) await linkFromStatus(job, now); break; case 'frp-read': case 'frp-write': { // What the agent found (secrets hidden on the server), for the server's page. const r = job.report?.result; if (agent.frpReadResultSchema.safeParse(r).success) { await prisma.server.update({ where: { id: job.serverId }, data: { frpConfig: { ...r, jobId: job.id } } }); } if (job.type === 'frp-write' && !ok) { const server = await prisma.server.findUnique({ where: { id: job.serverId } }); await emailJoshua(`frp config change ${job.status.replace('_', ' ')}: ${server?.name || job.serverId}`, jobReport(job, `The frp config change on ${server?.name || 'a server'}: ${job.status.replace('_', ' ')}`, job.status === 'rolled_back' ? 'frp didn\'t start with the new config, so the old one was put back.' : 'The config on the server is as it was.')); } break; } default: break; } if (job.batchId) await advanceBatch(job, now); } // ─── Batches (§8): one at a time, stop at the first failure ─────────────────── async function advanceBatch(job, now) { if (job.type === 'probe-ports') return portsProbed(job, now); const rest = await prisma.job.findMany({ where: { batchId: job.batchId, status: 'scheduled' }, orderBy: { batchOrder: 'asc' }, include: { deployment: { include: { install: true } } } }); if (!rest.length) return; if (job.status === 'succeeded') { 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 uninstallNotRun(j, j.deployment); } // Hub 2.5.0: the product after a failed Accounts install never ran: its record fails and its ports are freed. if (j.deployment && (j.type === 'install' || j.type === 'add-product')) { await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: 'failed' } }); await prisma.port.deleteMany({ where: { port: { in: [j.deployment.webPort, j.deployment.apiPort] } } }); } if (j.deployment && j.scheduled && j.type === 'deploy') { const name = PRODUCT_NAMES[j.deployment.product]; await emailSiteAdmin(j.deployment, `${name} update postponed`, { heading: 'The update is postponed', blocks: [ { note: { kind: 'info', title: 'Your site keeps running as it is', text: `The planned update of ${name} at ${j.deployment.domain} has been postponed.` } }, { p: 'We\'ll let you know the new time.' }, ], }); } } await emailJoshua('Batch stopped', jobReport(job, 'A batch stopped', `${rest.length} job(s) after this one were cancelled, and their churches were 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}`, { heading: `A ${job.type} job was missed`, blocks: [ { note: { kind: 'warning', title: 'Nothing ran', text: updated.message } }, { p: 'A new time needs a new notice to the church.' }, { button: { label: 'Open the job', url: `${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') { const name = PRODUCT_NAMES[job.deployment.product]; await emailSiteAdmin(job.deployment, `Reminder: ${name} update at ${sast(job.notBefore)}`, { heading: 'Reminder: an update in an hour', blocks: [ { rows: [['Site', job.deployment.domain], ['When', sast(job.notBefore)]] }, { p: `${name} will be unavailable for a few minutes while it's updated.` }, ], }); } } // 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}`, { heading: `${job.args.church}'s data is deleted in 3 days`, blocks: [ { note: { kind: 'warning', text: `${job.args.church}'s kept backup and its encrypted export will be deleted on ${sast(job.notBefore)}.` } }, { p: 'To keep them 30 days longer, open the job.' }, { button: { label: 'Open the job', url: `${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 ─────────────────────────────────────────────────────────────────── /** `content` is { heading?, sub?, preheader?, blocks } (emailLayout.js), or plain text. */ const asContent = content => (typeof content === 'string' ? { blocks: content.split(/\n{2,}/).map(p => ({ p })) } : content || { blocks: [] }); /** An email to Joshua at the alert address in Settings. */ async function emailJoshua(subject, content) { const { alert_email: to } = await getSettings(); if (!to) return; const c = asContent(content); const email = render({ heading: c.heading || subject, sub: c.sub, preheader: c.preheader, blocks: c.blocks, footer: 'Sent by the Cross Code Hub to the alert address in Settings.' }); await sendMail({ to, subject: `Cross Code Hub: ${subject}`, ...email }).catch(e => console.warn('[jobs] email failed:', e?.message)); } function siteAdminEmail(deployment) { return deployment.adminEmail || deployment.install?.adminContact?.email || null; } /** An email to a church's site admin: greeted by name and signed from Cross Code. */ async function emailSiteAdmin(deployment, subject, content) { const to = siteAdminEmail(deployment); if (!to) return; const hello = deployment.adminName || deployment.install?.adminContact?.name; const c = asContent(content); const product = PRODUCT_NAMES[deployment.product] || 'Cross Code'; const email = render({ heading: c.heading || subject, sub: c.sub, preheader: c.preheader, label: product, blocks: [hello ? { hello } : null, ...c.blocks, { p: 'Kind regards,\nThe Cross Code team' }], footer: `You're getting this because you look after ${deployment.customer?.name ? `${deployment.customer.name}'s ` : 'the '}${product} site at ${deployment.domain}.`, }); await sendMail({ to, subject, ...email }).catch(e => console.warn('[jobs] email failed:', e?.message)); } /** A job's report as email blocks: how it ended, its steps, the last log lines if it failed, a link. */ function jobReportBlocks(job, { button = true } = {}) { const r = job.report || {}; const kind = job.status === 'succeeded' ? 'success' : ['failed', 'missed'].includes(job.status) ? 'danger' : 'warning'; const log = job.status === 'succeeded' ? [] : (r.log || []).slice(-30); return [ { note: { kind, title: `${job.type}: ${job.status.replace(/_/g, ' ')}`, text: job.message || '' } }, { steps: (r.steps || []).map(s => ({ outcome: s.outcome, name: s.name, detail: s.detail })) }, log.length ? { code: log.join('\n'), label: 'Last log lines' } : null, button ? { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } } : { small: `Job ${job.id}: ${hubUrl()}/jobs/${job.id}` }, ]; } /** * A release's What's New notes as email blocks: "- " lines (with their indented continuations) * a list, other lines paragraphs; **bold** and `code` marks are dropped, as the Hub's page does. */ function notesBlocks(notes) { const plain = t => t.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1').replace(/\s+/g, ' ').trim(); const blocks = []; let para = []; let bullets = []; const flushPara = () => { if (para.length) blocks.push({ p: plain(para.join(' ')) }); para = []; }; const flushBullets = () => { if (bullets.length) blocks.push({ bullets: bullets.map(plain) }); bullets = []; }; for (const line of String(notes || '').split(/\r?\n/)) { if (/^\s*[-*] /.test(line)) { flushPara(); bullets.push(line.replace(/^\s*[-*] /, '')); } else if (!line.trim()) { flushPara(); flushBullets(); } else if (bullets.length && /^\s+/.test(line)) bullets[bullets.length - 1] += ` ${line.trim()}`; else { flushBullets(); para.push(line.trim()); } } flushPara(); flushBullets(); return blocks; } /** An email made of a job's report under a heading. */ const jobReport = (job, heading, intro) => ({ heading, blocks: [intro ? { p: intro } : null, ...jobReportBlocks(job)] }); 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 site's backend location for FastPanel's nginx. ^~ (2.10.0): FastPanel's static-file * handling adds a regex location for file extensions that falls back to the site's main proxy * (the frontend), and a regex wins over a plain "location /api", so /api/uploads/…/logo.png * reached the frontend and 404'd (Events 3.6.1). No regex can override ^~. */ const fastPanelNginx = d => [ 'location ^~ /api/ {', ` proxy_pass http://127.0.0.1:${d.apiPort};`, ' proxy_set_header Host $host;', ' proxy_set_header X-Real-IP $remote_addr;', ' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;', ' proxy_set_header X-Forwarded-Proto https;', '}', `location = /api { proxy_pass http://127.0.0.1:${d.apiPort}; }`, ].join('\n'); /** The FastPanel steps (§11): what Joshua sets up by hand; nothing is done automatically. */ async function fastPanelSteps(d) { const dnsOk = await dnsPointsAtCentral(d.domain); const ip = await centralIp(); return { heading: `Set up in FastPanel: ${d.domain}`, sub: `${d.customer?.name || d.shortName}, ${PRODUCT_NAMES[d.product]}`, link: `${hubUrl()}/servers/installs/${d.id}`, steps: [ { text: `Add the site ${d.domain} as a proxy to http://127.0.0.1:${d.webPort} (the frontend). Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https, and allow uploads up to 25 MB.` }, { text: 'Send /api to the backend: add this to the site\'s nginx configuration. Keep the ^~: without it FastPanel\'s static-file rule sends every /api path with a file extension (an uploaded logo, a PDF) to the frontend.', code: fastPanelNginx(d) }, { text: 'Turn on Let\'s Encrypt for the site.' }, { text: `DNS: ${d.domain} → ${ip || ''} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'}).` }, { text: 'Click "Proxy done" in the Hub. It checks the site, its /api and a file under /api, then makes it live.' }, ], }; } /** The FastPanel steps as text (the install's page shows them). */ async function fastPanelText(d) { const f = await fastPanelSteps(d); return [ `${f.heading} (${f.sub})`, '', ...f.steps.map((s, i) => `${i + 1}. ${s.text}${s.code ? `\n\n${s.code.split('\n').map(l => ` ${l}`).join('\n')}\n` : ''}`), '', `Proxy done: ${f.link}`, ].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).`); const invalid = invalidFor(servers.serverConfig(server), await servers.installDefaults()); if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${server.name}'s configuration: ${invalid.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.`); // Hub 2.5.0: a release that needs a sibling (Cross Events 3.0: "— requires accounts 1.1.0") gets // it. A church without Accounts has it installed first, in the same batch; one with an older // Accounts is refused until it's updated. const first = await requiredFirst({ release, product, siblings, input, domain, server, now }); const add = siblings.length > 0 || !!first; // 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).`); if (first) { const dnsFirst = await dnsPointsAtCentral(first.domain); if (dnsFirst === false) warnings.push(`${first.domain} doesn't point at the central server yet (the install still runs).`); } // Hub 2.11.0: the ports are checked on the central server and this one before the install runs. const probe = await probeServers(server, now); if (probe.skip) warnings.push(probe.skip); const probing = probe.servers.length > 0; const deployment = await prisma.$transaction(async tx => { const batchId = first || probing ? servers.newId('batch') : null; const candidates = probing ? await servers.reservePorts(tx, server.id, Math.min(50, (first ? 4 : 2) + PROBE_SPARE), probeNote(batchId), now) : null; let nextCandidate = 0; const portsFor = async () => { if (!candidates) return servers.allocatePorts(tx, server.id, now); // For now: the first free pair. They change if a server says one is in use. const [web, api] = candidates.slice(nextCandidate, nextCandidate += 2); for (const [port, role] of [[web, 'web'], [api, 'api']]) await tx.port.update({ where: { port }, data: { role } }); return { web, api }; }; const make = async (p, dom) => { let licence = await tx.licence.findFirst({ where: { customerId: customer.id, product: p, status: { not: 'revoked' } }, include: { install: true } }); if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${customer.name}'s ${PRODUCT_NAMES[p]} licence is already used by ${licence.install.url}.`); if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product: p, now })).licence; const ports = await portsFor(); const d = await tx.deployment.create({ data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product: p, shortName, domain: dom, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, status: 'installing' }, }); await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: d.id } }); return { d, ports }; }; // Accounts first (an install job), then the product next to it once that succeeded (a batch). // While the ports are checked, every install waits (scheduled) until the checks are back. if (first) { const a = await make('accounts', first.domain); await makeJob(tx, { serverId: server.id, type: siblings.length ? 'add-product' : 'install', deploymentId: a.d.id, createdById: admin?.id || null, notBefore: now, batchId, batchOrder: 0, ...(probing ? { status: 'scheduled' } : {}), args: siblings.length ? { church: shortName, product: 'accounts', version: `accounts@${first.release.version}`, domain: first.domain, ports: a.ports } : { church: shortName, products: ['accounts'], versions: { accounts: `accounts@${first.release.version}` }, domains: { accounts: first.domain }, ports: { accounts: a.ports } }, }); } const { d, ports } = await make(product, domain); const order = batchId ? { batchId, batchOrder: first ? 1 : 0, ...(first || probing ? { status: 'scheduled' } : {}) } : {}; await makeJob(tx, add ? { serverId: server.id, type: 'add-product', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, ...order, args: { church: shortName, product, version: `${product}@${release.version}`, domain, ports }, } : { serverId: server.id, type: 'install', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, ...order, args: { church: shortName, products: [product], versions: { [product]: `${product}@${release.version}` }, domains: { [product]: domain }, ports: { [product]: ports } }, }); if (probing) { for (const s of probe.servers) { await makeJob(tx, { serverId: s.id, type: 'probe-ports', args: { ports: candidates }, batchId, reason: probeRound(1), createdById: admin?.id || null, notBefore: now }); } } return d; }); return { deployment, warnings, checkingPorts: probing, ...(first ? { alsoInstalling: { product: 'accounts', domain: first.domain, version: first.release.version } } : {}) }; } // ─── Ports checked before an install (Hub 2.11.0, agent 1.4.0) ──────────────── // // An install reserves a few candidate ports and asks the central server and the church server // which are free (probe-ports). When both answer, it takes the first pair free on both: the // install's ports, the frp tunnel's on both ends. Ports found in use are kept in the port list as // taken, so they're never handed out again. If too few are free, it tries more (3 rounds). /** Spare candidates beyond the two each install needs, so a busy port doesn't need another round. */ const PROBE_SPARE = 8; const PROBE_ROUNDS = 3; const probeNote = batchId => `probe:${batchId}`; const probeRound = n => `ports round ${n}`; /** The servers that check the ports: every central server and the church server, or why not. */ async function probeServers(server, now) { const centrals = await prisma.server.findMany({ where: { mode: 'central', removedAt: null } }); const all = [...centrals, server]; const old = all.filter(s => compareVersions(s.agentVersion || '0.0.0', agent.FRP_JOBS_MIN_AGENT) < 0); if (old.length) { return { servers: [], skip: `The ports weren't checked on the servers first: ${old.map(s => `${s.name} (agent ${s.agentVersion || 'unknown'})`).join(', ')} need${old.length === 1 ? 's' : ''} agent ${agent.FRP_JOBS_MIN_AGENT} or later. The install still runs.` }; } for (const c of centrals) { const running = await prisma.job.findFirst({ where: { serverId: c.id, status: 'delivered' } }); if (!agentOnline(c, now, running)) throw fail(409, 'CENTRAL_OFFLINE', `The agent on the central server ${c.name} isn't online, so the ports can't be checked there first (last heard ${c.lastSeenAt ? c.lastSeenAt.toISOString() : 'never'}).`); } return { servers: all }; } /** The install jobs waiting on a port check, in order. */ const waitingInstalls = batchId => prisma.job.findMany({ where: { batchId, status: 'scheduled', type: { in: ['install', 'add-product'] } }, orderBy: { batchOrder: 'asc' }, include: { deployment: true } }); /** A port check didn't work out: nothing is installed, the ports are free again. */ async function probeFailed(job, why, now) { const rest = await prisma.job.findMany({ where: { batchId: job.batchId, status: { in: ['scheduled', 'queued'] } }, include: { deployment: true } }); for (const j of rest) { await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: `Not run: ${why}`, finishedAt: now } }); if (j.deployment && (j.type === 'install' || j.type === 'add-product')) { await prisma.deployment.update({ where: { id: j.deployment.id }, data: { status: 'failed' } }); await prisma.port.deleteMany({ where: { port: { in: [j.deployment.webPort, j.deployment.apiPort] }, role: { in: ['web', 'api', 'candidate'] } } }); } } await prisma.port.deleteMany({ where: { note: probeNote(job.batchId), role: { in: ['web', 'api', 'candidate'] } } }); const names = rest.filter(j => j.deployment).map(j => j.deployment.domain); await emailJoshua(`Install not started: ${names.join(', ') || job.batchId}`, { heading: 'The install didn\'t start', sub: 'The ports couldn\'t be checked first.', blocks: [ { note: { kind: 'danger', title: 'Nothing was installed', text: why } }, { p: 'Its ports are free again. Start the install again once the servers are ready.' }, { button: { label: 'Open the check', url: `${hubUrl()}/jobs/${job.id}` } }, ], }); } /** After each probe-ports report: once every server of this round has answered, choose the ports. */ async function portsProbed(job, now) { const round = await prisma.job.findMany({ where: { batchId: job.batchId, type: 'probe-ports', reason: job.reason }, include: { server: true } }); if (round.some(j => !DONE.includes(j.status))) return; const waiting = await waitingInstalls(job.batchId); if (!waiting.length) return; // cancelled meanwhile const bad = round.find(j => j.status !== 'succeeded'); if (bad) return probeFailed(bad, `the port check on ${bad.server.name} was ${bad.status.replace('_', ' ')}${bad.message ? `: ${bad.message}` : '.'}`, now); const asked = job.args.ports; const busy = new Map(); // port → "server: reason" for (const j of round) { const result = agent.probePortsResultSchema.safeParse(j.report?.result); if (!result.success) return probeFailed(j, `${j.server.name}'s port check came back in a form the Hub doesn't know.`, now); const answered = new Map(result.data.ports.map(p => [p.port, p])); for (const port of asked) { const p = answered.get(port); if (!p) busy.set(port, `${j.server.name}: not checked`); else if (!p.free && !busy.has(port)) busy.set(port, `${j.server.name}: ${p.reason || 'in use'}`); } } const free = asked.filter(p => !busy.has(p)); const serverId = waiting[0].serverId; // Busy ports stay in the port list as taken, so they're never handed out. for (const [port, why] of busy) { await prisma.port.upsert({ where: { port }, update: { role: 'taken', deploymentId: null, note: `Found in use before an install (${now.toISOString().slice(0, 10)}): ${why}`.slice(0, 500) }, create: { port, serverId, role: 'taken', note: `Found in use before an install: ${why}`.slice(0, 500) } }); } if (free.length < waiting.length * 2) { const n = Number(String(job.reason || '').replace(/\D/g, '')) || 1; if (n >= PROBE_ROUNDS) return probeFailed(job, `no two ports were free on every server after ${n} checks (${[...busy].slice(0, 10).map(([p, w]) => `${p} (${w})`).join('; ')}).`, now); let more; try { more = await prisma.$transaction(tx => servers.reservePorts(tx, serverId, Math.min(50 - free.length, waiting.length * 2 + PROBE_SPARE), probeNote(job.batchId), now)); } catch (e) { return probeFailed(job, e.message, now); } const ports = [...free, ...more].slice(0, 50); for (const j of round) await makeJob(prisma, { serverId: j.serverId, type: 'probe-ports', args: { ports }, batchId: job.batchId, reason: probeRound(n + 1), createdById: job.createdById, notBefore: now }); return; } // Each install gets the next two free ports. let i = 0; const used = new Set(); for (const j of waiting) { const [web, api] = free.slice(i, i += 2); used.add(web).add(api); const d = j.deployment; if (d) { await prisma.deployment.update({ where: { id: d.id }, data: { webPort: web, apiPort: api } }); for (const [port, role] of [[web, 'web'], [api, 'api']]) { await prisma.port.upsert({ where: { port }, update: { serverId, role, deploymentId: d.id, releasedAt: null, note: null }, create: { port, serverId, role, deploymentId: d.id } }); } } const args = j.type === 'install' ? { ...j.args, ports: Object.fromEntries(Object.keys(j.args.ports).map(k => [k, { web, api }])) } : { ...j.args, ports: { web, api } }; const parsed = agent.jobArgsSchemas[j.type].safeParse(args); if (!parsed.success) return probeFailed(job, `the install's arguments with ports ${web} and ${api} aren't valid.`, now); await prisma.job.update({ where: { id: j.id }, data: { args: parsed.data } }); } // The candidates not used are free again. await prisma.port.deleteMany({ where: { note: probeNote(job.batchId), role: { in: ['candidate', 'web', 'api'] }, port: { notIn: [...used] } } }); const firstJob = waiting[0]; await prisma.job.update({ where: { id: firstJob.id }, data: { status: 'queued', notBefore: now, expiresAt: new Date(now.getTime() + WINDOW_MIN * MIN) } }); } // ─── frp's config from the Hub (Hub 2.11.0, agent 1.4.0) ────────────────────── async function frpServer(serverId) { const s = await prisma.server.findUnique({ where: { id: serverId } }); if (!s || s.removedAt) throw fail(404, 'NOT_FOUND', 'Server not found.'); if (compareVersions(s.agentVersion || '0.0.0', agent.FRP_JOBS_MIN_AGENT) < 0) { throw fail(409, 'AGENT_TOO_OLD', `The agent on ${s.name} is ${s.agentVersion || 'an unknown version'}; reading and changing frp's config needs ${agent.FRP_JOBS_MIN_AGENT} or later (update the agent first).`); } return s; } /** * Read frps's (central) or frpc's (church) config. `path` given: the Hub keeps it for this server * and the agent uses that file from now on (an empty one: the agent finds the file itself). */ async function readFrp(serverId, { path } = {}, admin = null, now = new Date()) { const s = await frpServer(serverId); let use = s.frpConfigPath; if (path !== undefined) { const clean = String(path || '').trim(); if (clean && !agent.frpConfigPathSchema.safeParse(clean).success) throw fail(400, 'BAD_REQUEST', 'Give the full path of the config file, like /etc/frp/frps.toml (a file named frp….ini or frp….toml).'); await prisma.server.update({ where: { id: s.id }, data: { frpConfigPath: clean || null } }); use = clean || null; } return makeJob(prisma, { serverId: s.id, type: 'frp-read', args: use ? { path: use } : {}, createdById: admin?.id || null, notBefore: now }); } /** Replace frp's config with `content` (as the last read showed it, secrets hidden): two-factor, as for uninstalls. */ async function writeFrp(serverId, { content, restart = true, totp }, admin, now = new Date()) { requireTotp(admin, totp); const s = await frpServer(serverId); const last = s.frpConfig; if (!last?.found || !last.path) throw fail(409, 'READ_FIRST', 'Read the config first: the Hub writes to the file it last read.'); const pending = await prisma.job.findFirst({ where: { serverId: s.id, type: 'frp-write', status: { in: ['queued', 'delivered'] } } }); if (pending) throw fail(409, 'BUSY', 'A change to the config is already on its way.'); const text = String(content ?? ''); if (!text.trim()) throw fail(400, 'BAD_REQUEST', 'The config can\'t be empty.'); if (text.length > agent.FRP_CONFIG_MAX) throw fail(400, 'BAD_REQUEST', `The config is longer than ${agent.FRP_CONFIG_MAX} characters.`); return makeJob(prisma, { serverId: s.id, type: 'frp-write', args: { path: last.path, content: text, restart: !!restart }, createdById: admin?.id || null, notBefore: now }); } /** `events.hope.co.za` → `accounts.hope.co.za`: the first label swapped (ROADMAP-v3 decision 6). */ function accountsDomainFor(domain) { const parts = domain.split('.'); return parts.length > 2 ? ['accounts', ...parts.slice(1)].join('.') : `accounts.${domain}`; } /** * What a release needs installed first (Hub 2.5.0): its required Accounts, when the church has none. * Null when nothing is needed; refused when the church's Accounts is older than required, or no * Accounts release is new enough. */ async function requiredFirst({ release, product, siblings, input, domain, server, now }) { if (product === 'accounts') return null; const need = (Array.isArray(release.requires) ? release.requires : []).find(q => q && q.product === 'accounts'); if (!need) return null; const have = siblings.find(s => s.product === 'accounts'); if (have) { if (have.version && compareVersions(have.version, need.version) < 0) { throw fail(409, 'REQUIREMENT_NOT_MET', `${PRODUCT_NAMES[product]} ${release.version} needs Accounts ${need.version} or later; this church has ${have.version}. Update its Accounts first.`); } return null; } const accountsRelease = await releaseFor('accounts', null); if (compareVersions(accountsRelease.version, need.version) < 0) { throw fail(409, 'REQUIREMENT_NOT_MET', `${PRODUCT_NAMES[product]} ${release.version} needs Accounts ${need.version}; the newest Accounts release is ${accountsRelease.version}.`); } const accountsDomain = String(input.accountsDomain || accountsDomainFor(domain)).trim().toLowerCase(); if (!DOMAIN.test(accountsDomain) || accountsDomain === domain) throw fail(400, 'BAD_REQUEST', 'Give Accounts its own domain, like accounts.hope.co.za.'); await preflight(server, 'accounts', accountsRelease.version, now); return { release: accountsRelease, domain: accountsDomain }; } /** * Sites on a server the Hub has no install record for (Hub 2.6.0), from a `status` job's report * (`crosscode status --json`: each church's products with their domain, ports and checkout): * added as live installs on that server, tied to the site registered at that domain, with their * ports on the port list. The customer comes from the registered site, or from the church's other * products here. A product neither tells is left alone (and named in the job's message). */ async function linkFromStatus(job, now = new Date()) { const churches = Array.isArray(job.report?.result?.churches) ? job.report.result.churches : []; const linked = []; const unknown = []; for (const c of churches) { if (!c || !SHORT_NAME.test(String(c.church || ''))) continue; for (const p of Array.isArray(c.products) ? c.products : []) { const product = String(p?.product || ''); if (!PRODUCT_NAMES[product] || !p.domain) continue; const known = await prisma.deployment.findFirst({ where: { shortName: c.church, product, status: { notIn: ['removed', 'failed'] } } }); if (known) { if (known.serverId === job.serverId && !known.installId) await tieToRegistration(known); continue; } const domain = String(p.domain).toLowerCase(); const install = await prisma.install.findFirst({ where: { product, releasedAt: null, url: { contains: `//${domain}` } }, include: { deployment: true } }); const sibling = await prisma.deployment.findFirst({ where: { shortName: c.church, serverId: job.serverId, status: { notIn: ['removed', 'failed'] } } }); const customerId = install?.customerId || sibling?.customerId; const [api, web] = String(p.ports || '').trim().split(/\s+/).map(n => parseInt(n, 10)); if (!customerId || !(web > 0 && api > 0) || install?.deployment) { unknown.push(`${c.church}/${product}`); continue; } const version = /@(\d+\.\d+\.\d+.*)$/.exec(String(p.ref || ''))?.[1] || install?.version || null; const d = await prisma.$transaction(async tx => { const made = await tx.deployment.create({ data: { serverId: job.serverId, customerId, licenceId: install?.licenceId || null, installId: install?.id || null, product, shortName: c.church, domain, webPort: web, apiPort: api, version, timezone: install?.timezone || sibling?.timezone || null, status: 'live', liveAt: now, adminName: install?.adminContact?.name || sibling?.adminName || null, adminEmail: install?.adminContact?.email || sibling?.adminEmail || null }, }); for (const [port, role] of [[web, 'web'], [api, 'api']]) { await tx.port.upsert({ where: { port }, update: { serverId: job.serverId, deploymentId: made.id, role, releasedAt: null, note: 'found on the server' }, create: { port, serverId: job.serverId, deploymentId: made.id, role, note: 'found on the server' } }); } return made; }); linked.push(`${d.shortName} (${PRODUCT_NAMES[product]}, ${domain})`); } } if (linked.length || unknown.length) { const text = [linked.length ? `Added: ${linked.join(', ')}.` : '', unknown.length ? `Not added (no registered site or other product of the church tells the customer, or no ports): ${unknown.join(', ')}.` : ''].filter(Boolean).join(' '); await prisma.job.update({ where: { id: job.id }, data: { message: [job.message, text].filter(Boolean).join(' ') } }); if (linked.length) { await emailJoshua('Installs found on a server', { heading: 'Installs found on a server', blocks: [ { p: 'Added to the Hub:' }, { bullets: linked }, unknown.length ? { note: { kind: 'warning', title: 'Not added', text: `No registered site or other product of the church names the customer, or there are no ports: ${unknown.join(', ')}.` } } : null, { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, ], }); } } return { linked, unknown }; } /** Ties an install record to the site registered with its licence (if it has registered). */ async function tieToRegistration(d) { if (!d.licenceId) return; const install = await prisma.install.findFirst({ where: { licenceId: d.licenceId, releasedAt: null }, include: { deployment: true } }); if (install && !install.deployment) await prisma.deployment.update({ where: { id: d.id }, data: { installId: install.id } }); } /** * A registered site the Hub has no install record for, of a customer with a product on a server: * ask that server what's on it (a `status` job, at most one a day per server), so the site is added by * itself (linkFromStatus). Called after a heartbeat; never fails it. */ async function lookForUnlinked(install, now = new Date()) { try { if (!install || install.releasedAt) return null; const own = await prisma.deployment.findFirst({ where: { installId: install.id } }); if (own) return null; const sibling = await prisma.deployment.findFirst({ where: { customerId: install.customerId, status: { in: ['live', 'waiting_for_proxy'] } }, include: { server: true } }); if (!sibling || sibling.server.removedAt || sibling.server.mode !== 'church') return null; const recent = await prisma.job.findFirst({ where: { serverId: sibling.serverId, type: 'status', createdAt: { gt: new Date(now.getTime() - 24 * HOUR) } } }); if (recent) return null; return await makeJob(prisma, { serverId: sibling.serverId, type: 'status', args: { church: sibling.shortName }, notBefore: now }); } catch (e) { console.warn('[jobs] looking for an unlinked install failed:', e?.message || e); return null; } } // Exactly the JobStatus enum (prisma/schema.prisma; a test checks it): a value Postgres doesn't // know fails the whole query. 2.6.1: 2.6.0 listed a "timed_out" that doesn't exist, so the Failed // filter answered 500 every time. Unknown values from a request are dropped. const JOB_STATUSES = ['scheduled', 'queued', 'delivered', 'succeeded', 'failed', 'rolled_back', 'refused', 'expired', 'missed', 'cancelled']; /** The jobs list's filters (Hub 2.6.0, GET /api/admin/jobs). */ async function listWhere(q = {}) { const and = []; if (q.upcoming === 'true') and.push({ status: { in: ['queued', 'scheduled', 'delivered'] } }); else if (q.status) { const list = String(q.status).split(',').filter(s => JOB_STATUSES.includes(s)); if (!list.length) throw fail(400, 'BAD_REQUEST', 'Unknown job status.'); and.push({ status: { in: list } }); } if (q.type) and.push({ type: String(q.type) }); if (q.serverId) and.push({ serverId: String(q.serverId) }); if (q.deploymentId) and.push({ deploymentId: String(q.deploymentId) }); // By product or church: the matching installs first, then their jobs. const term = searchTerm(q.q); // Products are an enum too: an unknown one is refused, not sent to the database. if (q.product && !PRODUCT_NAMES[String(q.product)]) throw fail(400, 'BAD_REQUEST', 'Unknown product.'); if (q.product || term) { const dWhere = { AND: [ ...(q.product ? [{ product: String(q.product) }] : []), ...(term ? [{ OR: [{ shortName: { contains: term, mode: 'insensitive' } }, { domain: { contains: term, mode: 'insensitive' } }] }] : []), ] }; const ids = (await prisma.deployment.findMany({ where: dWhere, select: { id: true } })).map(d => d.id); and.push({ deploymentId: { in: ids } }); } return and.length ? { AND: and } : {}; } /** 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}.`); } // 2.10.0: a path under /api with a file extension must reach the backend too (FastPanel's // static-file rule sent them to the frontend, which answers as Next.js). A 404 is fine. const file = await get(`https://${d.domain}/api/proxy-check.png`); if (file && /next\.js/i.test(file.headers?.get?.('x-powered-by') || '')) { problems.push(`https://${d.domain}/api/… paths with a file extension (.png, .pdf) reach the frontend: in FastPanel use "location ^~ /api/" for the backend (step 2).`); } if (problems.length) return { live: false, problems }; await prisma.deployment.update({ where: { id: d.id }, data: { status: 'live', liveAt: now } }); const name = PRODUCT_NAMES[d.product]; await emailSiteAdmin(d, `Your ${name} site is ready`, { heading: `Your ${name} site is ready`, sub: `https://${d.domain}`, blocks: [ { p: `${d.customer?.name || 'Your church'}'s ${name} site is ready.` }, { p: 'To start, open the setup: it creates your admin account and walks you through the settings.' }, { button: { label: 'Start the setup', url: `https://${d.domain}/setup` } }, ], }); 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. */ /** * What an update of a product (not Accounts) does to the church's Accounts (Hub 2.6.0). * `crosscode deploy` always updates Accounts too, to its latest release unless told a version, so * the Hub always tells it one: * - the release needs a newer Accounts: the newest Accounts release (refused if none is new enough) * - the church has no Accounts and the release needs it: installed first, in the same batch * - otherwise: the version it runs, so it isn't changed * Returns { version: 'accounts@x' | null, install: { domain, release } | null, note }. */ async function accountsPlan(d, release, accountsRelease) { if (d.product === 'accounts') return { version: null, install: null, note: null }; const acc = await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'accounts', status: { notIn: ['removed', 'failed'] } }, include: { install: true } }); const running = acc ? (acc.install?.version || acc.version || null) : null; const releases = await prisma.release.findMany({ where: { product: d.product } }); const from = d.install?.version || d.version || null; const need = unmetRequirements({ releases, from, target: release.version, siblings: running ? [{ product: 'accounts', version: running }] : [] }).find(u => u.product === 'accounts'); if (!need) return { version: running ? `accounts@${running}` : null, install: null, note: null }; if (!accountsRelease || compareVersions(accountsRelease.version, need.version) < 0) { throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${PRODUCT_NAMES[d.product]} ${release.version} needs Accounts ${need.version}, and there's no Accounts release that new yet.`); } if (acc) { if (acc.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName}: its Accounts isn't live (${acc.status}).`); return { version: `accounts@${accountsRelease.version}`, install: null, note: `${d.shortName}: Accounts is updated from ${running || 'an unknown version'} to ${accountsRelease.version} first (${PRODUCT_NAMES[d.product]} ${release.version} needs ${need.version}).` }; } const domain = accountsDomainFor(d.domain); if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', `${d.shortName}: no Accounts domain could be made from ${d.domain}; install Accounts first (New install).`); return { version: `accounts@${accountsRelease.version}`, install: { domain, release: accountsRelease }, note: `${d.shortName}: Accounts ${accountsRelease.version} is installed first at ${domain} (${PRODUCT_NAMES[d.product]} ${release.version} needs it).` }; } /** * What's happening at a church now (Hub 2.7.0), from its Cross Events install's last heartbeat * (`stats.live`, Events 3.2.0+; a heartbeat older than 30 minutes doesn't count). An Accounts update * takes Events' sign-in down too, so it looks at the church's Events. Null when nothing is known. */ async function liveAt(d, now = new Date()) { const ev = d.product === 'events' ? d : await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'events', status: { notIn: ['removed', 'failed'] } }, include: { install: true } }); const install = ev?.install; const live = install?.stats?.live; if (!live || !install.lastHeartbeatAt || now - new Date(install.lastHeartbeatAt) > 30 * MIN) return null; return { eventsNow: Number(live.eventsNow) || 0, checkInsLastHour: Number(live.checkInsLastHour) || 0 }; } async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, asap = false, confirmLive = false, reason = null, totp = null }, admin, now = new Date()) { // Hub 2.7.0: an emergency update can run as soon as possible (the agent's next poll, within a // minute) instead of at a time at least 15 minutes away (decision 30, changed 2026-11-19). if (asap && !emergency) throw fail(400, 'BAD_REQUEST', 'Only an emergency update runs as soon as possible.'); const when = asap ? now : 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 (!asap && when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update at a time needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice (or choose as soon as possible).`); } 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: choose Cross Events or Accounts installs, not both.'); const product = [...products][0]; // Hub 2.6.0: the page says which product it's updating; a mismatch is refused, never guessed. if (wanted && wanted !== product) throw fail(400, 'WRONG_PRODUCT', `These installs are ${PRODUCT_NAMES[product]}, not ${PRODUCT_NAMES[wanted] || wanted}.`); if (version && /@/.test(String(version)) && !String(version).startsWith(`${product}@`)) throw fail(400, 'WRONG_PRODUCT', `${version} isn't a ${PRODUCT_NAMES[product]} release.`); const release = await releaseFor(product, version ? String(version).replace(/^[a-z]+@/, '') : null); const accountsRelease = product === 'accounts' ? null : await prisma.release.findMany({ where: { product: 'accounts' } }).then(rs => rs.sort((a, b) => compareVersions(b.version, a.version))[0] || null); const plans = new Map(); const warnings = []; // An emergency update takes a site down with little or no notice: a church with an event on now // (people checking in, a session running) is named, and the update waits for a second "yes". if (emergency) { const busy = []; for (const d of deployments) { const live = await liveAt(d, now); if (live && (live.eventsNow > 0 || live.checkInsLastHour > 0)) { busy.push(`${d.shortName} (${[live.eventsNow ? `${live.eventsNow} event(s) on now` : '', live.checkInsLastHour ? `${live.checkInsLastHour} check-in(s) in the last hour` : ''].filter(Boolean).join(', ')})`); } } if (busy.length && !confirmLive) { throw fail(409, 'LIVE_EVENT', `An event is on now at ${busy.join('; ')}. The site will be down for a few minutes during the update: people checking in or registering will be interrupted. Update anyway?`); } if (busy.length) warnings.push(`Updated while an event was on: ${busy.join('; ')}.`); } for (const d of deployments) { if (d.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName} isn't live (${d.status}).`); // 2.7.1: one update at a time per install, so a second click (or a second tab) can't plan another. const pending = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'deploy', status: { in: ['scheduled', 'queued', 'delivered'] } } }); if (pending) throw fail(409, 'ALREADY_PLANNED', `${d.shortName} already has an update ${pending.status === 'delivered' ? 'running' : `planned for ${sast(pending.notBefore)}`}. Cancel it first (its job) to plan another.`); if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`); if (d.install) { // Accounts is handled below (kept, updated, or installed first); anything else must be met. const unmet = (await unmetRequirementsFor(d.install, release.version)).filter(u => u.product !== 'accounts'); 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.`); const invalid = invalidFor(servers.serverConfig(d.server), await servers.installDefaults()); if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${d.shortName}: fix ${d.server.name}'s configuration first. ${invalid.join(' ')}`); warnings.push(...scheduleWarnings(when, d)); const plan = await accountsPlan(d, release, accountsRelease); if (plan.install) await preflight(d.server, 'accounts', plan.install.release.version, now); if (plan.note) warnings.push(plan.note); plans.set(d.id, plan); } const installsFirst = [...plans.values()].filter(p => p.install).length; const batchId = deployments.length + installsFirst > 1 ? servers.newId('batch') : null; const name = PRODUCT_NAMES[product]; const jobs = []; let order = 0; for (const d of deployments) { const plan = plans.get(d.id); const next = () => ({ batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' }); if (plan.install) { // The church's Accounts, installed just before its update (a licence, ports, an add-product job). const acc = await prisma.$transaction(async tx => { let licence = await tx.licence.findFirst({ where: { customerId: d.customerId, product: 'accounts', status: { not: 'revoked' } }, include: { install: true } }); if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${d.shortName}: its Accounts licence is already used by ${licence.install.url}. Link that install (Installs → Link existing) instead.`); if (!licence) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence; const ports = await servers.allocatePorts(tx, d.serverId, now); const a = await tx.deployment.create({ data: { serverId: d.serverId, customerId: d.customerId, licenceId: licence.id, product: 'accounts', shortName: d.shortName, domain: plan.install.domain, webPort: ports.web, apiPort: ports.api, timezone: d.timezone, adminName: d.adminName, adminEmail: d.adminEmail, status: 'installing' } }); await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: a.id } }); const o = next(); const job = await makeJob(tx, { serverId: d.serverId, type: 'add-product', deploymentId: a.id, createdById: admin?.id || null, notBefore: when, ...o, args: { church: d.shortName, product: 'accounts', version: `accounts@${plan.install.release.version}`, domain: plan.install.domain, ports }, }); return job; }); jobs.push(acc); } const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`; const message = asap ? `${name} is being updated now. The site will be unavailable for a few minutes. Why: ${reason}` : `${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); // Accounts goes first in the same deploy: told its version, so it's never changed by surprise. const versions = [...(plan.version && !plan.install ? [plan.version] : []), `${product}@${release.version}`]; jobs.push(await makeJob(prisma, { serverId: d.serverId, type: 'deploy', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, emergency, reason, ...next(), notBefore: when, noticeId, args: { church: d.shortName, products: [product], versions }, })); await emailSiteAdmin(d, asap ? `Urgent: ${name} is being updated now` : `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, { heading: asap ? `${name} is being updated now` : emergency ? `An urgent ${name} update` : `A planned ${name} update`, preheader: message, blocks: [ { rows: [['Site', d.domain], ['When', asap ? 'Now' : sast(when)], ['Version', release.version]] }, { p: 'The site will be unavailable for a few minutes while it\'s updated.' }, emergency && reason ? { note: { kind: 'warning', title: 'Why it can\'t wait', text: reason } } : null, ...(release.notes ? [{ divider: true }, { h: `What's new in ${release.version}` }, ...notesBlocks(release.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`, { heading: 'The update is cancelled', blocks: [ { note: { kind: 'info', title: 'Your site keeps running as it is', text: `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled.` } }, ], }); } if (job.batchId) await advanceBatch(updated, now); if (job.type === 'uninstall' && job.deployment) await uninstallNotRun(job, 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'; } /** * An uninstall that failed or won't run: every install it named is still on the server (2.12.0: * a run can name several products, when one was added to another's uninstall). */ async function uninstallNotRun(job, deployment) { const products = job.args?.products; const all = products ? [deployment, ...(await churchSiblings(deployment))] : [deployment]; for (const t of all) { if (t.id !== deployment.id && (!products.includes(t.product) || t.status !== 'uninstalling')) continue; await prisma.deployment.update({ where: { id: t.id }, data: { status: statusBeforeUninstall(t) } }); } } /** * 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; } const agentAtLeast = (server, version) => compareVersions(server?.agentVersion || '0.0.0', version) >= 0; /** The church's other products on the same server that are still there (2.12.0). */ function churchSiblings(d) { return prisma.deployment.findMany({ where: { serverId: d.serverId, shortName: d.shortName, id: { not: d.id }, status: { notIn: ['removed', 'failed'] } }, include: { install: true, server: true, customer: true } }); } /** * An install is gone from its server: removed here, its ports freed (after 30 days, as for any * uninstall), its licence's heartbeats refused, and what was still planned for it cancelled. */ async function markRemoved(d, now, { except = null, why = 'Not needed: the install is removed.' } = {}) { await prisma.deployment.update({ where: { id: d.id }, data: { status: 'removed', removedAt: now } }); await prisma.port.updateMany({ where: { port: { in: [d.webPort, d.apiPort] } }, data: { releasedAt: now, deploymentId: d.id } }); if (d.installId) await prisma.install.update({ where: { id: d.installId }, data: { releasedAt: now } }); const open = await prisma.job.findMany({ where: { deploymentId: d.id, status: { in: ['scheduled', 'queued'] } } }); for (const j of open) { if (j.id === except) continue; await prisma.job.update({ where: { id: j.id }, data: { status: 'cancelled', message: why, finishedAt: now } }); if (j.noticeId) await endNotice(j.noticeId, now); } } /** * The church's uninstalls on this server that haven't run yet (2.12.0), soonest first: when, what * they remove (`products` null: the whole church), and whether another product can still be added * to the run (its export hasn't started). */ async function pendingUninstalls(d, siblings) { const list = await prisma.job.findMany({ where: { type: 'uninstall', deploymentId: { in: [d.id, ...siblings.map(s => s.id)] }, status: { in: ['scheduled', 'queued'] } }, orderBy: { notBefore: 'asc' } }); const out = []; for (const job of list) { const exportJob = job.batchId ? await prisma.job.findFirst({ where: { batchId: job.batchId, type: 'export' } }) : null; const products = job.args?.products || null; const joinable = !!products && job.status === 'scheduled' && (!exportJob || ['scheduled', 'queued'].includes(exportJob.status)); out.push({ job, exportJob, products, joinable }); } return out; } /** * What an uninstall of this install would remove (for the install's page): only this product, or * the whole church with an agent before 1.5.0 (then refused while there are others). `pending`: * the church's uninstalls not run yet, which this one can join. `lastProduct`: every other product * is being uninstalled, so (at its own, later time) this one takes the whole church with it. */ async function uninstallPlan(d) { const others = await churchSiblings(d); const pending = await pendingUninstalls(d, others); return { onlyThisProduct: agentAtLeast(d.server, agent.PRODUCT_UNINSTALL_MIN_AGENT), minAgent: agent.PRODUCT_UNINSTALL_MIN_AGENT, others: others.map(o => ({ id: o.id, product: o.product, domain: o.domain, status: o.status })), pending: pending.map(p => ({ jobId: p.job.id, notBefore: p.job.notBefore, products: p.products, joinable: p.joinable })), lastProduct: others.length > 0 && others.every(o => o.status === 'uninstalling'), }; } /** Hub 2.12.0: an install's record can be removed by hand once it's sent nothing for this long. */ const STALE_MS = DAY; /** When the install was last heard from: its last heartbeat, else when it went live or was made. */ function lastHeardAt(d) { return d.install?.lastHeartbeatAt || d.liveAt || d.createdAt || null; } /** Whether an install's record can be removed without an uninstall: no heartbeat for 24 hours. */ function staleness(d, now = new Date()) { const since = lastHeardAt(d); const stale = !['removed', 'failed', 'installing'].includes(d.status) && !!since && now - new Date(since) >= STALE_MS; return { since, stale }; } /** * Remove an install from the Hub that's no longer on its server (uninstalled by hand, the server * rebuilt …): nothing runs on the server. Only after 24 hours without a heartbeat, typing the short * name; what was planned for it is cancelled. */ async function forgetStale(deploymentId, { confirm }, now = new Date()) { const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true } }); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to confirm.`); if (!staleness(d, now).stale) throw fail(409, 'NOT_STALE', 'Only an install that hasn\'t sent a heartbeat for 24 hours can be removed from the Hub; a working one is uninstalled.'); const running = await prisma.job.count({ where: { deploymentId: d.id, status: 'delivered' } }); if (running) throw fail(409, 'BUSY', 'The agent is running a job for it: wait for its report.'); await markRemoved(d, now, { why: 'Not needed: the install was removed from the Hub (no heartbeat for 24 hours).' }); 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. * * Hub 2.12.0: one product at a time (agent 1.5.0). When another product of the church is already * planned for uninstall, `join` says what to do: true adds this product to that run (one export * and one uninstall for both), false gives it its own batch at `at`. Not given: refused with * CHOOSE, so the page asks. The script removes the whole church (folder, app user) when a run * names every product it still has, so the last product to go always takes the church with it. */ async function scheduleUninstall({ deploymentId, at, totp, confirm, join, joinJobId }, admin, now = new Date()) { requireTotp(admin, totp); const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, server: true, customer: 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.'); // Only this product goes (agent 1.5.0). An older agent removes the whole church, so it's refused // while the church has other products on the server. const siblings = await churchSiblings(d); const onlyThis = agentAtLeast(d.server, agent.PRODUCT_UNINSTALL_MIN_AGENT); if (!onlyThis && siblings.length) { throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}: it would remove all of ${d.shortName} (${[d, ...siblings].map(x => PRODUCT_NAMES[x.product]).join(' and ')}). Update the agent to ${agent.PRODUCT_UNINSTALL_MIN_AGENT} or later to uninstall only ${PRODUCT_NAMES[d.product]}.`); } // Another product's uninstall that hasn't run yet: join it, or a time of its own. const pending = await pendingUninstalls(d, siblings); const whole = pending.find(p => !p.products); if (whole) throw fail(409, 'ALREADY', `${PRODUCT_NAMES[d.product]} already goes with the uninstall of all of ${d.shortName} on ${sast(whole.job.notBefore)}.`); if (pending.length && join === undefined) { const first = pending[0]; throw Object.assign(fail(409, 'CHOOSE', `${first.products.map(p => PRODUCT_NAMES[p]).join(' and ')} of ${d.shortName} is already being uninstalled on ${sast(first.job.notBefore)}: add ${PRODUCT_NAMES[d.product]} to that, or give it its own time.`), { details: { jobId: first.job.id, notBefore: first.job.notBefore } }); } const target = join ? pending.find(p => (joinJobId ? p.job.id === joinJobId : true) && p.joinable) : null; if (join && !target) throw fail(409, 'NOT_JOINABLE', 'That uninstall has already started (its export ran): give this one its own time.'); const when = target ? target.job.notBefore : new Date(at || now.getTime() + 7 * DAY); // The church gets at least 4 hours' notice, also when this joins a run planned earlier. if (when - now < SCHEDULE_MIN_HOURS * HOUR) throw fail(400, 'TOO_SOON', target ? `That uninstall is less than ${SCHEDULE_MIN_HOURS} hours away, too soon to tell the church: give this one its own time.` : `An uninstall is planned at least ${SCHEDULE_MIN_HOURS} hours ahead.`); // The church's other products sign in through Accounts: it goes last (or in the same run). if (d.product === 'accounts' && siblings.length) { const staying = siblings.filter(s => s.status !== 'uninstalling'); if (staying.length) throw fail(409, 'ACCOUNTS_IN_USE', `${staying.map(s => PRODUCT_NAMES[s.product]).join(' and ')} of ${d.shortName} sign${staying.length === 1 ? 's' : ''} in through Accounts: uninstall ${staying.length === 1 ? 'it' : 'them'} first, then Accounts.`); const later = pending.filter(p => p.job.notBefore > when).pop(); if (later) throw fail(400, 'ACCOUNTS_FIRST', `Accounts goes after the church's other products: plan it for ${sast(later.job.notBefore)} or later, or add it to that uninstall.`); } let exportJob; let uninstallJob; if (target) { // One run for both: the export and the uninstall name every product, in deploy order. const products = [...new Set([...target.products, d.product])].sort((a, b) => PRODUCT_ORDER.indexOf(a) - PRODUCT_ORDER.indexOf(b)); uninstallJob = await prisma.job.update({ where: { id: target.job.id }, data: { args: agent.jobArgsSchemas.uninstall.parse({ ...target.job.args, products }) } }); exportJob = target.exportJob ? await prisma.job.update({ where: { id: target.exportJob.id }, data: { args: agent.jobArgsSchemas.export.parse({ ...target.exportJob.args, products }) } }) : null; 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); } else { const products = onlyThis ? { products: [d.product] } : {}; 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) } }); 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, ...products } }); 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, ...products } }); } 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)}`, { heading: `${PRODUCT_NAMES[d.product]} is closing`, blocks: [ { p: `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed.` }, { rows: [['Site', d.domain], ['Closes on', sast(when)]] }, { note: { kind: 'info', title: 'Your data', text: `Shortly before, ${target ? 'the church\'s site admin gets' : 'you\'ll get'} an email with a link to download all the data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.` } }, ], }); return { exportJob, uninstallJob, joined: !!target, lastProduct: siblings.every(s => s.status === 'uninstalling') }; } /** 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/.'); 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.
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)}`, { heading: 'Planned maintenance', blocks: [ { rows: [['Site', d.domain], ['When', sast(when)]] }, { p: `${PRODUCT_NAMES[d.product]} will be moved to its new home. 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.`); // Hub 2.19.0: an agent update is to a known agent release, the latest when none is asked for. if (type === 'update-agent') args = { version: await agentTag(args?.version) }; return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now }); } /** Mark or unmark an install as a demo site. Marking it asks for its short name, since a demo site's data can be replaced. */ async function setDemo(deploymentId, { isDemo, confirm }) { const d = await prisma.deployment.findUnique({ where: { id: deploymentId } }); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); if (d.product !== 'events') throw fail(400, 'NOT_EVENTS', 'Only Cross Events installs have demo data.'); if (isDemo && confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to mark it as a demo site.`); return prisma.deployment.update({ where: { id: d.id }, data: { isDemo: !!isDemo } }); } /** * Replace a demo site's data with a demo set (`crosscode demo`, a backup is taken first). Only for * installs marked as demo sites, typing the short name, on an agent that knows the job (1.2.0+). */ async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Date()) { const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } }); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); if (!d.isDemo) throw fail(409, 'NOT_DEMO', `${d.shortName} isn't marked as a demo site.`); if (d.product !== 'events') throw fail(400, 'NOT_EVENTS', 'Only Cross Events installs have demo data.'); if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; demo data goes on an installed site.`); if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to replace its data.`); if (!agent.DEMO_PROFILES.includes(profile)) throw fail(400, 'BAD_REQUEST', `Choose one of: ${agent.DEMO_PROFILES.join(', ')}.`); if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.'); if (compareVersions(d.server.agentVersion || '0.0.0', agent.SEED_DEMO_MIN_AGENT) < 0) { throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; demo data needs ${agent.SEED_DEMO_MIN_AGENT} or later (update the agent first).`); } const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } }); if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`); const adminEmail = d.adminEmail && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.adminEmail) ? d.adminEmail.toLowerCase() : undefined; return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, profile, ...(adminEmail ? { adminEmail } : {}) } }); } // ─── An install's .env (2.8.0, contracts 1.12.0, agent 1.3.0) ───────────────── const ENV_PRODUCTS = ['events', 'accounts']; const ENV_OPEN = ['queued', 'delivered']; /** The install, checked for reading or changing its .env: installed, a product the script knows, an agent that can. */ async function envDeployment(deploymentId, now) { const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } }); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); if (!ENV_PRODUCTS.includes(d.product)) throw fail(400, 'NOT_SUPPORTED', `${PRODUCT_NAMES[d.product] || d.product} installs don't have .env settings here yet.`); if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; .env settings are for an installed site.`); if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.'); if (compareVersions(d.server.agentVersion || '0.0.0', agent.ENV_JOBS_MIN_AGENT) < 0) { throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; .env settings need ${agent.ENV_JOBS_MIN_AGENT} or later (update the agent first).`); } const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } }); if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`); return d; } /** What the install's page shows: the last read of its .env (secrets only as set or not) and any env job not finished. */ async function envState(deploymentId) { const d = await prisma.deployment.findUnique({ where: { id: deploymentId } }); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); const lastRead = await prisma.job.findFirst({ where: { deploymentId, type: 'env-read', status: 'succeeded' }, orderBy: { finishedAt: 'desc' } }); const parsed = lastRead ? agent.envReadResultSchema.safeParse(lastRead.report?.result?.env) : null; const pending = await prisma.job.findMany({ where: { deploymentId, type: { in: ['env-read', 'env-set'] }, status: { in: ENV_OPEN } }, orderBy: { createdAt: 'asc' } }); const lastSet = await prisma.job.findFirst({ where: { deploymentId, type: 'env-set', status: { notIn: ENV_OPEN } }, orderBy: { createdAt: 'desc' } }); return { supported: ENV_PRODUCTS.includes(d.product), minAgent: agent.ENV_JOBS_MIN_AGENT, env: parsed?.success ? parsed.data : null, readJobId: lastRead?.id || null, pending: pending.map(j => ({ id: j.id, type: j.type, status: j.status, createdAt: j.createdAt })), lastSet: lastSet ? { id: lastSet.id, status: lastSet.status, message: lastSet.message, finishedAt: lastSet.finishedAt, args: lastSet.args } : null, }; } /** Ask the agent for the install's .env values (an env-read job, at its next poll). */ async function readEnv(deploymentId, admin, now = new Date()) { const d = await envDeployment(deploymentId, now); const open = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'env-read', status: { in: ENV_OPEN } } }); if (open) return open; return makeJob(prisma, { serverId: d.serverId, type: 'env-read', args: { church: d.shortName, product: d.product }, deploymentId: d.id, createdById: admin?.id || null, notBefore: now }); } /** * Change values in one of the install's .env files, then (with `restart`, or always for the * frontend's file, which needs a rebuild) reload it. Never secrets (the contract refuses them, and * so does the server); values the app can't start with are refused here first. If the site doesn't * come back, the server puts the file back. */ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now = new Date()) { const d = await envDeployment(deploymentId, now); const values = set && typeof set === 'object' && !Array.isArray(set) ? Object.fromEntries(Object.entries(set).map(([k, v]) => [k, String(v ?? '')])) : {}; const bad = agent.invalidValues(values); if (Object.keys(bad).length) throw fail(400, 'BAD_VALUE', Object.values(bad).join(' ')); const args = { church: d.shortName, product: d.product, file: String(file || 'backend/.env'), set: values, unset: Array.isArray(unset) ? unset.map(String) : [], restart: restart !== false }; const open = await prisma.job.findFirst({ where: { deploymentId: d.id, type: 'env-set', status: { in: ENV_OPEN } } }); if (open) throw fail(409, 'ALREADY_PLANNED', 'A change to this install\'s .env is already waiting for the agent. Wait for it to finish first.'); return makeJob(prisma, { serverId: d.serverId, type: 'env-set', args, deploymentId: d.id, createdById: admin?.id || null, notBefore: now }); } module.exports = { readEnv, setEnv, envState, readFrp, writeFrp, portsProbed, probeServers, PROBE_SPARE, WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch, JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow, fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail, };