Update requests from installs (1.1.0)
POST /api/installs/update-request, signed like the heartbeat: opens an update_requested alert and emails the alert address once; the next heartbeat on a newer version resolves it. Shares the signature check with the heartbeat and syncs docs/hub-protocol.md with the install's copy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat.
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request.
|
||||
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
|
||||
*/
|
||||
|
||||
@@ -10,6 +10,8 @@ const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../util
|
||||
const licenceToken = require('../utils/licenceToken');
|
||||
const { checkSignature } = require('../utils/signing');
|
||||
const { getSettings } = require('../utils/settings');
|
||||
const { compareVersions } = require('../utils/alerts');
|
||||
const { sendMail } = require('../utils/mail');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -17,6 +19,7 @@ const PROTOCOL_VERSIONS = [1];
|
||||
const HEARTBEAT_MINUTES = 15;
|
||||
const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } });
|
||||
const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
|
||||
const updateRequestLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
|
||||
|
||||
const fail = (res, status, code, message) => res.status(status).json({ code, message });
|
||||
|
||||
@@ -44,6 +47,28 @@ async function tokenFor(install) {
|
||||
return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* The install a signed request comes from (§3), or null once the error has been sent:
|
||||
* unknown/released install, stale timestamp, bad signature or unsupported protocol.
|
||||
*/
|
||||
async function signedInstall(req, res) {
|
||||
const installId = String(req.headers['x-hub-install'] || '');
|
||||
const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null;
|
||||
if (!install || install.releasedAt) { fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.'); return null; }
|
||||
|
||||
const problem = checkSignature({
|
||||
secret: decrypt(install.secret),
|
||||
timestamp: String(req.headers['x-hub-timestamp'] || ''),
|
||||
rawBody: req.rawBody || '',
|
||||
given: String(req.headers['x-hub-signature'] || ''),
|
||||
});
|
||||
if (problem === 'STALE_REQUEST') { fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock."); return null; }
|
||||
if (problem) { fail(res, 401, problem, 'The request signature is not valid.'); return null; }
|
||||
|
||||
if (!protocolOk(req.body)) { fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${req.body?.protocolVersion} is not supported.`); return null; }
|
||||
return install;
|
||||
}
|
||||
|
||||
router.get('/public-key', (req, res) => {
|
||||
res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem });
|
||||
});
|
||||
@@ -98,21 +123,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
|
||||
router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
try {
|
||||
const installId = String(req.headers['x-hub-install'] || '');
|
||||
const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null;
|
||||
if (!install || install.releasedAt) return fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.');
|
||||
|
||||
const problem = checkSignature({
|
||||
secret: decrypt(install.secret),
|
||||
timestamp: String(req.headers['x-hub-timestamp'] || ''),
|
||||
rawBody: req.rawBody || '',
|
||||
given: String(req.headers['x-hub-signature'] || ''),
|
||||
});
|
||||
if (problem === 'STALE_REQUEST') return fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock.");
|
||||
if (problem) return fail(res, 401, problem, 'The request signature is not valid.');
|
||||
|
||||
const body = req.body || {};
|
||||
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported.`);
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
const body = req.body;
|
||||
|
||||
const now = new Date();
|
||||
const version = str(body.version, 40);
|
||||
@@ -124,6 +137,10 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
]);
|
||||
if (version && install.version && version !== install.version) {
|
||||
await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } });
|
||||
// An update the church asked for is done once the install runs a newer version.
|
||||
if (compareVersions(version, install.version) > 0) {
|
||||
await prisma.installEvent.updateMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, data: { resolvedAt: now } });
|
||||
}
|
||||
}
|
||||
|
||||
const settings = await getSettings();
|
||||
@@ -134,5 +151,38 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// A site admin pressed "Request update": open an alert (emailed once) until the install reports a
|
||||
// newer version. Asking again while a request is open doesn't email again.
|
||||
router.post('/installs/update-request', updateRequestLimiter, async (req, res) => {
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
|
||||
const settings = await getSettings();
|
||||
const latest = settings.latest_version || null;
|
||||
const current = str(req.body.version, 40) || install.version;
|
||||
if (!latest || compareVersions(current, latest) >= 0) {
|
||||
return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.');
|
||||
}
|
||||
|
||||
const open = await prisma.installEvent.findFirst({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, orderBy: { createdAt: 'desc' } });
|
||||
if (open) return res.json({ requestedAt: open.createdAt.toISOString(), version: latest, alreadyRequested: true });
|
||||
|
||||
const event = await prisma.installEvent.create({ data: { installId: install.id, type: 'update_requested', level: 'warning', message: `Update requested: runs ${current}, latest is ${latest}` } });
|
||||
if (settings.alert_email) {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events Hub: update requested by ${customer?.name || install.name}`,
|
||||
text: `${customer?.name || install.name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`,
|
||||
}).catch(e => console.warn('[update-request] email failed:', e?.message));
|
||||
}
|
||||
res.status(201).json({ requestedAt: event.createdAt.toISOString(), version: latest, alreadyRequested: false });
|
||||
} catch (e) {
|
||||
console.error('[update-request]', e);
|
||||
fail(res, 500, 'SERVER_ERROR', 'The Hub could not record the update request. Try again later.');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;
|
||||
|
||||
@@ -88,7 +88,8 @@ async function runAlerts(now = new Date()) {
|
||||
const newAlerts = [];
|
||||
for (const install of installs) {
|
||||
const current = problems(install, settings, now);
|
||||
const openByType = new Map(install.events.filter(e => e.type !== 'registered' && e.type !== 'version').map(e => [e.type, e]));
|
||||
// Update requests are opened by the install and resolved by its heartbeat, not by these checks.
|
||||
const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested'].includes(e.type)).map(e => [e.type, e]));
|
||||
for (const p of current) {
|
||||
if (openByType.has(p.type)) continue;
|
||||
await prisma.installEvent.create({ data: { installId: install.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
|
||||
|
||||
Reference in New Issue
Block a user