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:
2026-10-26 12:12:51 +02:00
co-authored by Claude Opus 5.5
commit e72330893a
56 changed files with 16952 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
node_modules/
.env
.env.local
keys/
backend/keys/
.next/
frontend/.next/
frontend/next-env.d.ts
*.log
coverage/
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/events-hub.iml" filepath="$PROJECT_DIR$/.idea/events-hub.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+23
View File
@@ -0,0 +1,23 @@
# Changelog
All notable changes to the Hope Events Hub. Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/);
versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added
- **Hub v1** (`docs/hub-protocol.md`, protocol 1):
- Install API: public key, register (licence key → install id, secret and signed licence),
heartbeat (HMAC-signed, 5-minute clock window) returning a fresh licence token.
- Licence tokens signed with Ed25519, valid 30 days, carrying status, expiry, grace days and
limits (AI cap for Hope Events 2.0).
- Dashboard: installs with health, version (flagged when behind the latest release), licence and
last heartbeat; install detail with health, usage, licence, history and notes.
- Customers and licences: generate keys (`CEH-XXXX-XXXX-XXXX-XXXX`), set status (active / suspended /
revoked), expiry, grace and AI cap, release a licence from a site.
- Alerts every 5 minutes — offline, database, stale backup, low disk, errors, failing jobs, pending
migrations, licence expiring/expired, behind latest — emailed once when they start.
- Heartbeats kept 30 days, then one a day.
- Login with two-factor (authenticator app) required, sign out everywhere, password change,
audit log.
+62
View File
@@ -0,0 +1,62 @@
# Hope Events Hub
Joshua's central management app for every **Hope Events** install: customers, licences,
install health and usage, and alerts. Customers never log in here.
- `backend/` — Express + Prisma (Postgres) API, port 5200
- `frontend/` — Next.js dashboard, port 3200
- `docs/hub-protocol.md` — the contract with Hope Events installs (a copy lives in the
`hope-events` repo; change both together)
Installs only ever call the Hub (register, heartbeat); the Hub never reaches into an install
and holds no church data — just versions, health and aggregate counts.
## Run it locally
Needs Node 20+ and Postgres.
```bash
cd backend
cp .env.example .env # set DATABASE_URL, JWT_SECRET, HUB_ENCRYPTION_KEY
npm install
npx prisma migrate deploy && npx prisma generate
npm run generate-keys # licence signing key → keys/hub-signing-key.pem
npm run create-admin -- --email you@example.com --name "Your Name"
npm run dev # http://localhost:5200
cd ../frontend
cp .env.example .env.local # NEXT_PUBLIC_API_URL=http://localhost:5200
npm install
npm run dev # http://localhost:3200
```
The first login sets up two-factor with an authenticator app (required).
To try it with Hope Events locally, point the install at the Hub with `HUB_URL=http://localhost:5200`
and `HUB_PUBLIC_KEY` (the public key shown in Hub → Settings) in Hope Events' `backend/.env`.
## The licence signing key
Licences are tokens signed with an Ed25519 key. **The private key exists only on the Hub server**;
installs check licences with the public key, which is built into Hope Events
(`backend/src/hub/publicKey.js`).
- Create the production key once, on the Hub server: `npm run generate-keys`. Back up
`keys/hub-signing-key.pem` somewhere safe and offline.
- Put the public key it prints into Hope Events (`backend/src/hub/publicKey.js`) and release.
- Losing or replacing the key means every install needs a Hope Events update with the new
public key before it can trust new licences — so don't.
- `HUB_ENCRYPTION_KEY` encrypts install secrets: it must never change after installs register.
## Deploying
Same pattern as Hope Events: on the server (`events-hub.crosscode.co.za`), behind nginx with
HTTPS, two PM2 processes (`backend`: `npm start`; `frontend`: `npm run build && npm start`),
`TRUST_PROXY=1`, `FRONTEND_URL=https://events-hub.crosscode.co.za`, and the frontend's
`NEXT_PUBLIC_API_URL` set to the public API address (e.g. `https://events-hub.crosscode.co.za`
with nginx routing `/api` to port 5200). Back up the database daily, plus the signing key.
## Tests
`cd backend && npm test` — encryption, licence tokens, request signatures, two-factor codes
(RFC 6238 vector) and alert rules.
+31
View File
@@ -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
+7490
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -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"
}
}
+15
View File
@@ -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"
+149
View File
@@ -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
}
+38
View File
@@ -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); });
+30
View File
@@ -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' }));
+28
View File
@@ -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;
+8
View File
@@ -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;
+32
View File
@@ -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);
}
+45
View File
@@ -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 };
+238
View File
@@ -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;
+86
View File
@@ -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;
+138
View File
@@ -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;
+129
View File
@@ -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 };
+16
View File
@@ -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 };
+54
View File
@@ -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; } };
+65
View File
@@ -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; } };
+27
View File
@@ -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 };
+29
View File
@@ -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 };
+28
View File
@@ -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 };
+74
View File
@@ -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 };
+135
View File
@@ -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);
});
});
+160
View File
@@ -0,0 +1,160 @@
# Hub protocol (version 1)
The contract between a **Hope Events install** (the church's site) and the **Hope Events
Hub** (`events-hub.crosscode.co.za`). A copy of this file lives in both repositories
(`joshua/hope-events` → `docs/hub-protocol.md`, `joshua/events-hub` → `docs/hub-protocol.md`);
change both together.
Principles:
- **Install → Hub only.** The install always starts the conversation; the Hub never calls
into an install. Works behind firewalls, and the Hub has no access to church data.
- **No personal information** is ever sent — counts, versions and health only. Income is
sent as a range, never an amount.
- **A Hub outage never switches a church off.** Licences are signed tokens the install
verifies offline with the Hub's public key.
- Every request carries `protocolVersion`. The Hub accepts the current and the previous
version, so installs waiting to update keep working.
All bodies are JSON (`Content-Type: application/json`). Times are ISO 8601 UTC strings.
Errors are `{ "message": "...", "code": "..." }` with a 4xx/5xx status.
---
## 1. Public key
```
GET /api/public-key
→ 200 { "protocolVersions": [1], "keyId": "k1", "algorithm": "Ed25519", "publicKey": "-----BEGIN PUBLIC KEY-----\n…" }
```
Installs ship with the Hub's public key built in (and may refresh it from here). The private
key exists only on the Hub server.
## 2. Register an install
Sent once, at the end of `/setup` (licence step) or from Site settings → "Connect to Hub".
```
POST /api/installs/register
{
"protocolVersion": 1,
"licenceKey": "CEH-7K2M-9QXA-P4RT-WD8C",
"install": {
"name": "Hope Family Church",
"url": "https://events.hopefamily.co.za",
"adminContact": { "name": "Jane Admin", "email": "jane@hopefamily.co.za" },
"version": "1.41.0",
"timezone": "Africa/Johannesburg",
"server": { "node": "20.18.0", "postgres": "16.4", "os": "linux 6.8" },
"features": { "whatsapp": true, "paymentProviders": ["yoco", "payfast"], "campuses": false }
}
}
→ 201 {
"installId": "inst_…",
"installSecret": "…", // shown once; the install stores it encrypted
"licence": "<licence token>",
"heartbeatIntervalMinutes": 15,
"latestVersion": "1.41.0"
}
```
- `404 LICENCE_NOT_FOUND` — unknown key. `403 LICENCE_REVOKED` — revoked licences can't register.
- One licence = one install. Registering again **from the same URL** re-registers (new
secret, same `installId`). From a different URL → `409 LICENCE_IN_USE` until Joshua releases
the licence in the Hub (e.g. after a move to a new domain).
- The `adminContact` is the one piece of personal information: a work contact for the
church's admin, so Joshua can reach them. It is not used for anything else.
- Rate-limited per IP.
## 3. Heartbeat
Every `heartbeatIntervalMinutes` (15) from the install's job queue.
```
POST /api/installs/heartbeat
X-Hub-Install: inst_…
X-Hub-Timestamp: 2026-10-24T08:15:00.000Z
X-Hub-Signature: <hex HMAC-SHA256(installSecret, timestamp + "." + rawBody)>
{
"protocolVersion": 1,
"version": "1.41.0",
"health": {
"uptimeSeconds": 86400,
"db": true,
"jobs": { "mode": "queue", "failedLast24h": 0 },
"lastBackupAt": "2026-10-24T00:00:12.000Z", // null if none
"disk": { "freeBytes": 21474836480, "totalBytes": 53687091200 }, // null if unknown
"errorsLast24h": 0, // null if not tracked
"pendingMigrations": 0
},
"stats": {
"users": 412,
"events": { "active": 3, "upcoming": 5, "total": 61 },
"registrations": { "last30d": 88, "total": 2310 },
"tickets": { "last30d": 140, "total": 3901 },
"checkIns": { "last30d": 96 },
"messages": { "email30d": 610, "whatsapp30d": 233 },
"paymentProviders": ["yoco", "payfast"],
"campuses": false,
"income": { "last30d": "R5 001–R20 000", "allTime": "over R100 000" }
}
}
→ 200 { "licence": "<fresh licence token>", "latestVersion": "1.42.0", "serverTime": "…" }
```
- The signature covers the exact bytes sent. Requests more than **5 minutes** off the Hub's
clock are refused (`401 STALE_REQUEST`); a bad signature is `401 BAD_SIGNATURE`; an unknown or
released install is `404 INSTALL_NOT_FOUND` (the install should show "Reconnect to Hub").
- **Income bands** (worked out on the install; the amount never leaves it): `R0–R1 000`,
`R1 001–R5 000`, `R5 001–R20 000`, `R20 001–R50 000`, `R50 001–R100 000`, `over R100 000`.
- The Hub keeps every heartbeat for 30 days, then one per install per day.
## 4. Licence token
`hel1.<payload>.<signature>` — `payload` is base64url JSON, `signature` is the base64url
Ed25519 signature of the ASCII string `hel1.<payload>`.
```json
{
"v": 1,
"licenceId": "lic_…",
"installId": "inst_…",
"customer": "Hope Family Church",
"plan": "standard",
"status": "active", // active | suspended | revoked
"licenceExpiresAt": "2027-10-31T21:59:59.000Z", // null = no end date
"graceDays": 14,
"issuedAt": "2026-10-24T08:15:00.000Z",
"validUntil": "2026-11-23T08:15:00.000Z", // issuedAt + 30 days
"limits": { "aiMonthlyCapCents": 0 }
}
```
### What the install does with it
The install keeps the newest valid token (signature checks out, `installId` matches) and works
out its state:
| State | When | What happens |
|-------|------|--------------|
| **active** | `status` is active and now is before `min(licenceExpiresAt, validUntil)` | Everything works |
| **grace** | after that date, for up to `graceDays` | Everything works; **only site admins** see a banner "Licence needs renewing — X days left" |
| **suspended** | `status` is suspended, or grace has run out | Read-only: no new events, registrations or payments. Tickets still scan; admins can view and export all data; privacy requests still work |
| **revoked** | `status` is revoked | Same as suspended, with a permanent banner |
| **unlicensed** | never connected | Works; admins see "Connect to Hub" |
`validUntil` is refreshed by every heartbeat, so a Hub outage only matters after 30 days (then
grace starts). Blocking the Hub can't keep a suspended licence active for more than 30 days.
## 5. Versioning
- `protocolVersion` goes up only for changes an older install can't handle. Adding optional
fields to a heartbeat or a token doesn't need a new version — both sides ignore fields they
don't know.
- The Hub accepts protocol `N` and `N-1`; anything else is `400 UNSUPPORTED_PROTOCOL`.
## 6. Later (not in v1)
- **AI proxy** (Hope Events 2.0): `POST /api/ai/complete`, signed like the heartbeat; the Hub holds
the Claude API key, meters each call in rand and enforces `limits.aiMonthlyCapCents`.
+2
View File
@@ -0,0 +1,2 @@
# Where the Hub API runs
NEXT_PUBLIC_API_URL=http://localhost:5200
+16
View File
@@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
poweredByHeader: false,
};
export default nextConfig;
+6467
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "events-hub-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
"build": "next build",
"start": "next start -p 3200",
"lint": "eslint src"
},
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.21",
"eslint": "^9",
"eslint-config-next": "^15.5.24",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
"typescript": "^5"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+48
View File
@@ -0,0 +1,48 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { InstallEvent } from "@/lib/types";
import { Badge, Loading, PageTitle } from "@/components/ui";
/** Open alerts, and the history of everything that happened to installs. */
export default function AlertsPage() {
const [openOnly, setOpenOnly] = useState(true);
const [events, setEvents] = useState<InstallEvent[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setEvents(null);
api<InstallEvent[]>(`/api/admin/events${openOnly ? "?open=true" : ""}`).then(setEvents).catch(e => setError(errorText(e)));
}, [openOnly]);
return (
<>
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Alert email)." />
<div className="mb-4 flex gap-2">
<button className={openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(true)}>Open</button>
<button className={!openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(false)}>Everything</button>
</div>
{error && <p className="text-sm text-red-700">{error}</p>}
{!events ? <Loading /> : events.length === 0 ? <p className="text-sm text-slate-500">{openOnly ? "No open alerts. 🎉" : "Nothing yet."}</p> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">When</th><th className="p-3">Install</th><th className="p-3">What</th><th className="p-3">State</th></tr></thead>
<tbody>
{events.map(e => (
<tr key={e.id} className="border-t align-top">
<td className="p-3 whitespace-nowrap text-xs text-slate-500">{fmtDate(e.createdAt)}</td>
<td className="p-3">{e.install ? <Link href={`/installs/${e.install.id}`} className="text-indigo-700 hover:underline">{e.install.name}</Link> : "—"}</td>
<td className="p-3"><Badge value={e.level} /> <span className="ml-1">{e.message}</span></td>
<td className="p-3 text-xs text-slate-500">{e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
@@ -0,0 +1,170 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
const dateInput = (d: string | null) => (d ? d.slice(0, 10) : "");
/** One licence: its key, and the settings that go into the next token the install receives. */
function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({
status: licence.status,
expiresAt: dateInput(licence.expiresAt),
graceDays: String(licence.graceDays),
aiRand: String(licence.aiMonthlyCapCents / 100),
notes: licence.notes || "",
});
const [busy, setBusy] = useState(false);
const save = async () => {
if (form.status !== licence.status && form.status !== "active" && !confirm(`${form.status === "revoked" ? "Revoke" : "Suspend"} this licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`)) return;
setBusy(true);
try {
await api(`/api/admin/licences/${licence.id}`, {
method: "PUT",
body: {
status: form.status,
// End of the chosen day, South African time.
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
graceDays: form.graceDays,
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
notes: form.notes,
},
});
setMsg({ type: "ok", text: "Licence saved. The site picks it up with its next heartbeat (within 15 minutes)." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const release = async () => {
if (!confirm("Release this licence from its site? The site's heartbeats are refused from now on, and the key can be registered again from a new address.")) return;
try {
await api(`/api/admin/licences/${licence.id}/release`, { method: "POST" });
setMsg({ type: "ok", text: "Released." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<div className="card space-y-3">
<div className="flex flex-wrap items-center gap-2">
<KeyRound className="h-4 w-4 text-slate-400" />
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
<span className="ml-auto"><Badge value={licence.status} /></span>
</div>
<div className="text-sm text-slate-600">
{licence.install
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
: "Not used yet — enter this key in the church's Hope Events setup (or Site settings → Licence)."}
</div>
<div className="grid gap-3 sm:grid-cols-4">
<div>
<label className="label">Status</label>
<select className="input" value={form.status} onChange={e => setForm({ ...form, status: e.target.value as LicenceStatus })}>
<option value="active">Active</option>
<option value="suspended">Suspended</option>
<option value="revoked">Revoked</option>
</select>
</div>
<div>
<label className="label">Expires</label>
<input type="date" className="input" value={form.expiresAt} onChange={e => setForm({ ...form, expiresAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{form.expiresAt ? "" : "No end date"}</p>
</div>
<div>
<label className="label">Grace (days)</label>
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
</div>
<div>
<label className="label">AI cap (R / month)</label>
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">0 = off. Used from 2.0.</p>
</div>
</div>
<div>
<label className="label">Notes</label>
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="e.g. paid annually, invoice #123" />
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save licence"}</button>
{licence.install && <button className="btn-danger" onClick={release}>Release from site</button>}
<span className="self-center text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
</div>
</div>
);
}
export default function CustomerPage() {
const { id } = useParams<{ id: string }>();
const [c, setC] = useState<Customer | null>(null);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" });
const [newLicence, setNewLicence] = useState({ expiresAt: "", graceDays: "14" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
setC(x);
setForm({ name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "" });
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!c) return msg ? <Message msg={msg} /> : <Loading />;
const saveDetails = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api(`/api/admin/customers/${id}`, { method: "PUT", body: form });
setMsg({ type: "ok", text: "Saved." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const generate = async (e: React.FormEvent) => {
e.preventDefault();
try {
const l = await api<Licence>(`/api/admin/customers/${id}/licences`, {
method: "POST",
body: { expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
});
setMsg({ type: "ok", text: `Licence ${l.key} created. Send it to the church for their setup.` });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<Link href="/customers" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
<PageTitle title={c.name} subtitle={`Customer since ${fmtDate(c.createdAt, false)}`} />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-[1fr_2fr]">
<form onSubmit={saveDetails} className="card space-y-3 self-start">
<h2 className="font-semibold">Details</h2>
<div><label className="label">Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
<div><label className="label">Contact person</label><input className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
<button className="btn-secondary">Save details</button>
</form>
<div className="space-y-4">
<h2 className="font-semibold">Licences</h2>
{c.licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
</form>
</div>
</div>
</>
);
}
+61
View File
@@ -0,0 +1,61 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import type { Customer } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
export default function CustomersPage() {
const router = useRouter();
const [list, setList] = useState<Customer[] | null>(null);
const [adding, setAdding] = useState(false);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "" });
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(() => api<Customer[]>("/api/admin/customers").then(setList).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => { load(); }, [load]);
const add = async (e: React.FormEvent) => {
e.preventDefault();
try {
const c = await api<Customer>("/api/admin/customers", { method: "POST", body: form });
router.push(`/customers/${c.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<PageTitle title="Customers" subtitle="Churches and organisations with a licence." actions={!adding && <button className="btn-primary" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add customer</button>} />
{adding && (
<form onSubmit={add} className="card mb-6 grid gap-3 md:grid-cols-2">
<div className="md:col-span-2"><label className="label" htmlFor="name">Name</label><input id="name" className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Hope Family Church" /></div>
<div><label className="label" htmlFor="contact">Contact person</label><input id="contact" className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label" htmlFor="email">Email</label><input id="email" type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label" htmlFor="phone">Phone</label><input id="phone" className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div className="flex items-end gap-2"><button className="btn-primary">Save</button><button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button></div>
</form>
)}
<Message msg={msg} />
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No customers yet.</p> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Customer</th><th className="p-3">Licences</th><th className="p-3">Site</th></tr></thead>
<tbody>
{list.map(c => (
<tr key={c.id} className="border-t hover:bg-slate-50">
<td className="p-3"><Link href={`/customers/${c.id}`} className="font-medium text-indigo-700 hover:underline">{c.name}</Link><div className="text-xs text-slate-500">{[c.contactName, c.email].filter(Boolean).join(" · ")}</div></td>
<td className="p-3">{c.licences.length ? c.licences.map(l => <span key={l.id} className="mr-1"><Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs">{i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
@@ -0,0 +1,150 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate, rand } from "@/lib/format";
import type { Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
type Detail = {
id: string; name: string; url: string; version: string | null; protocolVersion: number; timezone: string | null; notes: string | null;
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
health: Health | null; stats: Stats | null;
customer: { id: string; name: string };
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
summary: InstallSummary;
events: InstallEvent[];
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
};
const Row = ({ k, v }: { k: string; v: React.ReactNode }) => (
<div className="flex justify-between gap-4 border-b border-slate-100 py-1.5 text-sm last:border-0"><span className="text-slate-500">{k}</span><span className="text-right">{v}</span></div>
);
/** One install: health, usage, licence, history. */
export default function InstallPage() {
const { id } = useParams<{ id: string }>();
const [d, setD] = useState<Detail | null>(null);
const [notes, setNotes] = useState("");
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(() => api<Detail>(`/api/admin/installs/${id}`).then(x => { setD(x); setNotes(x.notes || ""); }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!d) return msg ? <Message msg={msg} /> : <Loading />;
const h = d.health || {};
const s = d.stats || {};
const diskPct = h.disk && h.disk.totalBytes ? Math.round((h.disk.freeBytes / h.disk.totalBytes) * 100) : null;
// One point per day for the last 30 days: registrations in the last 30 days, as reported.
const daily = new Map<string, number>();
for (const b of d.heartbeats) daily.set(b.receivedAt.slice(0, 10), b.stats?.registrations?.last30d ?? 0);
const points = [...daily.entries()];
const max = Math.max(1, ...points.map(([, v]) => v));
const saveNotes = async () => {
try {
await api(`/api/admin/installs/${id}`, { method: "PUT", body: { notes } });
setMsg({ type: "ok", text: "Notes saved." });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
<PageTitle
title={d.customer.name}
subtitle={<a href={d.url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{d.url}</a>}
actions={<Badge value={d.summary.status} />}
/>
{d.releasedAt && <div className="mb-4"><Message msg={{ type: "err", text: `Licence released ${fmtDate(d.releasedAt)} — this install's heartbeats are refused.` }} /></div>}
{d.summary.problems.length > 0 && (
<div className="card mb-6 space-y-1">
{d.summary.problems.map(p => <div key={p.type} className="flex items-center gap-2 text-sm"><Badge value={p.level} /> {p.message}</div>)}
</div>
)}
<div className="grid gap-6 md:grid-cols-2">
<div className="card">
<h2 className="mb-2 font-semibold">Health</h2>
<Row k="Last heartbeat" v={`${ago(d.lastHeartbeatAt)} (${fmtDate(d.lastHeartbeatAt)})`} />
<Row k="Version" v={`${d.version || "—"}${d.summary.behind ? " (behind)" : ""}`} />
<Row k="Database" v={h.db === false ? "Not OK" : h.db ? "OK" : "—"} />
<Row k="Background jobs" v={h.jobs ? `${h.jobs.mode || "?"}, ${h.jobs.failedLast24h ?? 0} failed (24 h)` : "—"} />
<Row k="Last backup" v={h.lastBackupAt ? `${ago(h.lastBackupAt)}` : "none reported"} />
<Row k="Disk free" v={h.disk ? `${bytes(h.disk.freeBytes)} of ${bytes(h.disk.totalBytes)} (${diskPct}%)` : "—"} />
<Row k="Errors (24 h)" v={h.errorsLast24h ?? "—"} />
<Row k="Pending migrations" v={h.pendingMigrations ?? "—"} />
<Row k="Uptime" v={h.uptimeSeconds != null ? `${Math.round(h.uptimeSeconds / 3600)} h` : "—"} />
</div>
<div className="card">
<h2 className="mb-2 font-semibold">Usage</h2>
<Row k="Users" v={s.users ?? "—"} />
<Row k="Events (active / upcoming / total)" v={s.events ? `${s.events.active ?? 0} / ${s.events.upcoming ?? 0} / ${s.events.total ?? 0}` : "—"} />
<Row k="Registrations (30 days / total)" v={s.registrations ? `${s.registrations.last30d ?? 0} / ${s.registrations.total ?? 0}` : "—"} />
<Row k="Tickets (30 days / total)" v={s.tickets ? `${s.tickets.last30d ?? 0} / ${s.tickets.total ?? 0}` : "—"} />
<Row k="Check-ins (30 days)" v={s.checkIns?.last30d ?? "—"} />
<Row k="Messages (30 days)" v={s.messages ? `${s.messages.email30d ?? 0} email, ${s.messages.whatsapp30d ?? 0} WhatsApp` : "—"} />
<Row k="Income (30 days / all time)" v={s.income ? `${s.income.last30d || "—"} / ${s.income.allTime || "—"}` : "—"} />
<Row k="Payment providers" v={s.paymentProviders?.join(", ") || "—"} />
{points.length > 1 && (
<div className="mt-3">
<div className="mb-1 text-xs text-slate-500">Registrations in the last 30 days, per day reported</div>
<div className="flex h-16 items-end gap-0.5">
{points.map(([day, v]) => <div key={day} title={`${day}: ${v}`} className="flex-1 rounded-t bg-indigo-300" style={{ height: `${(v / max) * 100}%` }} />)}
</div>
</div>
)}
</div>
<div className="card">
<h2 className="mb-2 font-semibold">Licence</h2>
{d.licence ? (
<>
<Row k="Key" v={<code className="text-xs">{d.licence.key}</code>} />
<Row k="Status" v={<Badge value={d.licence.status} />} />
<Row k="Expires" v={d.licence.expiresAt ? fmtDate(d.licence.expiresAt, false) : "no end date"} />
<Row k="Grace" v={`${d.licence.graceDays} days`} />
<Row k="AI cap (2.0)" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
</>
) : <p className="text-sm text-slate-500">No licence (released).</p>}
</div>
<div className="card">
<h2 className="mb-2 font-semibold">About</h2>
<Row k="Admin contact" v={d.adminContact ? `${d.adminContact.name || ""} ${d.adminContact.email ? `<${d.adminContact.email}>` : ""}` : "—"} />
<Row k="Server" v={d.server ? `Node ${d.server.node || "?"}, Postgres ${d.server.postgres || "?"}, ${d.server.os || "?"}` : "—"} />
<Row k="Time zone" v={d.timezone || "—"} />
<Row k="Registered" v={fmtDate(d.registeredAt)} />
<Row k="Protocol" v={d.protocolVersion} />
<label className="label mt-3" htmlFor="notes">Notes</label>
<textarea id="notes" className="input" rows={3} value={notes} onChange={e => setNotes(e.target.value)} />
<button className="btn-secondary mt-2" onClick={saveNotes}>Save notes</button>
</div>
</div>
{msg && <div className="mt-4"><Message msg={msg} /></div>}
<div className="card mt-6">
<h2 className="mb-3 font-semibold">History</h2>
{d.events.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
<ul className="space-y-2 text-sm">
{d.events.map(e => (
<li key={e.id} className="flex flex-wrap items-center gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(e.createdAt)}</span>
<Badge value={e.level} />
<span>{e.message}</span>
{e.level !== "info" && <span className="text-xs text-slate-400">{e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</span>}
</li>
))}
</ul>
)}
</div>
</>
);
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
type Me = { id: string; name: string; email: string };
const NAV = [
{ href: "/", label: "Installs", icon: LayoutDashboard },
{ href: "/customers", label: "Customers", icon: Building2 },
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/settings", label: "Settings", icon: Settings },
];
/** Everything except /login: requires a session, with the side navigation. */
export default function HubLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const [me, setMe] = useState<Me | null>(null);
useEffect(() => {
if (!getToken()) { router.replace("/login"); return; }
api<Me>("/api/auth/me").then(setMe).catch(() => router.replace("/login"));
}, [router]);
if (!me) return <div className="flex min-h-screen items-center justify-center text-sm text-slate-400">Loading…</div>;
const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : pathname.startsWith(href));
return (
<div className="flex min-h-screen">
<aside className="hidden w-56 shrink-0 border-r border-slate-200 bg-white p-4 md:flex md:flex-col">
<div className="mb-6 px-2">
<div className="text-base font-semibold">Hope Events Hub</div>
<div className="text-xs text-slate-500">{me.name}</div>
</div>
<nav className="space-y-1">
{NAV.map(n => {
const Icon = n.icon;
return (
<Link key={n.href} href={n.href} className={`flex items-center gap-2 rounded-lg px-3 py-2 text-sm ${active(n.href) ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600 hover:bg-slate-50"}`}>
<Icon className="h-4 w-4" /> {n.label}
</Link>
);
})}
</nav>
<button onClick={() => { setToken(null); router.replace("/login"); }} className="mt-auto flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-slate-600 hover:bg-slate-50">
<LogOut className="h-4 w-4" /> Sign out
</button>
</aside>
<div className="flex-1 min-w-0">
<nav className="flex gap-1 overflow-x-auto border-b border-slate-200 bg-white px-3 py-2 md:hidden">
{NAV.map(n => (
<Link key={n.href} href={n.href} className={`whitespace-nowrap rounded-lg px-3 py-1.5 text-sm ${active(n.href) ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600"}`}>{n.label}</Link>
))}
</nav>
<main className="mx-auto max-w-6xl p-4 md:p-8">{children}</main>
</div>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { InstallSummary } from "@/lib/types";
import { Badge, Loading, PageTitle, Stat } from "@/components/ui";
type Dashboard = {
latestVersion: string | null;
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number> };
installs: InstallSummary[];
};
/** Every install at a glance: health, version, licence, last heartbeat. */
export default function OverviewPage() {
const [data, setData] = useState<Dashboard | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () => api<Dashboard>("/api/admin/dashboard").then(d => { setData(d); setError(null); }).catch(e => setError(errorText(e)));
load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, []);
if (error) return <p className="text-sm text-red-700">{error}</p>;
if (!data) return <Loading />;
const c = data.counts;
return (
<>
<PageTitle title="Installs" subtitle={data.latestVersion ? `Latest release: ${data.latestVersion}` : "Set the latest release in Settings to see who is behind."} />
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
<Stat label="Installs" value={c.installs} />
<Stat label="Healthy" value={c.healthy} tone="green" />
<Stat label="Warnings" value={c.warning} tone={c.warning ? "amber" : undefined} />
<Stat label="Critical" value={c.critical} tone={c.critical ? "red" : undefined} />
<Stat label="Behind latest" value={c.behind} tone={c.behind ? "amber" : undefined} />
</div>
{data.installs.length === 0 ? (
<div className="card text-sm text-slate-600">
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s Hope Events setup.
</div>
) : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500">
<tr><th className="p-3">Install</th><th className="p-3">Health</th><th className="p-3">Version</th><th className="p-3">Licence</th><th className="p-3">Last heartbeat</th></tr>
</thead>
<tbody>
{data.installs.map(i => (
<tr key={i.id} className="border-t align-top hover:bg-slate-50">
<td className="p-3">
<Link href={`/installs/${i.id}`} className="font-medium text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link>
<div className="text-xs text-slate-500">{i.url}</div>
</td>
<td className="p-3">
<Badge value={i.status} />
{i.problems.filter(p => p.level !== "info").map(p => <div key={p.type} className="mt-1 text-xs text-slate-600">{p.message}</div>)}
</td>
<td className="p-3 whitespace-nowrap">{i.version || "—"}{i.behind && <span className="ml-1 text-xs text-amber-700">(behind)</span>}</td>
<td className="p-3 whitespace-nowrap">
{i.licence ? <><Badge value={i.licence.status} />{i.licence.expiresAt && <div className="mt-1 text-xs text-slate-500">to {fmtDate(i.licence.expiresAt, false)}</div>}</> : <span className="text-xs text-slate-400">none</span>}
</td>
<td className="p-3 whitespace-nowrap" title={fmtDate(i.lastHeartbeatAt)}>{ago(i.lastHeartbeatAt)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
+117
View File
@@ -0,0 +1,117 @@
"use client";
import React, { useEffect, useState } from "react";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
type Settings = Record<string, string>;
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
type Msg = { type: "ok" | "err"; text: string } | null;
const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "latest_version", label: "Latest Hope Events release", hint: "e.g. 1.41.0 — installs on an older version show as behind, and see \"Update available\"." },
{ key: "alert_email", label: "Alert email", hint: "Where new alerts are sent.", type: "email" },
{ key: "offline_minutes", label: "Offline after (minutes without a heartbeat)", hint: "Default 60.", type: "number" },
{ key: "backup_max_age_hours", label: "Backup too old after (hours)", hint: "Default 48.", type: "number" },
{ key: "disk_min_free_percent", label: "Disk low below (% free)", hint: "Default 10.", type: "number" },
{ key: "errors_per_day", label: "Errors spiking above (per 24 h)", hint: "Default 50.", type: "number" },
{ key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" },
];
export default function SettingsPage() {
const [settings, setSettings] = useState<Settings | null>(null);
const [publicKey, setPublicKey] = useState("");
const [smtp, setSmtp] = useState(false);
const [audit, setAudit] = useState<AuditRow[]>([]);
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
const [msg, setMsg] = useState<Msg>(null);
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AuditRow[]>("/api/admin/audit").then(setAudit).catch(() => {});
}, []);
if (!settings) return msg ? <Message msg={msg} /> : <Loading />;
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings } });
setSettings(r.settings);
setMsg({ type: "ok", text: "Settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const changePassword = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ token: string }>("/api/auth/password", { method: "POST", body: pw });
setToken(r.token);
setPw({ currentPassword: "", newPassword: "" });
setMsg({ type: "ok", text: "Password changed. Other devices are signed out." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const signOutEverywhere = async () => {
if (!confirm("Sign out on every device, including this one?")) return;
await api("/api/auth/logout-everywhere", { method: "POST" }).catch(() => {});
setToken(null);
window.location.href = "/login";
};
return (
<>
<PageTitle title="Settings" />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-2">
<form onSubmit={save} className="card space-y-4">
<h2 className="font-semibold">Releases and alerts</h2>
{!smtp && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">Email isn&apos;t set up on this server (SMTP_* in .env), so alerts are only logged.</p>}
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
<input id={f.key} className="input" type={f.type || "text"} value={settings[f.key] ?? ""} onChange={e => setSettings({ ...settings, [f.key]: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{f.hint}</p>
</div>
))}
<button className="btn-primary">Save settings</button>
</form>
<div className="space-y-6">
<div className="card space-y-2">
<h2 className="font-semibold">Licence signing key</h2>
<p className="text-sm text-slate-600">Installs check licences with this public key (built into Hope Events: <code>backend/src/hub/publicKey.js</code>). The private key stays on this server only — keep a backup.</p>
<pre className="overflow-x-auto rounded-lg bg-slate-50 p-3 text-xs">{publicKey}</pre>
</div>
<form onSubmit={changePassword} className="card space-y-3">
<h2 className="font-semibold">Your login</h2>
<div><label className="label">Current password</label><input type="password" className="input" autoComplete="current-password" value={pw.currentPassword} onChange={e => setPw({ ...pw, currentPassword: e.target.value })} required /></div>
<div><label className="label">New password (12+ characters)</label><input type="password" className="input" autoComplete="new-password" minLength={12} value={pw.newPassword} onChange={e => setPw({ ...pw, newPassword: e.target.value })} required /></div>
<div className="flex flex-wrap gap-2">
<button className="btn-secondary">Change password</button>
<button type="button" className="btn-danger" onClick={signOutEverywhere}>Sign out everywhere</button>
</div>
</form>
</div>
</div>
<div className="card mt-6">
<h2 className="mb-3 font-semibold">Audit log</h2>
{audit.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
<ul className="space-y-1 text-sm">
{audit.map(a => (
<li key={a.id} className="flex flex-wrap gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(a.createdAt)}</span>
<span className="font-medium">{a.actor?.name || "—"}</span>
<span>{a.action.replace(/_/g, " ")}</span>
{a.metadata ? <span className="text-xs text-slate-400 break-all">{JSON.stringify(a.metadata)}</span> : null}
</li>
))}
</ul>
)}
</div>
</>
);
}
+17
View File
@@ -0,0 +1,17 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
@apply bg-slate-50 text-slate-900 antialiased;
}
@layer components {
.input { @apply w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500; }
.btn { @apply inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium disabled:opacity-50; }
.btn-primary { @apply btn bg-indigo-600 text-white hover:bg-indigo-700; }
.btn-secondary { @apply btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50; }
.btn-danger { @apply btn border border-red-300 bg-white text-red-700 hover:bg-red-50; }
.card { @apply rounded-xl border border-slate-200 bg-white p-5 shadow-sm; }
.label { @apply mb-1 block text-sm font-medium text-slate-700; }
}
+16
View File
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Hope Events Hub",
description: "Installs, licences and health for Hope Events",
robots: { index: false, follow: false },
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
+96
View File
@@ -0,0 +1,96 @@
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { api, errorText, setToken } from "@/lib/api";
type LoginResponse = { token?: string; twoFactorRequired?: boolean; challengeToken?: string; setupRequired?: boolean; setupToken?: string };
type SetupResponse = { secret: string; otpauthUrl: string; qrDataUrl: string };
/** Email + password, then the authenticator code — or, the first time, setting up the app. */
export default function LoginPage() {
const router = useRouter();
const [step, setStep] = useState<"password" | "code" | "setup">("password");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
const [stepToken, setStepToken] = useState("");
const [setup, setSetup] = useState<SetupResponse | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const run = async (fn: () => Promise<void>) => {
setBusy(true);
setError(null);
try { await fn(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); }
};
const done = (token: string) => { setToken(token); router.replace("/"); };
const submitPassword = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<LoginResponse>("/api/auth/login", { method: "POST", body: { email, password }, auth: false });
if (r.setupRequired && r.setupToken) {
setStepToken(r.setupToken);
setSetup(await api<SetupResponse>("/api/auth/2fa/setup", { method: "POST", body: { setupToken: r.setupToken }, auth: false }));
setStep("setup");
} else if (r.challengeToken) {
setStepToken(r.challengeToken);
setStep("code");
}
});
};
const submitCode = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const path = step === "setup" ? "/api/auth/2fa/confirm" : "/api/auth/2fa";
const body = step === "setup" ? { setupToken: stepToken, code } : { challengeToken: stepToken, code };
const r = await api<{ token: string }>(path, { method: "POST", body, auth: false });
done(r.token);
});
};
return (
<div className="flex min-h-screen items-center justify-center p-4">
<div className="card w-full max-w-sm">
<h1 className="text-xl font-semibold">Hope Events Hub</h1>
{step === "password" && (
<form onSubmit={submitPassword} className="mt-5 space-y-4">
<div>
<label className="label" htmlFor="email">Email</label>
<input id="email" className="input" type="email" autoComplete="username" value={email} onChange={e => setEmail(e.target.value)} required />
</div>
<div>
<label className="label" htmlFor="password">Password</label>
<input id="password" className="input" type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} required />
</div>
<button className="btn-primary w-full" disabled={busy}>{busy ? "Checking…" : "Continue"}</button>
</form>
)}
{step !== "password" && (
<form onSubmit={submitCode} className="mt-5 space-y-4">
{step === "setup" && setup && (
<div className="space-y-2 text-sm text-slate-600">
<p>Two-factor is required. Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password…), then enter the code it shows.</p>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={setup.qrDataUrl} alt="QR code for your authenticator app" className="mx-auto h-44 w-44" />
<p className="break-all text-xs text-slate-500">Or type this key: <code>{setup.secret}</code></p>
</div>
)}
{step === "code" && <p className="text-sm text-slate-600">Enter the 6-digit code from your authenticator app.</p>}
<div>
<label className="label" htmlFor="code">Code</label>
<input id="code" className="input tracking-widest" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={code} onChange={e => setCode(e.target.value.replace(/\D/g, ""))} required autoFocus />
</div>
<button className="btn-primary w-full" disabled={busy || code.length !== 6}>{busy ? "Checking…" : step === "setup" ? "Turn on and log in" : "Log in"}</button>
<button type="button" className="w-full text-sm text-slate-500 hover:underline" onClick={() => { setStep("password"); setCode(""); setError(null); }}>Start again</button>
</form>
)}
{error && <p className="mt-4 text-sm text-red-700">{error}</p>}
</div>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
import React from "react";
import type { LicenceStatus, Problem } from "@/lib/types";
const STATUS_TONE: Record<string, string> = {
ok: "bg-green-50 text-green-700 ring-green-200",
warning: "bg-amber-50 text-amber-800 ring-amber-200",
critical: "bg-red-50 text-red-700 ring-red-200",
info: "bg-slate-100 text-slate-600 ring-slate-200",
active: "bg-green-50 text-green-700 ring-green-200",
suspended: "bg-amber-50 text-amber-800 ring-amber-200",
revoked: "bg-red-50 text-red-700 ring-red-200",
};
const STATUS_LABEL: Record<string, string> = { ok: "Healthy", warning: "Warning", critical: "Critical", info: "Info" };
export function Badge({ value, label }: { value: Problem["level"] | "ok" | LicenceStatus; label?: string }) {
return (
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${STATUS_TONE[value] || STATUS_TONE.info}`}>
{label || STATUS_LABEL[value] || value}
</span>
);
}
export function PageTitle({ title, subtitle, actions }: { title: string; subtitle?: React.ReactNode; actions?: React.ReactNode }) {
return (
<div className="mb-6 flex flex-wrap items-end justify-between gap-3">
<div>
<h1 className="text-2xl font-semibold">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-slate-500">{subtitle}</p>}
</div>
{actions}
</div>
);
}
export function Message({ msg }: { msg: { type: "ok" | "err"; text: string } | null }) {
if (!msg) return null;
return (
<div className={`rounded-lg border p-3 text-sm ${msg.type === "ok" ? "border-green-200 bg-green-50 text-green-800" : "border-red-200 bg-red-50 text-red-800"}`}>
{msg.text}
</div>
);
}
export function Stat({ label, value, tone }: { label: string; value: React.ReactNode; tone?: "red" | "amber" | "green" }) {
const color = tone === "red" ? "text-red-700" : tone === "amber" ? "text-amber-700" : tone === "green" ? "text-green-700" : "text-slate-900";
return (
<div className="card">
<div className="text-sm text-slate-500">{label}</div>
<div className={`mt-1 text-2xl font-semibold tabular-nums ${color}`}>{value}</div>
</div>
);
}
export function Loading() {
return <p className="text-sm text-slate-400">Loading…</p>;
}
+42
View File
@@ -0,0 +1,42 @@
export const API_URL = (process.env.NEXT_PUBLIC_API_URL || "http://localhost:5200").replace(/\/$/, "");
const TOKEN_KEY = "events_hub_token";
export class ApiError extends Error {
constructor(message: string, public status: number, public code?: string) {
super(message);
}
}
export function getToken(): string | null {
try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
}
export function setToken(token: string | null) {
try {
if (token) localStorage.setItem(TOKEN_KEY, token);
else localStorage.removeItem(TOKEN_KEY);
} catch { /* private window */ }
}
/** Call the Hub API. Logged-in calls send the session token; a 401 signs out. */
export async function api<T = unknown>(path: string, options: { method?: string; body?: unknown; auth?: boolean } = {}): Promise<T> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
const token = getToken();
if (options.auth !== false && token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(`${API_URL}${path}`, {
method: options.method || "GET",
headers,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 && options.auth !== false) {
setToken(null);
if (typeof window !== "undefined" && !window.location.pathname.startsWith("/login")) window.location.href = "/login";
}
throw new ApiError(data?.message || `Request failed (${res.status})`, res.status, data?.code);
}
return data as T;
}
export const errorText = (e: unknown, fallback = "Something went wrong.") => (e instanceof Error && e.message) || fallback;
+25
View File
@@ -0,0 +1,25 @@
export function fmtDate(d: string | Date | null | undefined, withTime = true) {
if (!d) return "—";
return new Date(d).toLocaleString("en-ZA", withTime ? { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" } : { day: "numeric", month: "short", year: "numeric" });
}
/** "5 min ago", "3 h ago", "2 days ago". */
export function ago(d: string | Date | null | undefined) {
if (!d) return "never";
const s = Math.round((Date.now() - new Date(d).getTime()) / 1000);
if (s < 90) return "just now";
if (s < 3600) return `${Math.round(s / 60)} min ago`;
if (s < 48 * 3600) return `${Math.round(s / 3600)} h ago`;
return `${Math.round(s / 86400)} days ago`;
}
export function bytes(n: number | null | undefined) {
if (n == null) return "—";
const units = ["B", "KB", "MB", "GB", "TB"];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
return `${v.toFixed(i > 1 ? 1 : 0)} ${units[i]}`;
}
export const rand = (cents: number) => `R${(cents / 100).toFixed(2)}`;
+65
View File
@@ -0,0 +1,65 @@
export type Problem = { type: string; level: "info" | "warning" | "critical"; message: string };
export type LicenceStatus = "active" | "suspended" | "revoked";
export type InstallSummary = {
id: string;
name: string;
url: string;
customer: { id: string; name: string } | null;
version: string | null;
behind: boolean;
licence: { id: string; status: LicenceStatus; expiresAt: string | null } | null;
lastHeartbeatAt: string | null;
status: "ok" | "warning" | "critical";
problems: Problem[];
releasedAt: string | null;
};
export type Licence = {
id: string;
key: string;
plan: string;
status: LicenceStatus;
expiresAt: string | null;
graceDays: number;
aiMonthlyCapCents: number;
notes: string | null;
createdAt: string;
install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null;
};
export type Customer = {
id: string;
name: string;
contactName: string | null;
email: string | null;
phone: string | null;
notes: string | null;
createdAt: string;
licences: Licence[];
installs: { id: string; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
};
export type Health = {
uptimeSeconds?: number;
db?: boolean;
jobs?: { mode?: string; failedLast24h?: number };
lastBackupAt?: string | null;
disk?: { freeBytes: number; totalBytes: number } | null;
errorsLast24h?: number | null;
pendingMigrations?: number;
};
export type Stats = {
users?: number;
events?: { active?: number; upcoming?: number; total?: number };
registrations?: { last30d?: number; total?: number };
tickets?: { last30d?: number; total?: number };
checkIns?: { last30d?: number };
messages?: { email30d?: number; whatsapp30d?: number };
paymentProviders?: string[];
campuses?: boolean;
income?: { last30d?: string; allTime?: string };
};
export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; install?: { id: string; name: string; url: string } };
+6
View File
@@ -0,0 +1,6 @@
/** @type {import("tailwindcss").Config} */
module.exports = {
content: ["./src/**/*.{js,ts,jsx,tsx}"],
theme: { extend: {} },
plugins: [],
};
+40
View File
@@ -0,0 +1,40 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
File diff suppressed because one or more lines are too long