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:
+19
-11
@@ -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);
|
||||
}));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user