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
View File
@@ -10,6 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -607,6 +608,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.0.0",
"resolved": "file:vendor/crosscode-contracts-1.0.0.tgz",
"integrity": "sha512-NcilXx9mVmHNsQvIBNNH5rPBmNKYKBSO8bLmC5czLNIlSiQQz95571qPYx+PMXvibAw7TX1LPpO8TKgz5f0dHA==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
}
},
"node_modules/@electric-sql/pglite": {
"version": "0.4.3",
"resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.3.tgz",
@@ -7742,6 +7752,15 @@
"grammex": "^3.1.11",
"graphmatch": "^1.1.0"
}
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+3 -1
View File
@@ -15,10 +15,12 @@
"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"
"generate-keys": "node scripts/generate-keys.js",
"check:hub2": "node scripts/check-hub2.js"
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -0,0 +1,29 @@
-- CreateEnum
CREATE TYPE "Product" AS ENUM ('events', 'accounts', 'website', 'app');
-- AlterTable
ALTER TABLE "Install" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events',
ADD COLUMN "publicKey" TEXT;
-- AlterTable
ALTER TABLE "Licence" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events';
-- CreateIndex
CREATE INDEX "Licence_customerId_product_idx" ON "Licence"("customerId", "product");
-- One licence per product per customer that isn't revoked (Hub 2.0; a revoked licence can be
-- replaced). Prisma can't express a partial index, so it's only here. Every licence before 2.0 is
-- an Events licence: a customer with two that aren't revoked stops the migration, named, so it can
-- be sorted out (revoke one) before deploying — `npm run check:hub2` lists them in advance.
DO $$
DECLARE dupes TEXT;
BEGIN
SELECT string_agg(format('%s (%s licences)', c.name, n), ', ') INTO dupes
FROM (SELECT "customerId", count(*) AS n FROM "Licence" WHERE status <> 'revoked' GROUP BY "customerId" HAVING count(*) > 1) d
JOIN "Customer" c ON c.id = d."customerId";
IF dupes IS NOT NULL THEN
RAISE EXCEPTION 'Hub 2.0 allows one Events licence per customer that is not revoked. Revoke the extra licences first: %', dupes;
END IF;
END $$;
CREATE UNIQUE INDEX "Licence_customerId_product_open_key" ON "Licence"("customerId", "product") WHERE status <> 'revoked';
+20 -1
View File
@@ -56,12 +56,25 @@ enum LicenceStatus {
revoked
}
// Hub 2.0: the Cross Code products a church can have (ROADMAP-v3 §5). Accounts comes free with
// any other product.
enum Product {
events
accounts
website
app
}
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.
// CEH-XXXX-XXXX-XXXX-XXXX (Events), CCA- (Accounts), CCW- (Website), CCP- (App).
key String @unique
// Hub 2.0. A customer has at most one licence per product that isn't revoked: enforced by the
// partial unique index "Licence_customerId_product_open_key" (migration 20261104…_products),
// which Prisma can't express here.
product Product @default(events)
plan String @default("standard")
status LicenceStatus @default(active)
// Null = no end date.
@@ -90,6 +103,8 @@ model Licence {
install Install?
invoices Invoice[]
licenceChanges LicenceChange[]
@@index([customerId, product])
}
enum BillingCycle {
@@ -104,8 +119,12 @@ model Install {
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String? @unique
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
// Hub 2.0: the licence's product, set when the install registers.
product Product @default(events)
name String
url String
// Protocol v2: the install's Ed25519 public key (PEM), shared with its linked products.
publicKey String?
// The install's HMAC secret, AES-GCM encrypted: the Hub needs it to check signatures.
secret String
version String?
+44
View File
@@ -0,0 +1,44 @@
/**
* Before deploying Hub 2.0: checks the database can take the 2.0 migrations, and lists what to
* sort out first. Changes nothing.
*
* npm run check:hub2
*
* Works before and after the 2.0 migrations (it reads the tables directly).
* - Hub 2.0 allows one licence per product per customer that isn't revoked. Every licence before
* 2.0 is an Events licence, so a customer with two open licences stops the migration: revoke
* the one that isn't used (its install, if any, stops reporting).
*/
require('dotenv').config();
const prisma = require('../src/config/db');
async function main() {
const columns = await prisma.$queryRaw`SELECT column_name FROM information_schema.columns WHERE table_name = 'Licence' AND column_name = 'product'`;
const hasProduct = columns.length > 0;
const rows = hasProduct
? await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", l.product::text AS product, count(*)::int AS n,
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId", l.product HAVING count(*) > 1 ORDER BY c.name`)
: await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", 'events' AS product, count(*)::int AS n,
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId" HAVING count(*) > 1 ORDER BY c.name`);
if (!rows.length) {
console.log('OK: every customer has at most one open licence per product. Hub 2.0 can be deployed.');
return 0;
}
console.log('Hub 2.0 allows one open (not revoked) licence per product per customer. Revoke the extra ones first:');
for (const r of rows) console.log(` - ${r.name}: ${r.n} ${r.product} licences: ${r.keys}`);
return 1;
}
main()
.then(code => prisma.$disconnect().then(() => process.exit(code)))
.catch(async e => {
console.error('The check failed:', e.message);
await prisma.$disconnect().catch(() => {});
process.exit(2);
});
+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}`;
}
+150
View File
@@ -0,0 +1,150 @@
// Hub 2.0 step 1: products, licence keys per product, one open licence per product per customer
// (with the partial unique index simulated), the free Accounts licence, and protocol v1
// registering Events licences only. In-memory database.
const mockLicences = [];
const mockInstalls = [];
const isOpen = l => l.status !== 'revoked';
const mockDb = {
licence: {
findFirst: jest.fn(async ({ where }) => mockLicences.find(l => l.customerId === where.customerId && l.product === where.product && (!where.status?.not || l.status !== where.status.not)) || null),
findUnique: jest.fn(async ({ where, include }) => {
const l = mockLicences.find(x => (where.key ? x.key === where.key : x.id === where.id));
if (!l) return null;
return include ? { ...l, install: mockInstalls.find(i => i.licenceId === l.id) || null, customer: { id: l.customerId, name: 'Hope Church' } } : l;
}),
create: jest.fn(async ({ data }) => {
// The unique key and the partial unique index on (customerId, product) WHERE status <> 'revoked'.
if (mockLicences.some(l => l.key === data.key)) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
const status = data.status || 'active';
if (status !== 'revoked' && mockLicences.some(l => isOpen(l) && l.customerId === data.customerId && l.product === data.product)) {
throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
}
const row = { id: `lic_${mockLicences.length + 1}`, status, plan: 'standard', createdAt: new Date(), ...data };
mockLicences.push(row);
return row;
}),
},
install: {
create: jest.fn(async ({ data }) => { const row = { id: `inst_${mockInstalls.length + 1}`, ...data }; mockInstalls.push(row); return row; }),
update: jest.fn(),
},
installEvent: { create: jest.fn(async () => ({})) },
};
jest.mock('../src/config/db', () => mockDb);
jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.1.1' })) }));
jest.mock('../src/utils/releases', () => ({ releasesForInstall: jest.fn(async () => []) }));
jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) }));
jest.mock('../src/utils/licenceToken', () => ({ sign: jest.fn(() => 'hel1.token.sig'), buildPayload: jest.fn(() => ({})) }));
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
const express = require('express');
const { licenceKey } = require('../src/utils/crypto');
const { PRODUCTS, KEY_PREFIXES, productOfKey } = require('../src/utils/products');
const { generateLicence, createLicence, checkReopen } = require('../src/utils/licences');
const { productSchema } = require('@crosscode/contracts');
beforeEach(() => { mockLicences.length = 0; mockInstalls.length = 0; });
describe('products', () => {
test('the Hub has the same products as the contracts', () => {
expect([...PRODUCTS].sort()).toEqual([...productSchema.options].sort());
});
test.each(PRODUCTS)('%s keys have their own prefix and are recognised', product => {
const key = licenceKey(product);
expect(key).toMatch(new RegExp(`^${KEY_PREFIXES[product]}(-[ACDEFGHJKMNPQRTUVWXY234679]{4}){4}$`));
expect(productOfKey(key)).toBe(product);
});
test('Events keys keep CEH-, and the default is Events', () => {
expect(licenceKey()).toMatch(/^CEH-/);
expect(() => licenceKey('nope')).toThrow();
});
});
describe('licences', () => {
test('the first product licence comes with a free Accounts licence', async () => {
const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: { status: 'active' } });
expect(licence).toMatchObject({ product: 'website', key: expect.stringMatching(/^CCW-/) });
expect(accounts).toMatchObject({ product: 'accounts', plan: 'included', key: expect.stringMatching(/^CCA-/) });
});
test('a later product licence does not make a second Accounts licence', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
const { accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
expect(accounts).toBeNull();
expect(mockLicences.filter(l => l.product === 'accounts')).toHaveLength(1);
});
test('a second open licence for the same product is refused', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).rejects.toMatchObject({ status: 409, code: 'PRODUCT_LICENCE_EXISTS' });
});
test('another customer can have the same product', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(generateLicence(mockDb, { customerId: 'c2', product: 'events', data: {} })).resolves.toBeTruthy();
});
test('a revoked licence can be replaced', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
licence.status = 'revoked';
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).resolves.toBeTruthy();
});
test('a race is caught by the unique index', async () => {
// Both requests pass the check before either inserts: the second insert hits the index.
mockDb.licence.findFirst.mockResolvedValueOnce(null);
await createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
mockDb.licence.findFirst.mockResolvedValueOnce(null);
await expect(createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} })).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
});
test('un-revoking is refused when the product has another open licence', async () => {
const { licence: old } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
old.status = 'revoked';
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(checkReopen(mockDb, old, 'active')).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
await expect(checkReopen(mockDb, old, 'revoked')).resolves.toBeUndefined();
});
test('unknown products are refused', async () => {
await expect(createLicence(mockDb, { customerId: 'c1', product: 'shop' })).rejects.toMatchObject({ status: 400 });
});
});
describe('register (protocol v1)', () => {
let server;
let base;
beforeAll(async () => {
const app = express();
app.use(express.json());
app.use('/api', require('../src/routes/installApi'));
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
base = `http://127.0.0.1:${server.address().port}/api`;
});
afterAll(() => new Promise(resolve => server.close(resolve)));
const register = key => fetch(`${base}/installs/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ protocolVersion: 1, licenceKey: key, install: { name: 'Hope Church', url: 'https://events.hope.test', version: '2.1.1' } }),
});
test('an Events licence registers, and the install is an Events install', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
const res = await register(licence.key);
expect(res.status).toBe(201);
expect(mockInstalls[0]).toMatchObject({ product: 'events', licenceId: licence.id });
});
test('another product\'s licence is refused with WRONG_PRODUCT', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: {} });
const res = await register(licence.key);
expect(res.status).toBe(409);
expect(await res.json()).toMatchObject({ code: 'WRONG_PRODUCT' });
expect(mockInstalls).toHaveLength(0);
});
});
Binary file not shown.