Files
events-hub/backend/src/routes/admin.js
T
joshuaandClaude Opus 5.5 ab6a0c6914 Hub 2.0 step 2: protocol v2 next to v1
- Accepts protocol 1 and 2 (utils/protocol.js); v2 bodies checked with the
  contracts' zod schemas (400 INVALID_REQUEST), v1 unchanged
- v2 register/heartbeat carry product (409 WRONG_PRODUCT on a mismatch),
  register stores the install's public key, stats stored per product
- v2 replies add linkedProducts (the church's other installs in use with a
  public key); v1 replies unchanged
- Licence tokens carry customerId and product
- Until releases per product, only Events installs get releases / "behind"
- Tests: every contract sample through the real routes, replies checked
  against the contract response schemas

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:37:02 +02:00

484 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** The Hub dashboard's API (admin login required). */
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { generateLicence, checkReopen } = require('../utils/licences');
const { isProduct, PRODUCT_NAMES } = require('../utils/products');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
const licenceToken = require('../utils/licenceToken');
const { smtpConfigured, testSmtp } = require('../utils/mail');
const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releases');
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases } = require('../utils/releaseSync');
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
const router = express.Router();
router.use(protect);
const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many test emails — wait a few minutes.' } });
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[admin]', e);
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
});
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
function dateOrNull(v) {
if (v == null || v === '') return null;
const d = new Date(v);
if (Number.isNaN(d.getTime())) throw bad('Not a valid date.');
return d;
}
// The health of an install at a glance, for lists.
function summary(install, settings, now = new Date()) {
const current = problems(install, settings, now);
const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok';
return {
id: install.id,
product: install.product,
name: install.name,
url: install.url,
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
version: install.version,
// Releases are Cross Events' until releases per product (Hub 2.0 step 3).
behind: !!(install.product === 'events' && settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0),
licence: install.licence ? { id: install.licence.id, status: install.licence.status, expiresAt: install.licence.expiresAt } : null,
lastHeartbeatAt: install.lastHeartbeatAt,
status: worst,
problems: current,
releasedAt: install.releasedAt,
};
}
// ─── Dashboard ────────────────────────────────────────────────────────────────
router.get('/dashboard', wrap(async (req, res) => {
const settings = await getSettings();
const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
const rows = installs.map(i => summary(i, settings));
const [customers, licences, openAlerts] = await Promise.all([
prisma.customer.count(),
prisma.licence.groupBy({ by: ['status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
]);
res.json({
latestVersion: settings.latest_version || null,
counts: {
installs: rows.length,
healthy: rows.filter(r => r.status === 'ok').length,
warning: rows.filter(r => r.status === 'warning').length,
critical: rows.filter(r => r.status === 'critical').length,
behind: rows.filter(r => r.behind).length,
customers,
licences: Object.fromEntries(licences.map(l => [l.status, l._count._all])),
openAlerts,
},
installs: rows,
});
}));
// ─── Customers ────────────────────────────────────────────────────────────────
router.get('/customers', wrap(async (req, res) => {
const customers = await prisma.customer.findMany({
orderBy: { name: 'asc' },
include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } },
});
res.json(customers);
}));
function customerData(body, { partial = false } = {}) {
const data = {};
for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.');
return data;
}
router.post('/customers', wrap(async (req, res) => {
const customer = await prisma.customer.create({ data: customerData(req.body) });
await audit(req, 'customer_created', customer.id, { name: customer.name });
res.status(201).json(customer);
}));
router.get('/customers/:id', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({
where: { id: req.params.id },
include: { licences: { orderBy: { createdAt: 'desc' }, include: { install: { select: { id: true, name: true, url: true, lastHeartbeatAt: true } } } }, installs: { orderBy: { registeredAt: 'desc' } } },
});
if (!customer) throw bad('Customer not found', 404);
res.json(customer);
}));
router.put('/customers/:id', wrap(async (req, res) => {
const customer = await prisma.customer.update({ where: { id: req.params.id }, data: customerData(req.body, { partial: true }) }).catch(() => { throw bad('Customer not found', 404); });
await audit(req, 'customer_updated', customer.id, { name: customer.name });
res.json(customer);
}));
// ─── Licences ─────────────────────────────────────────────────────────────────
function licenceData(body, { partial = false } = {}) {
const data = {};
if (body?.plan !== undefined) data.plan = text(body.plan, 50) || 'standard';
if (body?.expiresAt !== undefined) data.expiresAt = dateOrNull(body.expiresAt);
if (body?.graceDays !== undefined) {
const n = parseInt(body.graceDays, 10);
if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.');
data.graceDays = n;
}
if (body?.aiMonthlyCapCents !== undefined) {
const n = parseInt(body.aiMonthlyCapCents, 10);
if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.');
data.aiMonthlyCapCents = n;
}
if (body?.aiMarkupPercent !== undefined) {
if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null;
else {
const n = parseInt(body.aiMarkupPercent, 10);
if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.');
data.aiMarkupPercent = n;
}
}
if (body?.status !== undefined) {
if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.');
data.status = body.status;
}
if (body?.notes !== undefined) data.notes = text(body.notes, 5000);
if (!partial && data.status === undefined) data.status = 'active';
return data;
}
// "Generate": a new licence with a fresh key for a customer, for one product (Events unless
// another is given). A customer has one open licence per product; its Accounts licence (free)
// is created with its first other product.
router.post('/customers/:id/licences', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({ where: { id: req.params.id } });
if (!customer) throw bad('Customer not found', 404);
const product = req.body?.product ?? 'events';
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
res.status(201).json({ ...licence, accountsLicence: accounts });
}));
router.put('/licences/:id', wrap(async (req, res) => {
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Licence not found', 404);
const data = licenceData(req.body, { partial: true });
await checkReopen(prisma, existing, data.status);
const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => {
if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' });
throw e;
});
await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt });
res.json(licence);
}));
// Free the licence from its install (e.g. the church moved to a new address): the old install's
// heartbeats are refused, and the licence can be registered again from the new site.
router.post('/licences/:id/release', wrap(async (req, res) => {
const licence = await prisma.licence.findUnique({ where: { id: req.params.id }, include: { install: true } });
if (!licence) throw bad('Licence not found', 404);
if (!licence.install) throw bad('This licence is not in use.');
await prisma.install.update({ where: { id: licence.install.id }, data: { licenceId: null, releasedAt: new Date() } });
await prisma.installEvent.create({ data: { installId: licence.install.id, type: 'released', level: 'info', message: 'Licence released from this install', resolvedAt: new Date() } });
await audit(req, 'licence_released', licence.id, { install: licence.install.url });
res.json({ message: 'Released.' });
}));
// ─── Installs ─────────────────────────────────────────────────────────────────
router.get('/installs', wrap(async (req, res) => {
const settings = await getSettings();
const installs = await prisma.install.findMany({ include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
res.json(installs.map(i => summary(i, settings)));
}));
router.get('/installs/:id', wrap(async (req, res) => {
const settings = await getSettings();
const install = await prisma.install.findUnique({
where: { id: req.params.id },
include: { licence: true, customer: true, events: { orderBy: { createdAt: 'desc' }, take: 100 } },
});
if (!install) throw bad('Install not found', 404);
const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const heartbeats = await prisma.heartbeat.findMany({
where: { installId: install.id, receivedAt: { gte: since } },
orderBy: { receivedAt: 'asc' },
select: { receivedAt: true, version: true, health: true, stats: true },
});
const { secret, ...safe } = install;
let licence = null;
if (install.licence) {
// What the install would be told right now, for checking.
licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) };
}
const [aiStatus, aiMonths, aiHelpers] = await Promise.all([ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id)]);
res.json({ ...safe, licence, summary: summary(install, settings), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers } });
}));
router.put('/installs/:id', wrap(async (req, res) => {
const install = await prisma.install.update({ where: { id: req.params.id }, data: { notes: text(req.body?.notes, 5000) } }).catch(() => { throw bad('Install not found', 404); });
await audit(req, 'install_notes_updated', install.id);
res.json({ id: install.id, notes: install.notes });
}));
// ─── Alerts and history ───────────────────────────────────────────────────────
router.get('/events', wrap(async (req, res) => {
const where = req.query.open === 'true' ? { resolvedAt: null, level: { not: 'info' } } : {};
const events = await prisma.installEvent.findMany({
where, orderBy: { createdAt: 'desc' }, take: 200,
include: { install: { select: { id: true, name: true, url: true } } },
});
res.json(events);
}));
router.get('/audit', wrap(async (req, res) => {
res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } }));
}));
// ─── Releases ─────────────────────────────────────────────────────────────────
// What's new in each Cross Events version. Installs on an older version see the notes; the highest
// version is the latest (latest_version), so adding one tells installs an update is out. With a git
// repository set (Releases page), releases come from its tags and WHATS-NEW.md only.
router.get('/releases', wrap(async (req, res) => {
const [releases, installs] = await Promise.all([
prisma.release.findMany(),
prisma.install.findMany({ where: { releasedAt: null }, select: { version: true } }),
]);
const onVersion = {};
for (const i of installs) if (i.version) onVersion[i.version] = (onVersion[i.version] || 0) + 1;
res.json(sortReleases(releases).map(r => ({ ...r, installs: onVersion[r.version] || 0 })));
}));
function releaseData(body, { partial = false } = {}) {
const data = {};
if (body?.version !== undefined) {
const v = String(body.version || '').trim().replace(/^v/i, '');
if (!VERSION_RE.test(v)) throw bad('The version looks like 1.47.0.');
data.version = v;
} else if (!partial) throw bad('The version looks like 1.47.0.');
if (body?.notes !== undefined) data.notes = String(body.notes || '').trim().slice(0, 20000);
if (body?.urgent !== undefined) data.urgent = !!body.urgent;
if (body?.releasedAt !== undefined) data.releasedAt = dateOrNull(body.releasedAt) || new Date();
return data;
}
async function manualReleases() {
if (parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Releases come from git: tag the version and edit WHATS-NEW.md, then Sync now.');
}
router.post('/releases/sync', wrap(async (req, res) => {
if (!parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Set the git repository first.');
let result;
try {
result = await syncReleases();
} catch (e) {
throw bad(e.message, 502);
}
await audit(req, 'releases_synced', null, result);
res.json(result);
}));
const releaseError = e => {
if (e.code === 'P2002') throw bad('There is already a release with that version.', 409);
if (e.code === 'P2025') throw bad('Release not found', 404);
throw e;
};
router.post('/releases', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_added', release.id, { version: release.version, urgent: release.urgent });
res.status(201).json({ release, latestVersion: latest || null });
}));
router.put('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const data = releaseData(req.body, { partial: true });
const release = await prisma.release.update({ where: { id: req.params.id }, data }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_updated', release.id, { version: release.version, changed: Object.keys(data) });
res.json({ release, latestVersion: latest || null });
}));
router.delete('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_deleted', release.id, { version: release.version });
res.json({ latestVersion: latest || null });
}));
// ─── Notices ──────────────────────────────────────────────────────────────────
// Messages to churches: a banner on their site (site admins and supervisors) and/or one email.
router.get('/notices', wrap(async (req, res) => {
res.json(await prisma.notice.findMany({ orderBy: { createdAt: 'desc' }, take: 200 }));
}));
const NOTICE_LEVELS = ['info', 'maintenance', 'warning'];
async function noticeData(body, { partial = false } = {}) {
const data = {};
if (body?.title !== undefined) data.title = text(body.title, 120);
if (body?.message !== undefined) data.message = text(body.message, 2000);
if ((!partial || 'title' in data) && !data.title) throw bad('Give the notice a title.');
if ((!partial || 'message' in data) && !data.message) throw bad('Write the message.');
if (body?.level !== undefined) {
if (!NOTICE_LEVELS.includes(body.level)) throw bad('Level must be info, maintenance or warning.');
data.level = body.level;
}
if (body?.allInstalls !== undefined) data.allInstalls = !!body.allInstalls;
if (body?.installIds !== undefined) {
const ids = [...new Set((Array.isArray(body.installIds) ? body.installIds : []).map(String))];
const found = ids.length ? await prisma.install.count({ where: { id: { in: ids } } }) : 0;
if (found !== ids.length) throw bad('One of the chosen installs no longer exists.');
data.installIds = ids;
}
if (body?.showBanner !== undefined) data.showBanner = !!body.showBanner;
if (body?.startsAt !== undefined) data.startsAt = dateOrNull(body.startsAt);
if (body?.endsAt !== undefined) data.endsAt = dateOrNull(body.endsAt);
return data;
}
function checkNotice(notice) {
if (notice.allInstalls === false && !(notice.installIds || []).length) throw bad('Choose at least one install, or send it to every install.');
if (notice.startsAt && notice.endsAt && new Date(notice.endsAt) <= new Date(notice.startsAt)) throw bad('The end has to be after the start.');
}
// Create, and email it straight away when asked. Email only (no banner) is fine too.
router.post('/notices', wrap(async (req, res) => {
const data = await noticeData(req.body);
const sendEmail = !!req.body?.sendEmail;
if (data.showBanner === false && !sendEmail) throw bad('Show it as a banner, email it, or both.');
checkNotice(data);
let notice = await prisma.notice.create({ data });
if (sendEmail) {
const sent = await emailNotice(notice);
notice = await prisma.notice.update({ where: { id: notice.id }, data: { emailedAt: new Date(), emailedTo: sent } });
}
await audit(req, 'notice_created', notice.id, { title: notice.title, allInstalls: notice.allInstalls, installs: notice.installIds.length, banner: notice.showBanner, emailedTo: sendEmail ? notice.emailedTo : null });
res.status(201).json(notice);
}));
// Edit the banner (the email isn't sent again). "End now" is { endsAt: now }.
router.put('/notices/:id', wrap(async (req, res) => {
const existing = await prisma.notice.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Notice not found', 404);
const data = await noticeData(req.body, { partial: true });
checkNotice({ ...existing, ...data });
const notice = await prisma.notice.update({ where: { id: existing.id }, data });
await audit(req, 'notice_updated', notice.id, { title: notice.title, changed: Object.keys(data) });
res.json(notice);
}));
router.delete('/notices/:id', wrap(async (req, res) => {
const notice = await prisma.notice.delete({ where: { id: req.params.id } }).catch(() => { throw bad('Notice not found', 404); });
await audit(req, 'notice_deleted', notice.id, { title: notice.title });
res.json({ message: 'Deleted.' });
}));
// ─── Settings ─────────────────────────────────────────────────────────────────
router.get('/settings', wrap(async (req, res) => {
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
}));
const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from'];
function checkSmtp(values) {
if (values.smtp_port != null && values.smtp_port !== '' && !/^\d{1,5}$/.test(String(values.smtp_port))) throw bad('SMTP port is a number, usually 587 or 465.');
if (values.smtp_host && /[\s/]/.test(String(values.smtp_host).trim())) throw bad('SMTP server is a host name like mail.example.com, without https:// or a path.');
}
// What the audit log records: never the password, only that it changed.
function auditValues(values) {
const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_clear, ai_api_key, ai_api_key_clear, ...rest } = values;
if (smtp_pass_clear) rest.smtp_pass = '(removed)';
else if (smtp_pass) rest.smtp_pass = '(changed)';
if (release_repo_token_clear) rest.release_repo_token = '(removed)';
else if (release_repo_token) rest.release_repo_token = '(changed)';
if (ai_api_key_clear) rest.ai_api_key = '(removed)';
else if (ai_api_key) rest.ai_api_key = '(changed)';
return rest;
}
function checkAi(values) {
for (const [key, label] of [['ai_input_usd_per_mtok', 'Input price'], ['ai_output_usd_per_mtok', 'Output price'], ['ai_usd_zar', 'Exchange rate']]) {
if (values[key] != null && values[key] !== '' && !(parseFloat(values[key]) >= 0)) throw bad(`${label} is a number.`);
}
if (values.ai_markup_percent != null && values.ai_markup_percent !== '') {
const n = Number(values.ai_markup_percent);
if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The default markup is a whole number of % (0–500).');
}
if (values.ai_model != null && !/^[a-z0-9][a-z0-9.-]{2,60}$/.test(String(values.ai_model).trim())) throw bad('The model looks like claude-haiku-5-5.');
}
router.put('/settings', wrap(async (req, res) => {
// The latest version follows the Releases page; the sync writes its own status.
// eslint-disable-next-line no-unused-vars
const { latest_version, release_synced_at, release_sync_error, ...values } = req.body?.settings || {};
if (values.release_repo_url && !parseRepoUrl(values.release_repo_url)) throw bad('The repository address looks like https://git.example.com/owner/repo.');
if (values.release_notes_path != null && !String(values.release_notes_path).trim()) values.release_notes_path = 'WHATS-NEW.md';
checkSmtp(values);
checkAi(values);
if (values.ai_model != null) values.ai_model = String(values.ai_model).trim();
const settings = await setSettings(values);
await audit(req, 'settings_updated', null, auditValues(values));
res.json({ settings, smtp: await smtpConfigured() });
}));
// Tries the SMTP settings in the form (unsaved is fine): logs in and sends a test email.
router.post('/settings/smtp-test', smtpTestLimiter, wrap(async (req, res) => {
const values = Object.fromEntries(SMTP_FIELDS.filter(k => req.body?.settings?.[k] != null).map(k => [k, req.body.settings[k]]));
checkSmtp(values);
const to = text(req.body?.to, 200) || (await getSettings()).alert_email || req.admin.email;
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) throw bad('Send the test to a valid email address.');
try {
await testSmtp(values, to);
} catch (e) {
await audit(req, 'smtp_test_failed', null, { to, error: String(e.message).slice(0, 300) });
throw bad(`The test failed: ${e.message}`);
}
await audit(req, 'smtp_test_sent', null, { to });
res.json({ to });
}));
// ─── AI ───────────────────────────────────────────────────────────────────────
// A tiny call with the saved key and model, to check they work. Not metered to any install.
router.post('/settings/ai-test', smtpTestLimiter, wrap(async (req, res) => {
try {
const result = await ai.testCall(await getSettings());
await audit(req, 'ai_test_ok', null, { model: result.model });
res.json(result);
} catch (e) {
await audit(req, 'ai_test_failed', null, { error: String(e.message).slice(0, 300) });
throw bad(e.message, e.status || 502);
}
}));
// Every install's AI use in a month (YYYY-MM, default this month): real cost, charged, profit.
router.get('/ai-usage', wrap(async (req, res) => {
const month = /^\d{4}-\d{2}$/.test(String(req.query.month || '')) ? String(req.query.month) : ai.monthOf();
const installs = await ai.usageForMonth(month);
const sum = key => Math.round(installs.reduce((n, i) => n + i[key], 0) * 100) / 100;
res.json({ month, installs, totals: { calls: installs.reduce((n, i) => n + i.calls, 0), realCents: sum('realCents'), chargedCents: sum('chargedCents'), profitCents: sum('profitCents') } });
}));
module.exports = router;
module.exports.summary = summary;