Files
crosscode-platform/apps/events/backend/src/hub/licence.js
T
joshuaandClaude Opus 5.5 b67f40c2df Hub client: licence, heartbeat, read-only mode, /health, install script
- Connect with a licence key (/setup last screen, Site settings -> Licence)
- hub-heartbeat job every 15 min: version, health, totals (income as a band)
- Licence tokens verified with the Hub's public key; states active / grace
  (banner for site admins only) / suspended / revoked (read-only) /
  unlicensed; Hub keys kept out of the generic settings endpoints
- /health; "update available" for admins; scripts/install.sh
- docs/hub-protocol.md shared with the events-hub repo
- Unit tests (hub.test.js); docs

The production Hub public key (backend/src/hub/publicKey.js) must be set
before this is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 12:25:52 +02:00

94 lines
3.8 KiB
JavaScript

/**
* Licence checks (docs/hub-protocol.md §4). The Hub signs a licence token with its private
* key; this install checks it with the public key and works out its state, offline:
*
* active — everything works
* grace — past the end date for up to graceDays: works, site admins see a banner
* suspended — suspended by the Hub, or grace ran out: read-only (no new events,
* registrations or payments); tickets still scan, data can be exported
* revoked — like suspended, with a permanent banner
* unlicensed — never connected to the Hub: works, admins see "Connect to Hub"
*/
const crypto = require('crypto');
const prisma = require('../config/db');
const { hubPublicKey } = require('./publicKey');
const DAY = 24 * 60 * 60 * 1000;
const READ_ONLY_STATES = new Set(['suspended', 'revoked']);
const CACHE_MS = 30 * 1000;
let publicKeyObject = null;
let publicKeyPem = null;
function publicKey() {
const pem = hubPublicKey();
if (!pem) return null;
if (pem !== publicKeyPem) {
publicKeyObject = crypto.createPublicKey(pem);
publicKeyPem = pem;
}
return publicKeyObject;
}
/** The token's claims if the Hub signed it, else null. */
function verifyToken(token, key = publicKey()) {
if (!key) return null;
const parts = String(token || '').split('.');
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
try {
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], 'base64url'));
return ok ? JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) : null;
} catch {
return null;
}
}
/**
* The state for verified claims (or null = never connected). Pure, for tests.
* Returns { state, readOnly, endsAt, graceEndsAt, daysLeft }.
*/
function stateFor(claims, installId, now = new Date()) {
if (!claims || (installId && claims.installId !== installId)) {
return { state: 'unlicensed', readOnly: false, endsAt: null, graceEndsAt: null, daysLeft: null };
}
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map(d => new Date(d));
const endsAt = ends.length ? new Date(Math.min(...ends)) : null;
const graceEndsAt = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
let state;
if (claims.status === 'revoked') state = 'revoked';
else if (claims.status === 'suspended') state = 'suspended';
else if (!endsAt || now < endsAt) state = 'active';
else if (now < graceEndsAt) state = 'grace';
else state = 'suspended';
const daysLeft = state === 'grace' ? Math.max(0, Math.ceil((graceEndsAt - now) / DAY)) : null;
return { state, readOnly: READ_ONLY_STATES.has(state), endsAt, graceEndsAt, daysLeft, expired: state === 'suspended' && claims.status === 'active' };
}
let cache = null;
/** This install's licence: claims, state and Hub connection details. Cached for 30 s. */
async function licenceStatus({ fresh = false } = {}) {
if (!fresh && cache && Date.now() - cache.at < CACHE_MS) return cache.value;
const rows = await prisma.appSetting.findMany({ where: { key: { in: ['hub_install_id', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version'] } } });
const s = Object.fromEntries(rows.map(r => [r.key, r.value]));
const claims = verifyToken(s.hub_licence);
const value = {
keyConfigured: !!publicKey(),
connected: !!s.hub_install_id,
installId: s.hub_install_id || null,
claims: claims && claims.installId === s.hub_install_id ? claims : null,
...stateFor(claims, s.hub_install_id || null),
lastHeartbeatAt: s.hub_last_heartbeat_at || null,
lastError: s.hub_last_error || null,
latestVersion: s.hub_latest_version || null,
};
cache = { at: Date.now(), value };
return value;
}
function clearLicenceCache() {
cache = null;
}
module.exports = { verifyToken, stateFor, licenceStatus, clearLicenceCache, READ_ONLY_STATES };