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,31 @@
|
||||
# ─── Hope Events Hub — backend ────────────────────────────────────────────────
|
||||
PORT=5200
|
||||
DATABASE_URL=postgresql://postgres:password@localhost:5432/events_hub
|
||||
# Where the Hub's dashboard runs (CORS, links in alert emails)
|
||||
FRONTEND_URL=http://localhost:3200
|
||||
|
||||
# Signs admin login sessions. Long random string.
|
||||
JWT_SECRET=change-me
|
||||
# Encrypts install secrets and two-factor secrets. 32+ random characters; never change it
|
||||
# once installs are registered (their secrets couldn't be read any more).
|
||||
HUB_ENCRYPTION_KEY=change-me-to-32-or-more-random-characters
|
||||
|
||||
# Licence signing key (Ed25519, PEM). Create with `npm run generate-keys`. Keep the private
|
||||
# key only on the Hub server and back it up: losing it means every install needs a new
|
||||
# release with the new public key. Either a file path or the PEM itself (\n for newlines).
|
||||
HUB_SIGNING_KEY_FILE=./keys/hub-signing-key.pem
|
||||
# HUB_SIGNING_KEY=
|
||||
|
||||
# Behind a reverse proxy (nginx), so rate limits see real client IPs
|
||||
TRUST_PROXY=1
|
||||
|
||||
# Alert emails (install offline, backups failing, disk low, licences expiring)
|
||||
SMTP_HOST=
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=hub@crosscode.co.za
|
||||
ALERT_EMAIL=
|
||||
|
||||
# Background checks (alerts, heartbeat roll-up). false to switch off.
|
||||
JOBS_ENABLED=true
|
||||
Generated
+7490
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "events-hub-backend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Hope Events Hub — API for managing Hope Events installs, licences and heartbeats",
|
||||
"main": "src/index.js",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js",
|
||||
"test": "jest",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"create-admin": "node scripts/create-admin.js",
|
||||
"generate-keys": "node scripts/generate-keys.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^8.6.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"nodemailer": "^10.0.16",
|
||||
"qrcode": "^1.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^30.4.2",
|
||||
"prisma": "^7.10.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Prisma CLI config (migrate, generate). Prisma 7 no longer reads the datasource URL
|
||||
// from schema.prisma or auto-loads .env, so both happen here.
|
||||
require('dotenv/config');
|
||||
const { defineConfig } = require('prisma/config');
|
||||
|
||||
module.exports = defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: {
|
||||
path: 'prisma/migrations',
|
||||
},
|
||||
datasource: {
|
||||
// process.env rather than env() so `prisma generate` works without a DATABASE_URL.
|
||||
url: process.env.DATABASE_URL,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "LicenceStatus" AS ENUM ('active', 'suspended', 'revoked');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "EventLevel" AS ENUM ('info', 'warning', 'critical');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AdminUser" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"password" TEXT NOT NULL,
|
||||
"totpSecret" TEXT,
|
||||
"totpEnabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"tokenVersion" INTEGER NOT NULL DEFAULT 0,
|
||||
"lastLoginAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AdminUser_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Customer" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"contactName" TEXT,
|
||||
"email" TEXT,
|
||||
"phone" TEXT,
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Customer_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Licence" (
|
||||
"id" TEXT NOT NULL,
|
||||
"customerId" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"plan" TEXT NOT NULL DEFAULT 'standard',
|
||||
"status" "LicenceStatus" NOT NULL DEFAULT 'active',
|
||||
"expiresAt" TIMESTAMP(3),
|
||||
"graceDays" INTEGER NOT NULL DEFAULT 14,
|
||||
"aiMonthlyCapCents" INTEGER NOT NULL DEFAULT 0,
|
||||
"notes" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Licence_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Install" (
|
||||
"id" TEXT NOT NULL,
|
||||
"customerId" TEXT NOT NULL,
|
||||
"licenceId" TEXT,
|
||||
"name" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"version" TEXT,
|
||||
"protocolVersion" INTEGER NOT NULL DEFAULT 1,
|
||||
"adminContact" JSONB,
|
||||
"server" JSONB,
|
||||
"timezone" TEXT,
|
||||
"features" JSONB,
|
||||
"lastHeartbeatAt" TIMESTAMP(3),
|
||||
"health" JSONB,
|
||||
"stats" JSONB,
|
||||
"notes" TEXT,
|
||||
"registeredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"releasedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "Install_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Heartbeat" (
|
||||
"id" TEXT NOT NULL,
|
||||
"installId" TEXT NOT NULL,
|
||||
"receivedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"version" TEXT,
|
||||
"health" JSONB,
|
||||
"stats" JSONB,
|
||||
|
||||
CONSTRAINT "Heartbeat_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "InstallEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"installId" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"level" "EventLevel" NOT NULL DEFAULT 'info',
|
||||
"message" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"resolvedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "InstallEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"action" TEXT NOT NULL,
|
||||
"target" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Setting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "Setting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AdminUser_email_key" ON "AdminUser"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Licence_key_key" ON "Licence"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Install_licenceId_key" ON "Install"("licenceId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Install_lastHeartbeatAt_idx" ON "Install"("lastHeartbeatAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Heartbeat_installId_receivedAt_idx" ON "Heartbeat"("installId", "receivedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "InstallEvent_installId_createdAt_idx" ON "InstallEvent"("installId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "InstallEvent_type_resolvedAt_idx" ON "InstallEvent"("type", "resolvedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Licence" ADD CONSTRAINT "Licence_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Install" ADD CONSTRAINT "Install_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Install" ADD CONSTRAINT "Install_licenceId_fkey" FOREIGN KEY ("licenceId") REFERENCES "Licence"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Heartbeat" ADD CONSTRAINT "Heartbeat_installId_fkey" FOREIGN KEY ("installId") REFERENCES "Install"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "InstallEvent" ADD CONSTRAINT "InstallEvent_installId_fkey" FOREIGN KEY ("installId") REFERENCES "Install"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "AdminUser"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,149 @@
|
||||
// Hope Events Hub — customers, licences, installs and their heartbeats.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
// Someone who logs in to the Hub (Joshua, later support staff). Two-factor (authenticator
|
||||
// app) is required: totpSecret is set up on first login.
|
||||
model AdminUser {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
name String
|
||||
password String
|
||||
// AES-GCM encrypted (utils/crypto.js); null until two-factor is set up.
|
||||
totpSecret String?
|
||||
totpEnabled Boolean @default(false)
|
||||
// Bumped to sign out everywhere.
|
||||
tokenVersion Int @default(0)
|
||||
lastLoginAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
auditLogs AuditLog[]
|
||||
}
|
||||
|
||||
model Customer {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
contactName String?
|
||||
email String?
|
||||
phone String?
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
licences Licence[]
|
||||
installs Install[]
|
||||
}
|
||||
|
||||
enum LicenceStatus {
|
||||
active
|
||||
suspended
|
||||
revoked
|
||||
}
|
||||
|
||||
model Licence {
|
||||
id String @id @default(uuid())
|
||||
customerId String
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
|
||||
// CEH-XXXX-XXXX-XXXX-XXXX, generated by the Hub.
|
||||
key String @unique
|
||||
plan String @default("standard")
|
||||
status LicenceStatus @default(active)
|
||||
// Null = no end date.
|
||||
expiresAt DateTime?
|
||||
graceDays Int @default(14)
|
||||
// Hope Events 2.0: monthly AI spend cap (in cents, rand). 0 = AI off.
|
||||
aiMonthlyCapCents Int @default(0)
|
||||
notes String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
// One licence = one install.
|
||||
install Install?
|
||||
}
|
||||
|
||||
model Install {
|
||||
id String @id @default(uuid())
|
||||
customerId String
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
|
||||
licenceId String? @unique
|
||||
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
|
||||
name String
|
||||
url String
|
||||
// The install's HMAC secret, AES-GCM encrypted: the Hub needs it to check signatures.
|
||||
secret String
|
||||
version String?
|
||||
protocolVersion Int @default(1)
|
||||
adminContact Json?
|
||||
server Json?
|
||||
timezone String?
|
||||
features Json?
|
||||
// From the latest heartbeat.
|
||||
lastHeartbeatAt DateTime?
|
||||
health Json?
|
||||
stats Json?
|
||||
notes String?
|
||||
registeredAt DateTime @default(now())
|
||||
// Set when Joshua releases the licence (e.g. the church moved domain): heartbeats are refused.
|
||||
releasedAt DateTime?
|
||||
heartbeats Heartbeat[]
|
||||
events InstallEvent[]
|
||||
|
||||
@@index([lastHeartbeatAt])
|
||||
}
|
||||
|
||||
// Every heartbeat for 30 days, then one per install per day.
|
||||
model Heartbeat {
|
||||
id String @id @default(uuid())
|
||||
installId String
|
||||
install Install @relation(fields: [installId], references: [id], onDelete: Cascade)
|
||||
receivedAt DateTime @default(now())
|
||||
version String?
|
||||
health Json?
|
||||
stats Json?
|
||||
|
||||
@@index([installId, receivedAt])
|
||||
}
|
||||
|
||||
enum EventLevel {
|
||||
info
|
||||
warning
|
||||
critical
|
||||
}
|
||||
|
||||
// Things that happened to an install: alerts (offline, backup failing, disk low, errors,
|
||||
// licence expiring), version changes, registration. An alert stays open (resolvedAt null)
|
||||
// until the condition clears, so it's emailed once.
|
||||
model InstallEvent {
|
||||
id String @id @default(uuid())
|
||||
installId String
|
||||
install Install @relation(fields: [installId], references: [id], onDelete: Cascade)
|
||||
type String
|
||||
level EventLevel @default(info)
|
||||
message String
|
||||
createdAt DateTime @default(now())
|
||||
resolvedAt DateTime?
|
||||
|
||||
@@index([installId, createdAt])
|
||||
@@index([type, resolvedAt])
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorId String?
|
||||
actor AdminUser? @relation(fields: [actorId], references: [id], onDelete: SetNull)
|
||||
action String
|
||||
target String?
|
||||
metadata Json?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model Setting {
|
||||
key String @id
|
||||
value String
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Create a Hub login (or reset its password and two-factor).
|
||||
*
|
||||
* npm run create-admin -- --email you@example.com --name "Your Name"
|
||||
*
|
||||
* Asks for the password on the terminal. Two-factor is set up at the first login.
|
||||
*/
|
||||
|
||||
require('dotenv').config();
|
||||
const readline = require('readline');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const prisma = require('../src/config/db');
|
||||
|
||||
function arg(name) {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > -1 ? process.argv[i + 1] : null;
|
||||
}
|
||||
|
||||
function ask(question) {
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
return new Promise(resolve => rl.question(question, answer => { rl.close(); resolve(answer); }));
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const email = String(arg('email') || '').trim().toLowerCase();
|
||||
const name = arg('name') || email;
|
||||
if (!email) throw new Error('Usage: npm run create-admin -- --email you@example.com --name "Your Name"');
|
||||
const password = process.env.HUB_ADMIN_PASSWORD || await ask('Password (12+ characters): ');
|
||||
if (String(password).length < 12) throw new Error('Use at least 12 characters.');
|
||||
const hash = await bcrypt.hash(password, 12);
|
||||
const admin = await prisma.adminUser.upsert({
|
||||
where: { email },
|
||||
update: { password: hash, name, totpEnabled: false, totpSecret: null, tokenVersion: { increment: 1 } },
|
||||
create: { email, name, password: hash },
|
||||
});
|
||||
console.log(`Saved ${admin.email}. Log in to the Hub to set up two-factor.`);
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e.message); process.exit(1); });
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Create the Hub's licence signing key pair (Ed25519).
|
||||
*
|
||||
* npm run generate-keys → keys/hub-signing-key.pem (refuses to overwrite)
|
||||
* npm run generate-keys -- --force → replace it (every install then needs the new public key!)
|
||||
*
|
||||
* The private key stays on the Hub server only — back it up somewhere safe. The public key it
|
||||
* prints goes into Hope Events (backend/src/hub/publicKey.js) so installs can check licences.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const dir = path.join(__dirname, '..', 'keys');
|
||||
const file = path.join(dir, 'hub-signing-key.pem');
|
||||
|
||||
if (fs.existsSync(file) && !process.argv.includes('--force')) {
|
||||
console.error(`${file} already exists. Use --force to replace it (installs would need the new public key).`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(file, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
|
||||
|
||||
console.log(`Private key written to ${file} — keep it secret and back it up.`);
|
||||
console.log('Set HUB_SIGNING_KEY_FILE to that path in .env.\n');
|
||||
console.log('Public key (for Hope Events, backend/src/hub/publicKey.js):\n');
|
||||
console.log(publicKey.export({ type: 'spki', format: 'pem' }));
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,135 @@
|
||||
jest.mock('../src/config/db', () => ({}));
|
||||
|
||||
const cryptoNode = require('crypto');
|
||||
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
|
||||
|
||||
const hubCrypto = require('../src/utils/crypto');
|
||||
const licenceToken = require('../src/utils/licenceToken');
|
||||
const { signature, checkSignature } = require('../src/utils/signing');
|
||||
const totp = require('../src/utils/totp');
|
||||
const { problems, compareVersions } = require('../src/utils/alerts');
|
||||
|
||||
describe('secrets at rest', () => {
|
||||
test('encrypt/decrypt round-trip, different every time', () => {
|
||||
const a = hubCrypto.encrypt('s3cret');
|
||||
expect(a).not.toBe(hubCrypto.encrypt('s3cret'));
|
||||
expect(hubCrypto.decrypt(a)).toBe('s3cret');
|
||||
});
|
||||
|
||||
test('tampering is detected', () => {
|
||||
const [v, iv, tag, data] = hubCrypto.encrypt('s3cret').split(':');
|
||||
const flipped = Buffer.from(data, 'base64url');
|
||||
flipped[0] ^= 1;
|
||||
expect(() => hubCrypto.decrypt([v, iv, tag, flipped.toString('base64url')].join(':'))).toThrow();
|
||||
});
|
||||
|
||||
test('licence keys look like CEH-XXXX-XXXX-XXXX-XXXX with no look-alike characters', () => {
|
||||
const key = hubCrypto.licenceKey();
|
||||
expect(key).toMatch(/^CEH(-[ACDEFGHJKMNPQRTUVWXY234679]{4}){4}$/);
|
||||
expect(hubCrypto.normaliseLicenceKey(' ceh-7k2m-9qxa-p4rt-wd8c ')).toBe('CEH-7K2M-9QXA-P4RT-WD8C');
|
||||
});
|
||||
});
|
||||
|
||||
describe('licence tokens', () => {
|
||||
const { privateKey, publicKey } = cryptoNode.generateKeyPairSync('ed25519');
|
||||
const licence = { id: 'lic_1', plan: 'standard', status: 'active', expiresAt: new Date('2027-10-31T00:00:00Z'), graceDays: 14, aiMonthlyCapCents: 5000 };
|
||||
const now = new Date('2026-10-24T08:00:00Z');
|
||||
|
||||
test('payload is valid for 30 days and carries the limits', () => {
|
||||
const p = licenceToken.buildPayload(licence, { id: 'inst_1' }, 'Hope Church', now);
|
||||
expect(p).toMatchObject({ v: 1, licenceId: 'lic_1', installId: 'inst_1', customer: 'Hope Church', status: 'active', graceDays: 14, limits: { aiMonthlyCapCents: 5000 } });
|
||||
expect(p.validUntil).toBe('2026-11-23T08:00:00.000Z');
|
||||
expect(p.licenceExpiresAt).toBe('2027-10-31T00:00:00.000Z');
|
||||
});
|
||||
|
||||
test('signed tokens verify, edited ones do not', () => {
|
||||
const token = licenceToken.sign({ status: 'active' }, privateKey);
|
||||
expect(token.startsWith('hel1.')).toBe(true);
|
||||
expect(licenceToken.verify(token, publicKey)).toEqual({ status: 'active' });
|
||||
|
||||
const [prefix, , sig] = token.split('.');
|
||||
const forged = `${prefix}.${Buffer.from(JSON.stringify({ status: 'active', plan: 'gold' })).toString('base64url')}.${sig}`;
|
||||
expect(licenceToken.verify(forged, publicKey)).toBeNull();
|
||||
expect(licenceToken.verify('nonsense', publicKey)).toBeNull();
|
||||
const other = cryptoNode.generateKeyPairSync('ed25519');
|
||||
expect(licenceToken.verify(token, other.publicKey)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('request signatures', () => {
|
||||
const secret = 'install-secret';
|
||||
const now = Date.parse('2026-10-24T08:00:00Z');
|
||||
const ts = '2026-10-24T08:00:30.000Z';
|
||||
const body = '{"protocolVersion":1}';
|
||||
|
||||
test('a correct signature passes', () => {
|
||||
expect(checkSignature({ secret, timestamp: ts, rawBody: body, given: signature(secret, ts, body), now })).toBeNull();
|
||||
});
|
||||
|
||||
test('a changed body, wrong secret or old timestamp fails', () => {
|
||||
expect(checkSignature({ secret, timestamp: ts, rawBody: body + ' ', given: signature(secret, ts, body), now })).toBe('BAD_SIGNATURE');
|
||||
expect(checkSignature({ secret: 'other', timestamp: ts, rawBody: body, given: signature(secret, ts, body), now })).toBe('BAD_SIGNATURE');
|
||||
const old = '2026-10-24T07:50:00.000Z';
|
||||
expect(checkSignature({ secret, timestamp: old, rawBody: body, given: signature(secret, old, body), now })).toBe('STALE_REQUEST');
|
||||
expect(checkSignature({ secret, timestamp: 'nope', rawBody: body, given: 'x', now })).toBe('STALE_REQUEST');
|
||||
});
|
||||
});
|
||||
|
||||
describe('two-factor codes', () => {
|
||||
// RFC 6238 test secret "12345678901234567890" (SHA-1): at T=59s the 8-digit code is 94287082.
|
||||
const secret = totp.base32Encode(Buffer.from('12345678901234567890'));
|
||||
|
||||
test('matches the RFC test vector', () => {
|
||||
expect(totp.codeAt(secret, 1)).toBe('287082');
|
||||
expect(totp.verifyCode(secret, '287082', 59 * 1000)).toBe(true);
|
||||
});
|
||||
|
||||
test('accepts one step of clock drift, not more', () => {
|
||||
expect(totp.verifyCode(secret, '287082', 89 * 1000)).toBe(true);
|
||||
expect(totp.verifyCode(secret, '287082', 150 * 1000)).toBe(false);
|
||||
expect(totp.verifyCode(secret, '12345', 59 * 1000)).toBe(false);
|
||||
});
|
||||
|
||||
test('base32 round-trips', () => {
|
||||
const buf = cryptoNode.randomBytes(20);
|
||||
expect(totp.base32Decode(totp.base32Encode(buf)).equals(buf)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('alerts', () => {
|
||||
const settings = { offline_minutes: '60', backup_max_age_hours: '48', disk_min_free_percent: '10', errors_per_day: '50', licence_expiry_warning_days: '14', latest_version: '1.42.0' };
|
||||
const now = new Date('2026-10-24T12:00:00Z');
|
||||
const healthy = {
|
||||
registeredAt: new Date('2026-01-01'),
|
||||
lastHeartbeatAt: new Date('2026-10-24T11:50:00Z'),
|
||||
version: '1.42.0',
|
||||
health: { db: true, lastBackupAt: '2026-10-24T02:00:00Z', disk: { freeBytes: 50, totalBytes: 100 }, errorsLast24h: 0, jobs: { failedLast24h: 0 }, pendingMigrations: 0 },
|
||||
licence: { status: 'active', expiresAt: new Date('2027-10-31'), graceDays: 14 },
|
||||
};
|
||||
|
||||
test('a healthy install has no problems', () => {
|
||||
expect(problems(healthy, settings, now)).toEqual([]);
|
||||
});
|
||||
|
||||
test('offline, stale backup, low disk, errors, expiring licence, behind', () => {
|
||||
const types = problems({
|
||||
...healthy,
|
||||
lastHeartbeatAt: new Date('2026-10-24T10:00:00Z'),
|
||||
version: '1.41.3',
|
||||
health: { ...healthy.health, lastBackupAt: '2026-10-21T02:00:00Z', disk: { freeBytes: 5, totalBytes: 100 }, errorsLast24h: 80 },
|
||||
licence: { status: 'active', expiresAt: new Date('2026-11-01'), graceDays: 14 },
|
||||
}, settings, now).map(p => p.type);
|
||||
expect(types).toEqual(['offline', 'backup_stale', 'disk_low', 'errors_high', 'licence_expiring', 'behind']);
|
||||
});
|
||||
|
||||
test('a never-seen install is offline an hour after registering, with no health alerts', () => {
|
||||
const types = problems({ registeredAt: new Date('2026-10-24T10:00:00Z'), lastHeartbeatAt: null, health: null, licence: null }, settings, now).map(p => p.type);
|
||||
expect(types).toEqual(['offline']);
|
||||
});
|
||||
|
||||
test('version comparison', () => {
|
||||
expect(compareVersions('1.40.2', '1.41.0')).toBeLessThan(0);
|
||||
expect(compareVersions('1.41.0', '1.41.0')).toBe(0);
|
||||
expect(compareVersions('2.0.0', '1.99.9')).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user