Hub 2.0 step 1: products foundation

- Product enum (events, accounts, website, app) on Licence and Install,
  Install.publicKey; existing rows are events
- One open licence per product per customer: partial unique index, with a
  migration guard that names customers with duplicates (npm run check:hub2
  lists them beforehand)
- Licence keys per product (CEH-, CCA-, CCW-, CCP-); free Accounts licence
  created with the first other product licence
- Protocol v1 registers Events licences only (409 WRONG_PRODUCT); only Events
  licences can be invoiced until billing per customer
- Cross Code Hub in the UI, emails and PDFs
- @crosscode/contracts 1.0.0 vendored (backend/vendor)
- Steps merge into release/2.0, not main (plan updated)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 15:28:06 +02:00
co-authored by Claude Opus 5.5
parent fe0f2638c6
commit ad602b2846
30 changed files with 544 additions and 49 deletions
+19 -11
View File
@@ -4,7 +4,8 @@ const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { licenceKey } = require('../utils/crypto');
const { generateLicence, checkReopen } = require('../utils/licences');
const { isProduct, PRODUCT_NAMES } = require('../utils/products');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
@@ -24,7 +25,7 @@ const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardH
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 && !e.status ? 'Something went wrong.' : e.message });
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
});
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));
@@ -42,6 +43,7 @@ function summary(install, settings, now = new Date()) {
const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok';
return {
id: install.id,
product: install.product,
name: install.name,
url: install.url,
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
@@ -87,7 +89,7 @@ router.get('/dashboard', wrap(async (req, res) => {
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 } } },
include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } },
});
res.json(customers);
}));
@@ -153,23 +155,29 @@ function licenceData(body, { partial = false } = {}) {
return data;
}
// "Generate": a new licence with a fresh key for a customer.
// "Generate": a new licence with a fresh key for a customer, for one product (Events unless
// another is given). A customer has one open licence per product; its Accounts licence (free)
// is created with its first other product.
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);
const product = req.body?.product ?? 'events';
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
res.status(201).json({ ...licence, accountsLicence: accounts });
}));
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 checkReopen(prisma, existing, data.status);
const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => {
if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' });
throw e;
});
await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt });
res.json(licence);
}));
+5
View File
@@ -12,6 +12,7 @@ const billing = require('../utils/billing');
const compute = require('../utils/billing/compute');
const { ymd, day, today } = require('../utils/billing/dates');
const { TIERS } = require('../utils/billing/tiers');
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
const router = express.Router();
router.use(protect);
@@ -279,6 +280,10 @@ router.put('/licences/:id', wrap(async (req, res) => {
}
}
const merged = { ...existing, ...data };
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
}
if (merged.billingCycle !== 'none') {
if (!merged.billingStart) throw bad('Set the date billing starts.');
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
+10 -4
View File
@@ -17,6 +17,7 @@ const { sendMail } = require('../utils/mail');
const { releasesForInstall } = require('../utils/releases');
const { noticesForInstall } = require('../utils/notices');
const ai = require('../utils/ai');
const { PRODUCT_NAMES } = require('../utils/products');
const router = express.Router();
@@ -91,6 +92,11 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
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.');
// Protocol v1 is Cross Events only; other products register with v2 (Hub 2.0 step 2).
const product = 'events';
if (licence.product !== product) {
return fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[licence.product]} licence key, not a ${PRODUCT_NAMES[product]} one. Check you copied the right key.`);
}
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.');
}
@@ -111,7 +117,7 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
// 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.install.create({ data: { ...data, product: licence.product, 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();
@@ -197,7 +203,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
const name = await customerName();
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update request changed by ${name}`,
subject: `Cross Code Hub: update request changed by ${name}`,
text: `${name} (${install.url}) now asks to be updated from ${current} to ${latest}${previous ? ` instead of ${previous}` : ''}.\n\n${link}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
@@ -209,7 +215,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
const name = await customerName();
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update requested by ${name}`,
subject: `Cross Code Hub: update requested by ${name}`,
text: `${name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${link}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
@@ -238,7 +244,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update request withdrawn by ${customer?.name || install.name}`,
subject: `Cross Code Hub: update request withdrawn by ${customer?.name || install.name}`,
text: `${customer?.name || install.name} (${install.url}) withdrew their update request. No need to update the site for now.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
+1 -1
View File
@@ -106,7 +106,7 @@ async function runAlerts(now = new Date()) {
if (newAlerts.length && settings.alert_email) {
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
subject: `Cross Code 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));
}
+2 -1
View File
@@ -21,6 +21,7 @@ const pdf = require('./pdf');
const { layout, sendBillingEmail } = require('./email');
const { ymd, day, today, saHour, addDays, longDate, periodLabel, money } = require('./dates');
const { planPrice, tierNamed } = require('./tiers');
const { BILLABLE } = require('../products');
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`;
@@ -97,7 +98,7 @@ async function createDueDrafts(now, settings) {
const days = parseInt(settings.billing_draft_days, 10) || 14;
const horizon = addDays(today(now), days);
const licences = await prisma.licence.findMany({
where: { status: 'active', billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
where: { status: 'active', product: { in: BILLABLE }, billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
select: { id: true },
});
let made = 0;
+1 -1
View File
@@ -18,7 +18,7 @@ const W = 595.28 - M * 2; // content width
/** Renders `draw(doc)` into a PDF and resolves with its bytes. */
function render(draw, { title, draft = false } = {}) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Events Hub' } });
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Code Hub' } });
const chunks = [];
doc.on('data', c => chunks.push(c));
doc.on('end', () => resolve(Buffer.concat(chunks)));
+9 -3
View File
@@ -7,6 +7,7 @@
*/
const crypto = require('crypto');
const { KEY_PREFIXES } = require('./products');
let cachedKey = null;
function key() {
@@ -35,11 +36,16 @@ function decrypt(stored) {
// 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() {
/**
* A licence key for a product: CEH-XXXX-XXXX-XXXX-XXXX for Events, CCA-/CCW-/CCP- for Accounts,
* Website and App (16 characters from 26, ~75 bits of randomness).
*/
function licenceKey(product = 'events') {
const prefix = KEY_PREFIXES[product];
if (!prefix) throw new Error(`Unknown product: ${product}`);
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)}`;
return `${prefix}-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
}
/** Tidy what someone typed: upper case, no spaces. */
+77
View File
@@ -0,0 +1,77 @@
/**
* Creating licences (Hub 2.0): one licence per product per customer that isn't revoked, a key
* with the product's prefix, and the free Accounts licence that comes with any other product.
*/
const { licenceKey } = require('./crypto');
const { PRODUCT_NAMES, isProduct } = require('./products');
const conflict = (message, code) => Object.assign(new Error(message), { status: 409, code });
/** The customer's licence for a product that isn't revoked, or null. */
function openLicence(db, customerId, product) {
return db.licence.findFirst({ where: { customerId, product, status: { not: 'revoked' } } });
}
const productTaken = product =>
conflict(`This customer already has a ${PRODUCT_NAMES[product]} licence. Revoke it first to issue a new one (a customer has one of each product).`, 'PRODUCT_LICENCE_EXISTS');
/**
* A new licence for `product`, with a fresh key. A key collision (vanishingly rare) is retried; a
* second open licence for the product is refused with 409 PRODUCT_LICENCE_EXISTS, also when two
* requests race (the partial unique index catches the second).
*/
async function createLicence(db, { customerId, product = 'events', data = {} }) {
if (!isProduct(product)) throw Object.assign(new Error('Unknown product.'), { status: 400 });
if (await openLicence(db, customerId, product)) throw productTaken(product);
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await db.licence.create({ data: { ...data, customerId, product, key: licenceKey(product) } });
} catch (e) {
if (e?.code !== 'P2002') throw e;
if (await openLicence(db, customerId, product)) throw productTaken(product);
// Otherwise the key collided: try another.
}
}
throw new Error('Could not generate a unique licence key.');
}
/**
* The customer's Accounts licence, created (free, never invoiced) if it has none that isn't
* revoked. Returns { licence, created }.
*/
async function ensureAccountsLicence(db, customerId) {
const existing = await openLicence(db, customerId, 'accounts');
if (existing) return { licence: existing, created: false };
try {
const licence = await createLicence(db, { customerId, product: 'accounts', data: { plan: 'included', status: 'active', notes: 'Comes with the church\'s other products (free).' } });
return { licence, created: true };
} catch (e) {
// Created by a request running at the same time.
if (e.code === 'PRODUCT_LICENCE_EXISTS') return { licence: await openLicence(db, customerId, 'accounts'), created: false };
throw e;
}
}
/**
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
*/
async function generateLicence(db, { customerId, product = 'events', data = {} }) {
const licence = await createLicence(db, { customerId, product, data });
if (product === 'accounts') return { licence, accounts: null };
const { licence: accounts, created } = await ensureAccountsLicence(db, customerId);
return { licence, accounts: created ? accounts : null };
}
/**
* Changing a licence's status back from revoked would give the customer two open licences for the
* product: refused with 409 PRODUCT_LICENCE_EXISTS.
*/
async function checkReopen(db, licence, nextStatus) {
if (licence.status !== 'revoked' || !nextStatus || nextStatus === 'revoked') return;
const other = await openLicence(db, licence.customerId, licence.product);
if (other && other.id !== licence.id) throw productTaken(licence.product);
}
module.exports = { openLicence, createLicence, ensureAccountsLicence, generateLicence, checkReopen };
+2 -2
View File
@@ -61,8 +61,8 @@ async function testSmtp(overrides, to) {
await t.sendMail({
from: fromAddress(smtp),
to,
subject: 'Cross Events Hub: test email',
text: `This is a test email from the Cross Events Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
subject: 'Cross Code Hub: test email',
text: `This is a test email from the Cross Code Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
});
} finally {
t.close();
+40
View File
@@ -0,0 +1,40 @@
/**
* The Cross Code products a church can have (Hub 2.0, ROADMAP-v3 §5). The same names as the
* `Product` enum in schema.prisma and `productSchema` in @crosscode/contracts.
*
* - A customer has at most one licence per product that isn't revoked (a partial unique index).
* - Accounts is free and comes with any other product: its licence is created with the first one.
*/
const PRODUCTS = ['events', 'accounts', 'website', 'app'];
const PRODUCT_NAMES = {
events: 'Cross Events',
accounts: 'Accounts',
website: 'Church Website',
app: 'Church App',
};
/** Licence key prefixes. CEH- (Cross Events Hub) predates 2.0 and stays for Events. */
const KEY_PREFIXES = {
events: 'CEH',
accounts: 'CCA',
website: 'CCW',
app: 'CCP',
};
/** The product a licence key is for, from its prefix, or null. */
function productOfKey(key) {
const prefix = String(key || '').slice(0, 3).toUpperCase();
return PRODUCTS.find(p => KEY_PREFIXES[p] === prefix) || null;
}
const isProduct = p => PRODUCTS.includes(p);
/**
* Products that can be invoiced. Until billing per customer (Hub 2.0 step 4) only Events has
* prices; Accounts is never invoiced.
*/
const BILLABLE = ['events'];
module.exports = { PRODUCTS, PRODUCT_NAMES, KEY_PREFIXES, BILLABLE, productOfKey, isProduct };
+1 -1
View File
@@ -67,7 +67,7 @@ function verifyCode(secret, code, now = Date.now()) {
}
/** The otpauth:// link an authenticator app scans (as a QR code). */
function otpauthUrl(secret, account, issuer = 'Cross Events Hub') {
function otpauthUrl(secret, account, issuer = 'Cross Code Hub') {
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
}