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,28 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
|
||||
const app = express();
|
||||
if (process.env.TRUST_PROXY) app.set('trust proxy', parseInt(process.env.TRUST_PROXY, 10) || 1);
|
||||
app.disable('x-powered-by');
|
||||
|
||||
// Installs call the Hub server-to-server; only the dashboard needs CORS.
|
||||
app.use(cors({ origin: (process.env.FRONTEND_URL || 'http://localhost:3200').replace(/\/$/, '') }));
|
||||
|
||||
// Keep the exact bytes: heartbeat signatures are over the raw body.
|
||||
app.use(express.json({ limit: '200kb', verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
|
||||
|
||||
app.get('/api/health', (req, res) => res.json({ ok: true }));
|
||||
app.use('/api', require('./routes/installApi'));
|
||||
app.use('/api/auth', require('./routes/auth'));
|
||||
app.use('/api/admin', require('./routes/admin'));
|
||||
|
||||
app.use((req, res) => res.status(404).json({ message: 'Not found', code: 'NOT_FOUND' }));
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, next) => {
|
||||
if (err.type === 'entity.parse.failed') return res.status(400).json({ message: 'Invalid JSON', code: 'BAD_JSON' });
|
||||
if (err.type === 'entity.too.large') return res.status(413).json({ message: 'Too large', code: 'TOO_LARGE' });
|
||||
console.error('[hub]', err);
|
||||
res.status(500).json({ message: 'Server error', code: 'SERVER_ERROR' });
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
@@ -0,0 +1,8 @@
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
const { PrismaPg } = require('@prisma/adapter-pg');
|
||||
|
||||
// Prisma 7 talks to Postgres through the node-postgres driver adapter.
|
||||
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 5000 });
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
module.exports = prisma;
|
||||
@@ -0,0 +1,32 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const required = ['DATABASE_URL', 'JWT_SECRET', 'HUB_ENCRYPTION_KEY'];
|
||||
const missing = required.filter(k => !process.env[k]);
|
||||
if (missing.length) {
|
||||
console.error(`[hub] Missing environment variables: ${missing.join(', ')} (see .env.example)`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = require('./app');
|
||||
const { keyPair } = require('./utils/licenceToken');
|
||||
const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
|
||||
|
||||
// Fail early if the licence signing key is missing or wrong.
|
||||
try {
|
||||
keyPair();
|
||||
} catch (e) {
|
||||
console.error(`[hub] ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const PORT = parseInt(process.env.PORT || '5200', 10);
|
||||
app.listen(PORT, () => console.log(`[hub] Listening on ${PORT}`));
|
||||
|
||||
// Background checks: alerts every 5 minutes, heartbeat roll-up once a day. The Hub runs as a
|
||||
// single process, so plain timers are enough.
|
||||
if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() !== 'false') {
|
||||
const every = (ms, name, fn) => setInterval(() => fn().catch(e => console.warn(`[hub] ${name} failed:`, e?.message || e)), ms);
|
||||
every(5 * 60 * 1000, 'alerts', () => runAlerts());
|
||||
every(24 * 60 * 60 * 1000, 'heartbeat roll-up', () => rollupHeartbeats());
|
||||
setTimeout(() => runAlerts().catch(() => {}), 30 * 1000);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const prisma = require('../config/db');
|
||||
|
||||
const SESSION_HOURS = 12;
|
||||
|
||||
function secret() {
|
||||
if (!process.env.JWT_SECRET) throw new Error('JWT_SECRET is not set');
|
||||
return process.env.JWT_SECRET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens carry a scope: 'session' (logged in), 'totp' (password checked, waiting for the
|
||||
* two-factor code) or 'setup' (password checked, two-factor not set up yet).
|
||||
*/
|
||||
function issue(admin, scope, expiresIn) {
|
||||
return jwt.sign({ sub: admin.id, v: admin.tokenVersion, scope }, secret(), { expiresIn, algorithm: 'HS256' });
|
||||
}
|
||||
|
||||
const sessionToken = admin => issue(admin, 'session', `${SESSION_HOURS}h`);
|
||||
const stepToken = (admin, scope) => issue(admin, scope, '10m');
|
||||
|
||||
/** The admin for a token of the given scope, or null. */
|
||||
async function adminFromToken(token, scope) {
|
||||
try {
|
||||
const decoded = jwt.verify(String(token || ''), secret(), { algorithms: ['HS256'] });
|
||||
if (decoded.scope !== scope) return null;
|
||||
const admin = await prisma.adminUser.findUnique({ where: { id: decoded.sub } });
|
||||
if (!admin || admin.tokenVersion !== decoded.v) return null;
|
||||
return admin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Requires a logged-in admin (Authorization: Bearer <session token>). */
|
||||
async function protect(req, res, next) {
|
||||
const header = req.headers.authorization || '';
|
||||
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
|
||||
const admin = await adminFromToken(token, 'session');
|
||||
if (!admin) return res.status(401).json({ message: 'Please log in again.', code: 'UNAUTHENTICATED' });
|
||||
req.admin = admin;
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { protect, sessionToken, stepToken, adminFromToken, SESSION_HOURS };
|
||||
@@ -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;
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Install alerts: which problems an install has right now (pure, testable), and the job
|
||||
* that opens an InstallEvent (and emails Joshua) when a problem starts, and resolves it when
|
||||
* it clears — so each problem is emailed once.
|
||||
*/
|
||||
|
||||
const prisma = require('../config/db');
|
||||
const { getSettings } = require('./settings');
|
||||
const { sendMail } = require('./mail');
|
||||
|
||||
const MIN = 60 * 1000;
|
||||
const HOUR = 60 * MIN;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
/** Compare "1.40.2" with "1.41.0": negative, 0 or positive. */
|
||||
function compareVersions(a, b) {
|
||||
const pa = String(a || '').split(/[.-]/).map(n => parseInt(n, 10) || 0);
|
||||
const pb = String(b || '').split(/[.-]/).map(n => parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problems an install has now: [{ type, level, message }]. `install` needs
|
||||
* lastHeartbeatAt, health, version, registeredAt, licence (status, expiresAt, graceDays).
|
||||
*/
|
||||
function problems(install, settings, now = new Date()) {
|
||||
const out = [];
|
||||
const s = {
|
||||
offlineMin: parseInt(settings.offline_minutes, 10) || 60,
|
||||
backupHours: parseInt(settings.backup_max_age_hours, 10) || 48,
|
||||
diskPercent: parseFloat(settings.disk_min_free_percent) || 10,
|
||||
errorsPerDay: parseInt(settings.errors_per_day, 10) || 50,
|
||||
expiryDays: parseInt(settings.licence_expiry_warning_days, 10) || 14,
|
||||
};
|
||||
const health = install.health || {};
|
||||
|
||||
const lastSeen = install.lastHeartbeatAt ? new Date(install.lastHeartbeatAt) : null;
|
||||
const since = lastSeen || new Date(install.registeredAt);
|
||||
if (now - since > s.offlineMin * MIN) {
|
||||
out.push({ type: 'offline', level: 'critical', message: lastSeen ? `No heartbeat since ${lastSeen.toISOString()}` : 'Never sent a heartbeat since registering' });
|
||||
}
|
||||
|
||||
// Health from the last heartbeat (skipped when there is none yet).
|
||||
if (lastSeen) {
|
||||
if (health.db === false) out.push({ type: 'database', level: 'critical', message: 'The install reports its database is not OK' });
|
||||
const backup = health.lastBackupAt ? new Date(health.lastBackupAt) : null;
|
||||
if (!backup || now - backup > s.backupHours * HOUR) {
|
||||
out.push({ type: 'backup_stale', level: 'warning', message: backup ? `Last backup ${backup.toISOString()}` : 'No backup reported' });
|
||||
}
|
||||
const disk = health.disk;
|
||||
if (disk && disk.totalBytes > 0 && (disk.freeBytes / disk.totalBytes) * 100 < s.diskPercent) {
|
||||
out.push({ type: 'disk_low', level: 'warning', message: `Disk ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free` });
|
||||
}
|
||||
if (Number.isFinite(health.errorsLast24h) && health.errorsLast24h > s.errorsPerDay) {
|
||||
out.push({ type: 'errors_high', level: 'warning', message: `${health.errorsLast24h} errors in the last 24 hours` });
|
||||
}
|
||||
if (Number.isFinite(health.jobs?.failedLast24h) && health.jobs.failedLast24h > 0) {
|
||||
out.push({ type: 'jobs_failing', level: 'warning', message: `${health.jobs.failedLast24h} background job run(s) failed in the last 24 hours` });
|
||||
}
|
||||
if (health.pendingMigrations > 0) {
|
||||
out.push({ type: 'pending_migrations', level: 'warning', message: `${health.pendingMigrations} database migration(s) not applied` });
|
||||
}
|
||||
}
|
||||
|
||||
const lic = install.licence;
|
||||
if (lic && lic.status === 'active' && lic.expiresAt) {
|
||||
const left = new Date(lic.expiresAt) - now;
|
||||
if (left <= 0) out.push({ type: 'licence_expired', level: 'critical', message: `Licence expired ${new Date(lic.expiresAt).toISOString().slice(0, 10)} (grace ${lic.graceDays} days)` });
|
||||
else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` });
|
||||
}
|
||||
|
||||
if (settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0) {
|
||||
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${settings.latest_version}` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Run the checks for every install: open new alerts (emailed unless info), resolve cleared ones. */
|
||||
async function runAlerts(now = new Date()) {
|
||||
const settings = await getSettings();
|
||||
const installs = await prisma.install.findMany({
|
||||
where: { releasedAt: null },
|
||||
include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } },
|
||||
});
|
||||
let opened = 0;
|
||||
let resolved = 0;
|
||||
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]));
|
||||
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 } });
|
||||
opened++;
|
||||
if (p.level !== 'info') newAlerts.push(`• ${install.customer?.name || install.name} (${install.url}): ${p.message}`);
|
||||
}
|
||||
const currentTypes = new Set(current.map(p => p.type));
|
||||
for (const [type, event] of openByType) {
|
||||
if (currentTypes.has(type)) continue;
|
||||
await prisma.installEvent.update({ where: { id: event.id }, data: { resolvedAt: now } });
|
||||
resolved++;
|
||||
}
|
||||
}
|
||||
if (newAlerts.length && settings.alert_email) {
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Hope Events Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
|
||||
text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`,
|
||||
}).catch(e => console.warn('[alerts] email failed:', e?.message));
|
||||
}
|
||||
return { installs: installs.length, opened, resolved };
|
||||
}
|
||||
|
||||
/** Keep every heartbeat for 30 days, then only the last one of each day per install. */
|
||||
async function rollupHeartbeats(now = new Date(), db = prisma) {
|
||||
const cutoff = new Date(now.getTime() - 30 * DAY);
|
||||
const res = await db.$executeRawUnsafe(`
|
||||
DELETE FROM "Heartbeat" h
|
||||
WHERE h."receivedAt" < $1
|
||||
AND h."id" NOT IN (
|
||||
SELECT DISTINCT ON ("installId", date_trunc('day', "receivedAt")) "id"
|
||||
FROM "Heartbeat" WHERE "receivedAt" < $1
|
||||
ORDER BY "installId", date_trunc('day', "receivedAt"), "receivedAt" DESC
|
||||
)`, cutoff);
|
||||
return { deleted: res };
|
||||
}
|
||||
|
||||
module.exports = { compareVersions, problems, runAlerts, rollupHeartbeats };
|
||||
@@ -0,0 +1,16 @@
|
||||
const prisma = require('../config/db');
|
||||
|
||||
function clientIp(req) {
|
||||
return req?.ip || req?.socket?.remoteAddress || null;
|
||||
}
|
||||
|
||||
/** Record an admin action. Never throws — logging must not break the action itself. */
|
||||
async function audit(req, action, target = null, metadata = null) {
|
||||
try {
|
||||
await prisma.auditLog.create({ data: { actorId: req?.admin?.id || null, action, target, metadata: metadata || undefined, ip: clientIp(req) } });
|
||||
} catch (e) {
|
||||
console.error('[audit] failed:', e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { audit, clientIp };
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Secrets at rest (install secrets, two-factor secrets) and random identifiers.
|
||||
*
|
||||
* Encryption is AES-256-GCM with a key derived from HUB_ENCRYPTION_KEY, stored as
|
||||
* "v1:<iv>:<tag>:<ciphertext>" (base64url). The key must not change once installs are
|
||||
* registered — their secrets couldn't be decrypted any more.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
let cachedKey = null;
|
||||
function key() {
|
||||
if (cachedKey) return cachedKey;
|
||||
const secret = process.env.HUB_ENCRYPTION_KEY || '';
|
||||
if (secret.length < 32) throw new Error('HUB_ENCRYPTION_KEY must be at least 32 characters');
|
||||
cachedKey = crypto.scryptSync(secret, 'events-hub-secrets-v1', 32);
|
||||
return cachedKey;
|
||||
}
|
||||
|
||||
function encrypt(plain) {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key(), iv);
|
||||
const data = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]);
|
||||
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join(':');
|
||||
}
|
||||
|
||||
function decrypt(stored) {
|
||||
const [version, iv, tag, data] = String(stored || '').split(':');
|
||||
if (version !== 'v1' || !iv || !tag || !data) throw new Error('Not an encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key(), Buffer.from(iv, 'base64url'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'base64url'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
|
||||
// No 0/O, 1/I/L, 5/S, 8/B — easy to read out over the phone.
|
||||
const KEY_ALPHABET = 'ACDEFGHJKMNPQRTUVWXY234679';
|
||||
|
||||
/** A licence key: CEH-XXXX-XXXX-XXXX-XXXX (16 characters from 26, ~75 bits of randomness). */
|
||||
function licenceKey() {
|
||||
const bytes = crypto.randomBytes(20);
|
||||
const chars = Array.from(bytes, b => KEY_ALPHABET[b % KEY_ALPHABET.length]).join('');
|
||||
return `CEH-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
|
||||
}
|
||||
|
||||
/** Tidy what someone typed: upper case, no spaces. */
|
||||
function normaliseLicenceKey(input) {
|
||||
return String(input || '').toUpperCase().replace(/\s+/g, '').trim();
|
||||
}
|
||||
|
||||
function randomSecret(bytes = 32) {
|
||||
return crypto.randomBytes(bytes).toString('base64url');
|
||||
}
|
||||
|
||||
module.exports = { encrypt, decrypt, licenceKey, normaliseLicenceKey, randomSecret, KEY_ALPHABET, _resetKeyForTests: () => { cachedKey = null; } };
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Licence tokens (docs/hub-protocol.md §4): `hel1.<payload>.<signature>`, where payload is
|
||||
* base64url JSON and signature is Ed25519 over "hel1.<payload>". The Hub signs with its
|
||||
* private key; installs verify offline with the public key.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PREFIX = 'hel1';
|
||||
const VALID_DAYS = 30;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
let cached = null;
|
||||
|
||||
/** The Hub's signing key pair, from HUB_SIGNING_KEY (PEM) or HUB_SIGNING_KEY_FILE. */
|
||||
function keyPair() {
|
||||
if (cached) return cached;
|
||||
let pem = (process.env.HUB_SIGNING_KEY || '').replace(/\\n/g, '\n').trim();
|
||||
if (!pem && process.env.HUB_SIGNING_KEY_FILE) {
|
||||
pem = fs.readFileSync(path.resolve(process.env.HUB_SIGNING_KEY_FILE), 'utf8');
|
||||
}
|
||||
if (!pem) throw new Error('No licence signing key: set HUB_SIGNING_KEY_FILE (run `npm run generate-keys`)');
|
||||
const privateKey = crypto.createPrivateKey(pem);
|
||||
if (privateKey.asymmetricKeyType !== 'ed25519') throw new Error('The licence signing key must be Ed25519');
|
||||
const publicKey = crypto.createPublicKey(privateKey);
|
||||
cached = { privateKey, publicKey, publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** The payload for an install's licence, as of `now`. */
|
||||
function buildPayload(licence, install, customerName, now = new Date()) {
|
||||
return {
|
||||
v: 1,
|
||||
licenceId: licence.id,
|
||||
installId: install.id,
|
||||
customer: customerName,
|
||||
plan: licence.plan,
|
||||
status: licence.status,
|
||||
licenceExpiresAt: licence.expiresAt ? new Date(licence.expiresAt).toISOString() : null,
|
||||
graceDays: licence.graceDays,
|
||||
issuedAt: now.toISOString(),
|
||||
validUntil: new Date(now.getTime() + VALID_DAYS * DAY).toISOString(),
|
||||
limits: { aiMonthlyCapCents: licence.aiMonthlyCapCents || 0 },
|
||||
};
|
||||
}
|
||||
|
||||
function sign(payload, privateKey = keyPair().privateKey) {
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
||||
const signed = `${PREFIX}.${body}`;
|
||||
const signature = crypto.sign(null, Buffer.from(signed), privateKey).toString('base64url');
|
||||
return `${signed}.${signature}`;
|
||||
}
|
||||
|
||||
/** The payload if the token is genuine, else null. (The install does the same check.) */
|
||||
function verify(token, publicKey = keyPair().publicKey) {
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3 || parts[0] !== PREFIX) return null;
|
||||
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), publicKey, Buffer.from(parts[2], 'base64url'));
|
||||
if (!ok) return null;
|
||||
try { return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); } catch { return null; }
|
||||
}
|
||||
|
||||
module.exports = { PREFIX, VALID_DAYS, keyPair, buildPayload, sign, verify, _resetForTests: () => { cached = null; } };
|
||||
@@ -0,0 +1,27 @@
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
let transporter = null;
|
||||
|
||||
function smtpConfigured() {
|
||||
return !!process.env.SMTP_HOST;
|
||||
}
|
||||
|
||||
/** Send an email; without SMTP it's logged instead (development). */
|
||||
async function sendMail({ to, subject, text }) {
|
||||
if (!to) return;
|
||||
if (!smtpConfigured()) {
|
||||
console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"\n${text}`);
|
||||
return;
|
||||
}
|
||||
if (!transporter) {
|
||||
transporter = nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port: parseInt(process.env.SMTP_PORT || '587', 10),
|
||||
secure: String(process.env.SMTP_PORT) === '465',
|
||||
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
|
||||
});
|
||||
}
|
||||
await transporter.sendMail({ from: process.env.SMTP_FROM || 'hub@localhost', to, subject, text });
|
||||
}
|
||||
|
||||
module.exports = { sendMail, smtpConfigured };
|
||||
@@ -0,0 +1,29 @@
|
||||
const prisma = require('../config/db');
|
||||
|
||||
// Hub settings Joshua edits on the Settings page, with their defaults.
|
||||
const DEFAULTS = {
|
||||
latest_version: '',
|
||||
alert_email: '',
|
||||
// Alert thresholds
|
||||
offline_minutes: '60',
|
||||
backup_max_age_hours: '48',
|
||||
disk_min_free_percent: '10',
|
||||
errors_per_day: '50',
|
||||
licence_expiry_warning_days: '14',
|
||||
};
|
||||
|
||||
async function getSettings() {
|
||||
const rows = await prisma.setting.findMany();
|
||||
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
|
||||
return { ...DEFAULTS, ...saved };
|
||||
}
|
||||
|
||||
async function setSettings(values) {
|
||||
const updates = Object.entries(values || {}).filter(([k]) => k in DEFAULTS);
|
||||
for (const [key, value] of updates) {
|
||||
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
|
||||
}
|
||||
return getSettings();
|
||||
}
|
||||
|
||||
module.exports = { DEFAULTS, getSettings, setSettings };
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Install → Hub request signing (docs/hub-protocol.md §3):
|
||||
* X-Hub-Signature = hex HMAC-SHA256(installSecret, timestamp + "." + rawBody).
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const MAX_SKEW_MS = 5 * 60 * 1000;
|
||||
|
||||
function signature(secret, timestamp, rawBody) {
|
||||
return crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a signed request. Returns null when it's fine, or the error code
|
||||
* (STALE_REQUEST | BAD_SIGNATURE).
|
||||
*/
|
||||
function checkSignature({ secret, timestamp, rawBody, given, now = Date.now() }) {
|
||||
const at = Date.parse(timestamp || '');
|
||||
if (!Number.isFinite(at) || Math.abs(now - at) > MAX_SKEW_MS) return 'STALE_REQUEST';
|
||||
const expected = signature(secret, timestamp, rawBody);
|
||||
const a = Buffer.from(String(given || ''), 'utf8');
|
||||
const b = Buffer.from(expected, 'utf8');
|
||||
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return 'BAD_SIGNATURE';
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = { MAX_SKEW_MS, signature, checkSignature };
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Two-factor codes from an authenticator app (RFC 6238 TOTP: SHA-1, 6 digits, 30 s), so
|
||||
* logging in to the Hub doesn't depend on email being set up.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const STEP = 30;
|
||||
|
||||
function base32Encode(buf) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let out = '';
|
||||
for (const byte of buf) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
out += BASE32[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
|
||||
return out;
|
||||
}
|
||||
|
||||
function base32Decode(str) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
const out = [];
|
||||
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
|
||||
const idx = BASE32.indexOf(ch);
|
||||
if (idx === -1) continue;
|
||||
value = (value << 5) | idx;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
out.push((value >>> (bits - 8)) & 255);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
function generateSecret() {
|
||||
return base32Encode(crypto.randomBytes(20));
|
||||
}
|
||||
|
||||
function codeAt(secret, counter) {
|
||||
const buf = Buffer.alloc(8);
|
||||
buf.writeBigUInt64BE(BigInt(counter));
|
||||
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
|
||||
const offset = hmac[hmac.length - 1] & 0xf;
|
||||
const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3];
|
||||
return String(num % 1_000_000).padStart(6, '0');
|
||||
}
|
||||
|
||||
/** True if `code` is right for now, or one 30-second step either side (clock drift). */
|
||||
function verifyCode(secret, code, now = Date.now()) {
|
||||
const clean = String(code || '').replace(/\D/g, '');
|
||||
if (clean.length !== 6) return false;
|
||||
const counter = Math.floor(now / 1000 / STEP);
|
||||
for (const c of [counter - 1, counter, counter + 1]) {
|
||||
const expected = codeAt(secret, c);
|
||||
if (crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(clean))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The otpauth:// link an authenticator app scans (as a QR code). */
|
||||
function otpauthUrl(secret, account, issuer = 'Hope Events Hub') {
|
||||
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||
}
|
||||
|
||||
module.exports = { generateSecret, verifyCode, otpauthUrl, codeAt, base32Encode, base32Decode, STEP };
|
||||
Reference in New Issue
Block a user