diff --git a/CHANGELOG.md b/CHANGELOG.md index 6743cda..bff5fa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.7.0] - 2026-11-19 + +### Added + +- **Emergency updates "as soon as possible".** An emergency update (still with a reason and your + two-factor code) can run at the agent's next poll, within a minute, instead of at a time at least + 15 minutes away, which stays as the other choice. The church is emailed "is being updated now" and + sees a banner saying so. (ROADMAP-v3 decision 30, changed 2026-11-19.) +- **An event on now holds an emergency update for a second yes.** From the church's Cross Events + heartbeat (`stats.live`, Events 3.2.0+: events with a session or a one-day event on now, and + check-ins in the last hour; a heartbeat older than 30 minutes doesn't count), an emergency update + that would take such a site down is refused with what's on (`LIVE_EVENT`) until you confirm. An + Accounts update looks at the church's Events, whose sign-in it takes down. The audit log records it. + +### Changed + +- Contracts 1.10.0 (`backend/vendor/`), so the heartbeat keeps `stats.live`. + ## [2.6.1] - 2026-11-19 ### Fixed diff --git a/backend/package-lock.json b/backend/package-lock.json index e6de1e3..046cba0 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,16 +1,16 @@ { "name": "events-hub-backend", - "version": "2.6.1", + "version": "2.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.6.1", + "version": "2.7.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.8.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", @@ -609,9 +609,9 @@ "license": "MIT" }, "node_modules/@crosscode/contracts": { - "version": "1.8.0", - "resolved": "file:vendor/crosscode-contracts-1.8.0.tgz", - "integrity": "sha512-OJb/egG9duMnN1D3AEpoLpYXtzeVpqU6SuXDbVcBKYARGNC9VOwfDsLwxbThR6igRtByuMhJ+jJEkFPlTRFHdg==", + "version": "1.10.0", + "resolved": "file:vendor/crosscode-contracts-1.10.0.tgz", + "integrity": "sha512-FUm5qrZcyhM7JW7H1DNHifY9IFaxCJhVsLVed++gag65RO+EFnAjlPLw2bJqPIX/9e2CD1OBtHmNKxc9NjBCWA==", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/backend/package.json b/backend/package.json index d6b1f27..37b7e88 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.6.1", + "version": "2.7.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", @@ -20,7 +20,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.8.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.10.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/src/routes/servers.js b/backend/src/routes/servers.js index 3f3cdcb..cc0dc5b 100644 --- a/backend/src/routes/servers.js +++ b/backend/src/routes/servers.js @@ -211,7 +211,7 @@ router.post('/deployments/:id/uninstall', wrap(async (req, res) => { router.post('/updates', wrap(async (req, res) => { const out = await jobs.scheduleUpdate(req.body || {}, req.admin); - await audit(req, req.body?.emergency ? 'emergency_update_scheduled' : 'update_scheduled', out.batchId || out.jobs[0]?.id, { deployments: req.body?.deploymentIds, version: req.body?.version, at: req.body?.at, reason: req.body?.reason || null }); + await audit(req, req.body?.emergency ? 'emergency_update_scheduled' : 'update_scheduled', out.batchId || out.jobs[0]?.id, { deployments: req.body?.deploymentIds, version: req.body?.version, at: req.body?.asap ? 'as soon as possible' : req.body?.at, reason: req.body?.reason || null, ...(req.body?.confirmLive ? { duringLiveEvent: true } : {}) }); res.status(201).json(out); })); diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index 0dc45e6..bad920e 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -700,13 +700,29 @@ async function accountsPlan(d, release, accountsRelease) { 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).` }; } -async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) { - const when = new Date(at); +/** + * 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 (when - now < EMERGENCY_MIN_MINUTES * MIN) throw fail(400, 'TOO_SOON', `An emergency update needs at least ${EMERGENCY_MIN_MINUTES} minutes' notice.`); + 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).`); } @@ -724,6 +740,21 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version, 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}).`); if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`); @@ -769,7 +800,9 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version, jobs.push(acc); } const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`; - const message = `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`; + const 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}`]; @@ -779,7 +812,7 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version, args: { church: d.shortName, products: [product], versions }, })); const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : ''; - await emailSiteAdmin(d, `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`); + await emailSiteAdmin(d, asap ? `Urgent: ${name} is being updated now` : `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`); } return { jobs, batchId, warnings: [...new Set(warnings)] }; } diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js index c81dae7..7c863a1 100644 --- a/backend/tests/servers.test.js +++ b/backend/tests/servers.test.js @@ -682,3 +682,51 @@ describe('the jobs list only asks for statuses the database knows (2.6.1)', () = expect(await jobs.listWhere({ status: 'failed,expired' })).toEqual({ AND: [{ status: { in: ['failed', 'expired'] } }] }); }); }); + +describe('emergency updates as soon as possible, and events on now (2.7.0)', () => { + async function liveChurch(shortName, live = null, heardMinutesAgo = 5) { + let server = await db.server.findFirst({ where: { name: 'church-1' } }); + if (!server) { + server = (await joinServer()).server; + await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' }); + } + const n = (await db.deployment.count()) * 2; + const install = await db.install.create({ data: { id: `inst-${shortName}`, customerId: 'cust-1', product: 'events', name: shortName, url: `https://events.${shortName}.co.za`, secret: 'x', version: '2.3.0', lastHeartbeatAt: new Date(NOW.getTime() - heardMinutesAgo * 60e3), stats: live ? { live } : {}, adminContact: { name: 'Admin', email: `admin@${shortName}.test` } } }); + return db.deployment.create({ data: { id: `dep-${shortName}`, serverId: server.id, customerId: 'cust-1', installId: install.id, product: 'events', shortName, domain: `events.${shortName}.co.za`, webPort: 23000 + n, apiPort: 23001 + n, status: 'live' } }); + } + const urgent = (ids, extra = {}) => jobs.scheduleUpdate({ deploymentIds: ids, version: '2.4.0', emergency: true, reason: 'Broken release', totp: totpNow(), ...extra }, admin, NOW); + + test('as soon as possible: queued now for the agent\'s next poll, with the church told it\'s happening now', async () => { + const d = await liveChurch('quick'); + const { jobs: [job] } = await urgent([d.id], { asap: true }); + expect(job).toMatchObject({ status: 'queued', emergency: true }); + expect(new Date(job.notBefore).getTime()).toBe(NOW.getTime()); + expect(mockMails.find(m => m.to === 'admin@quick.test')?.subject).toBe('Urgent: Cross Events is being updated now'); + const notice = await db.notice.findUnique({ where: { id: job.noticeId } }); + expect(notice.message).toContain('is being updated now'); + }); + + test('still an emergency only, with a reason and two-factor; at a time it\'s still 15 minutes', async () => { + const d = await liveChurch('rules'); + await expect(jobs.scheduleUpdate({ deploymentIds: [d.id], version: '2.4.0', asap: true }, admin, NOW)).rejects.toMatchObject({ message: expect.stringContaining('Only an emergency') }); + await expect(urgent([d.id], { asap: true, reason: '' })).rejects.toMatchObject({ message: expect.stringContaining('reason') }); + await expect(urgent([d.id], { asap: true, totp: '000000' })).rejects.toMatchObject({ code: 'BAD_TOTP' }); + await expect(urgent([d.id], { at: new Date(NOW.getTime() + 5 * 60e3) })).rejects.toMatchObject({ code: 'TOO_SOON' }); + }); + + test('a church with an event on now is named, and the update waits for a second yes', async () => { + const busy = await liveChurch('busy', { eventsNow: 1, checkInsLastHour: 37 }); + const calm = await liveChurch('calm', { eventsNow: 0, checkInsLastHour: 0 }); + await expect(urgent([busy.id, calm.id], { asap: true })).rejects.toMatchObject({ code: 'LIVE_EVENT', message: expect.stringContaining('busy (1 event(s) on now, 37 check-in(s) in the last hour)') }); + expect(await db.job.count()).toBe(0); + const out = await urgent([busy.id, calm.id], { asap: true, confirmLive: true }); + expect(out.jobs).toHaveLength(2); + expect(out.warnings.join(' ')).toContain('Updated while an event was on: busy'); + }); + + test('an old heartbeat, or one without live stats, doesn\'t hold an update back', async () => { + const stale = await liveChurch('stale', { eventsNow: 3, checkInsLastHour: 0 }, 90); + const older = await liveChurch('older'); + expect((await urgent([stale.id, older.id], { asap: true })).jobs).toHaveLength(2); + }); +}); diff --git a/backend/vendor/crosscode-contracts-1.10.0.tgz b/backend/vendor/crosscode-contracts-1.10.0.tgz new file mode 100644 index 0000000..b1aa962 Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.10.0.tgz differ diff --git a/backend/vendor/crosscode-contracts-1.8.0.tgz b/backend/vendor/crosscode-contracts-1.8.0.tgz deleted file mode 100644 index 5f4fc56..0000000 Binary files a/backend/vendor/crosscode-contracts-1.8.0.tgz and /dev/null differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c0e8a05..1c2ea2d 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.6.1", + "version": "2.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.6.1", + "version": "2.7.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index accf3ef..a042604 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.6.1", + "version": "2.7.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx index 467c634..b1abddb 100644 --- a/frontend/src/app/(hub)/servers/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/[id]/page.tsx @@ -3,7 +3,7 @@ import React, { useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { useParams, useRouter, useSearchParams } from "next/navigation"; -import { api, errorText } from "@/lib/api"; +import { api, ApiError, errorText } from "@/lib/api"; import { ago, bytes, fmtDate } from "@/lib/format"; import { useServerPaged } from "@/lib/paging"; import { PRODUCT_NAMES } from "@/lib/products"; @@ -28,7 +28,7 @@ export default function DeploymentPage() { const [d, setD] = useState(null); const [msg, setMsg] = useState(warn ? { type: "err", text: warn } : null); const [problems, setProblems] = useState([]); - const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" }); + const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" }); const [adopt, setAdopt] = useState({ eventsDir: "", version: "", address: "", at: toInput(new Date(Date.now() + 5 * H)) }); const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" }); const [demo, setDemo] = useState({ profile: "events", confirm: "", markConfirm: "" }); @@ -44,13 +44,17 @@ export default function DeploymentPage() { useEffect(() => { load(); }, [load]); useEffect(() => { api("/api/admin/releases").then(setReleases).catch(() => {}); }, []); - const act = async (path: string, body: unknown, ok: string) => { + const act = async (path: string, body: Record, ok: string) => { setMsg(null); try { const r = await api<{ warnings?: string[] }>(path, { method: "POST", body }); setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` }); load(); - } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + } catch (e) { + // Hub 2.7.0: an event is on there now: ask once more, then go ahead. + if (e instanceof ApiError && e.code === "LIVE_EVENT" && !body.confirmLive && window.confirm(e.message)) return act(path, { ...body, confirmLive: true }, ok); + setMsg({ type: "err", text: errorText(e) }); + } }; const proxyDone = async () => { setMsg(null); @@ -100,7 +104,7 @@ export default function DeploymentPage() { )} {x.status === "live" && ( -
{ e.preventDefault(); act("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: fromInput(upd.at), emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, "Planned. The site admin was emailed and sees a banner."); }}> + { e.preventDefault(); const asap = upd.emergency && upd.asap; act("/api/admin/updates", { deploymentIds: [x.id], product: x.product, version: upd.version || undefined, at: asap ? undefined : fromInput(upd.at), asap, emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, asap ? "Started: the agent picks it up within a minute. The site admin was emailed and sees a banner." : "Planned. The site admin was emailed and sees a banner."); }}>

Schedule an update

@@ -109,13 +113,20 @@ export default function DeploymentPage() { {releases.filter(r => r.product === x.product).map(r => )}
-
setUpd({ ...upd, at: e.target.value })} />

At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.

- + {upd.emergency && upd.asap + ?
When

As soon as possible: the agent starts within a minute.

+ :
setUpd({ ...upd, at: e.target.value })} />

At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.

} + {upd.emergency && <> +
+ When the emergency update runs + + +
setUpd({ ...upd, reason: e.target.value })} />
setUpd({ ...upd, totp: e.target.value })} />
} -
+
)} diff --git a/frontend/src/app/(hub)/servers/updates/page.tsx b/frontend/src/app/(hub)/servers/updates/page.tsx index 9392c99..67ce4df 100644 --- a/frontend/src/app/(hub)/servers/updates/page.tsx +++ b/frontend/src/app/(hub)/servers/updates/page.tsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; -import { api, errorText } from "@/lib/api"; +import { api, ApiError, errorText } from "@/lib/api"; import { fmtDate } from "@/lib/format"; import { usePaged } from "@/lib/paging"; import { PRODUCT_NAMES } from "@/lib/products"; @@ -30,7 +30,7 @@ export default function UpdatesPage() { const [releases, setReleases] = useState([]); const [upcoming, setUpcoming] = useState([]); const [chosen, setChosen] = useState([]); - const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" }); + const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, asap: true, reason: "", totp: "" }); const [msg, setMsg] = useState(null); const load = useCallback(() => { @@ -54,17 +54,22 @@ export default function UpdatesPage() { setMsg(null); }; - const submit = async (e: React.FormEvent) => { - e.preventDefault(); + const submit = async (e: React.FormEvent | null, confirmLive = false) => { + e?.preventDefault(); setMsg(null); + const asap = form.emergency && form.asap; try { - const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, product, version: form.version || undefined, at: fromInput(form.at), emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } }); + const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, product, version: form.version || undefined, at: asap ? undefined : fromInput(form.at), asap, confirmLive, emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } }); const deploys = r.jobs.filter(j => j.type === "deploy").length; const installs = r.jobs.length - deploys; setMsg({ type: "ok", text: `Planned for ${deploys} install(s)${installs ? `, with ${installs} Accounts install(s) first` : ""}; each church was emailed and sees a banner.${r.warnings.length ? ` Note: ${r.warnings.join(" ")}` : ""}` }); setChosen([]); load(); - } catch (err) { setMsg({ type: "err", text: errorText(err) }); } + } catch (err) { + // Hub 2.7.0: an event is on at one of them: ask once more, then go ahead. + if (err instanceof ApiError && err.code === "LIVE_EVENT" && !confirmLive && window.confirm(err.message)) return submit(null, true); + setMsg({ type: "err", text: errorText(err) }); + } }; const name = PRODUCT_NAMES[product]; @@ -103,14 +108,21 @@ export default function UpdatesPage() { {product === "events" &&

Each church's Accounts stays on its version, unless this release needs a newer one: then it's updated first in the same deploy, or installed first if the church has none. The confirmation lists what happens.

} -
setForm({ ...form, at: e.target.value })} />

At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.

- + {form.emergency && form.asap + ?
When

As soon as possible: the agent starts within a minute. They run one at a time.

+ :
setForm({ ...form, at: e.target.value })} />

At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.

} + {form.emergency && <> +
+ When the emergency update runs + + +
setForm({ ...form, reason: e.target.value })} />
setForm({ ...form, totp: e.target.value })} />
} - + )}