Hub v1: install API, licences, health dashboard, alerts
- Protocol 1 (docs/hub-protocol.md): public key, register, signed heartbeats - Ed25519 licence tokens (30-day validity, status, expiry, grace, limits) - Dashboard: installs, install detail, customers and licences, alerts, settings and audit log; two-factor login required - Alert checks every 5 minutes, emailed once; heartbeat roll-up after 30 days - Unit tests for encryption, tokens, signatures, TOTP and alert rules Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
This commit is contained in:
@@ -0,0 +1,238 @@
|
||||
/** The Hub dashboard's API (admin login required). */
|
||||
|
||||
const express = require('express');
|
||||
const prisma = require('../config/db');
|
||||
const { protect } = require('../middleware/auth');
|
||||
const { licenceKey } = require('../utils/crypto');
|
||||
const { audit } = require('../utils/audit');
|
||||
const { getSettings, setSettings } = require('../utils/settings');
|
||||
const { problems, compareVersions } = require('../utils/alerts');
|
||||
const licenceToken = require('../utils/licenceToken');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(protect);
|
||||
|
||||
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 ? 'Something went wrong.' : e.message });
|
||||
});
|
||||
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,
|
||||
name: install.name,
|
||||
url: install.url,
|
||||
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
|
||||
version: install.version,
|
||||
behind: !!(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, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: 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?.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.
|
||||
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);
|
||||
let licence;
|
||||
for (let attempt = 0; !licence && attempt < 5; attempt++) {
|
||||
licence = await prisma.licence.create({ data: { ...licenceData(req.body), customerId: customer.id, key: licenceKey() } }).catch(e => (e.code === 'P2002' ? null : Promise.reject(e)));
|
||||
}
|
||||
await audit(req, 'licence_generated', licence.id, { customer: customer.name, expiresAt: licence.expiresAt });
|
||||
res.status(201).json(licence);
|
||||
}));
|
||||
|
||||
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 });
|
||||
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
|
||||
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) };
|
||||
}
|
||||
res.json({ ...safe, licence, summary: summary(install, settings), heartbeats });
|
||||
}));
|
||||
|
||||
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 } } } }));
|
||||
}));
|
||||
|
||||
// ─── Settings ─────────────────────────────────────────────────────────────────
|
||||
|
||||
router.get('/settings', wrap(async (req, res) => {
|
||||
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: !!process.env.SMTP_HOST });
|
||||
}));
|
||||
|
||||
router.put('/settings', wrap(async (req, res) => {
|
||||
const values = req.body?.settings || {};
|
||||
if (values.latest_version && !/^\d+\.\d+\.\d+$/.test(String(values.latest_version))) throw bad('Latest version looks like 1.41.0.');
|
||||
const settings = await setSettings(values);
|
||||
await audit(req, 'settings_updated', null, values);
|
||||
res.json({ settings });
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
module.exports.summary = summary;
|
||||
@@ -0,0 +1,86 @@
|
||||
const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const QRCode = require('qrcode');
|
||||
const prisma = require('../config/db');
|
||||
const { encrypt, decrypt } = require('../utils/crypto');
|
||||
const totp = require('../utils/totp');
|
||||
const { audit } = require('../utils/audit');
|
||||
const { protect, sessionToken, stepToken, adminFromToken } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts — wait a few minutes.' } });
|
||||
|
||||
const publicAdmin = a => ({ id: a.id, email: a.email, name: a.name, totpEnabled: a.totpEnabled, lastLoginAt: a.lastLoginAt });
|
||||
|
||||
async function finishLogin(req, res, admin) {
|
||||
const updated = await prisma.adminUser.update({ where: { id: admin.id }, data: { lastLoginAt: new Date() } });
|
||||
req.admin = updated;
|
||||
await audit(req, 'login');
|
||||
res.json({ token: sessionToken(updated), admin: publicAdmin(updated) });
|
||||
}
|
||||
|
||||
// Step 1: email + password → a two-factor step (or two-factor set-up on first login).
|
||||
router.post('/login', limiter, async (req, res) => {
|
||||
const { email, password } = req.body || {};
|
||||
const admin = await prisma.adminUser.findUnique({ where: { email: String(email || '').trim().toLowerCase() } });
|
||||
if (!admin || !(await bcrypt.compare(String(password || ''), admin.password))) {
|
||||
return res.status(401).json({ message: 'Wrong email or password.' });
|
||||
}
|
||||
if (!admin.totpEnabled) return res.json({ setupRequired: true, setupToken: stepToken(admin, 'setup') });
|
||||
res.json({ twoFactorRequired: true, challengeToken: stepToken(admin, 'totp') });
|
||||
});
|
||||
|
||||
// Step 2: the authenticator code.
|
||||
router.post('/2fa', limiter, async (req, res) => {
|
||||
const admin = await adminFromToken(req.body?.challengeToken, 'totp');
|
||||
if (!admin) return res.status(401).json({ message: 'That took too long — log in again.' });
|
||||
if (!admin.totpSecret || !totp.verifyCode(decrypt(admin.totpSecret), req.body?.code)) {
|
||||
return res.status(401).json({ message: 'That code is not right. Check your authenticator app and try again.' });
|
||||
}
|
||||
await finishLogin(req, res, admin);
|
||||
});
|
||||
|
||||
// First login: make a secret and show it as a QR code to scan.
|
||||
router.post('/2fa/setup', limiter, async (req, res) => {
|
||||
const admin = await adminFromToken(req.body?.setupToken, 'setup');
|
||||
// Only while two-factor is still off: a set-up token can't replace a working secret.
|
||||
if (!admin || admin.totpEnabled) return res.status(401).json({ message: 'That took too long — log in again.' });
|
||||
const secret = totp.generateSecret();
|
||||
await prisma.adminUser.update({ where: { id: admin.id }, data: { totpSecret: encrypt(secret), totpEnabled: false } });
|
||||
const url = totp.otpauthUrl(secret, admin.email);
|
||||
res.json({ secret, otpauthUrl: url, qrDataUrl: await QRCode.toDataURL(url) });
|
||||
});
|
||||
|
||||
// ...then confirm with a code from the app, which turns two-factor on and logs in.
|
||||
router.post('/2fa/confirm', limiter, async (req, res) => {
|
||||
const admin = await adminFromToken(req.body?.setupToken, 'setup');
|
||||
if (!admin || admin.totpEnabled || !admin.totpSecret) return res.status(401).json({ message: 'That took too long — log in again.' });
|
||||
if (!totp.verifyCode(decrypt(admin.totpSecret), req.body?.code)) {
|
||||
return res.status(400).json({ message: 'That code is not right. Check the time on your phone and try again.' });
|
||||
}
|
||||
const enabled = await prisma.adminUser.update({ where: { id: admin.id }, data: { totpEnabled: true } });
|
||||
req.admin = enabled;
|
||||
await audit(req, 'two_factor_enabled');
|
||||
await finishLogin(req, res, enabled);
|
||||
});
|
||||
|
||||
router.get('/me', protect, (req, res) => res.json(publicAdmin(req.admin)));
|
||||
|
||||
// Sign out on every device (e.g. a lost laptop).
|
||||
router.post('/logout-everywhere', protect, async (req, res) => {
|
||||
await prisma.adminUser.update({ where: { id: req.admin.id }, data: { tokenVersion: { increment: 1 } } });
|
||||
await audit(req, 'logout_everywhere');
|
||||
res.json({ message: 'Signed out everywhere.' });
|
||||
});
|
||||
|
||||
router.post('/password', protect, limiter, async (req, res) => {
|
||||
const { currentPassword, newPassword } = req.body || {};
|
||||
if (!(await bcrypt.compare(String(currentPassword || ''), req.admin.password))) return res.status(400).json({ message: 'Your current password is not right.' });
|
||||
if (String(newPassword || '').length < 12) return res.status(400).json({ message: 'Use at least 12 characters.' });
|
||||
const updated = await prisma.adminUser.update({ where: { id: req.admin.id }, data: { password: await bcrypt.hash(newPassword, 12), tokenVersion: { increment: 1 } } });
|
||||
await audit({ ...req, admin: updated }, 'password_changed');
|
||||
res.json({ token: sessionToken(updated) });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat.
|
||||
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const prisma = require('../config/db');
|
||||
const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../utils/crypto');
|
||||
const licenceToken = require('../utils/licenceToken');
|
||||
const { checkSignature } = require('../utils/signing');
|
||||
const { getSettings } = require('../utils/settings');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
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 fail = (res, status, code, message) => res.status(status).json({ code, message });
|
||||
|
||||
function protocolOk(body) {
|
||||
const minSupported = Math.max(...PROTOCOL_VERSIONS) - 1;
|
||||
const v = body?.protocolVersion;
|
||||
return Number.isInteger(v) && v >= minSupported && v <= Math.max(...PROTOCOL_VERSIONS);
|
||||
}
|
||||
|
||||
// Only small, known pieces of what an install says about itself are kept.
|
||||
const str = (v, max = 200) => (v == null ? null : String(v).slice(0, max));
|
||||
function cleanUrl(url) {
|
||||
try {
|
||||
const u = new URL(String(url));
|
||||
if (!/^https?:$/.test(u.protocol)) return null;
|
||||
return `${u.protocol}//${u.host}${u.pathname.replace(/\/$/, '')}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function tokenFor(install) {
|
||||
const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null;
|
||||
if (!licence) return null;
|
||||
return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name));
|
||||
}
|
||||
|
||||
router.get('/public-key', (req, res) => {
|
||||
res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem });
|
||||
});
|
||||
|
||||
router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
try {
|
||||
const body = req.body || {};
|
||||
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
|
||||
const info = body.install || {};
|
||||
const url = cleanUrl(info.url);
|
||||
if (!url) return fail(res, 400, 'BAD_URL', 'The install needs its public web address (https://…).');
|
||||
|
||||
const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } });
|
||||
if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.');
|
||||
if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.');
|
||||
if (licence.install && licence.install.url !== url) {
|
||||
return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.');
|
||||
}
|
||||
|
||||
const secret = randomSecret();
|
||||
const data = {
|
||||
name: str(info.name) || licence.customer.name,
|
||||
url,
|
||||
secret: encrypt(secret),
|
||||
version: str(info.version, 40),
|
||||
protocolVersion: body.protocolVersion,
|
||||
adminContact: info.adminContact ? { name: str(info.adminContact.name), email: str(info.adminContact.email) } : undefined,
|
||||
server: info.server ? { node: str(info.server.node, 40), postgres: str(info.server.postgres, 40), os: str(info.server.os, 80) } : undefined,
|
||||
timezone: str(info.timezone, 60),
|
||||
features: info.features && typeof info.features === 'object' ? info.features : undefined,
|
||||
releasedAt: null,
|
||||
};
|
||||
// Same licence, same site → re-register (new secret, same id).
|
||||
const install = licence.install
|
||||
? await prisma.install.update({ where: { id: licence.install.id }, data })
|
||||
: await prisma.install.create({ data: { ...data, customerId: licence.customerId, licenceId: licence.id } });
|
||||
await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } });
|
||||
|
||||
const settings = await getSettings();
|
||||
res.status(201).json({
|
||||
installId: install.id,
|
||||
installSecret: secret,
|
||||
licence: await tokenFor(install),
|
||||
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
|
||||
latestVersion: settings.latest_version || null,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[register]', e);
|
||||
fail(res, 500, 'SERVER_ERROR', 'The Hub could not register this install. Try again later.');
|
||||
}
|
||||
});
|
||||
|
||||
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 now = new Date();
|
||||
const version = str(body.version, 40);
|
||||
const health = body.health && typeof body.health === 'object' ? body.health : null;
|
||||
const stats = body.stats && typeof body.stats === 'object' ? body.stats : null;
|
||||
await prisma.$transaction([
|
||||
prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }),
|
||||
prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }),
|
||||
]);
|
||||
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 } });
|
||||
}
|
||||
|
||||
const settings = await getSettings();
|
||||
res.json({ licence: await tokenFor(install), latestVersion: settings.latest_version || null, serverTime: now.toISOString() });
|
||||
} catch (e) {
|
||||
console.error('[heartbeat]', e);
|
||||
fail(res, 500, 'SERVER_ERROR', 'The Hub could not record this heartbeat.');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;
|
||||
Reference in New Issue
Block a user