Hub 2.0 step 2: protocol v2 next to v1

- Accepts protocol 1 and 2 (utils/protocol.js); v2 bodies checked with the
  contracts' zod schemas (400 INVALID_REQUEST), v1 unchanged
- v2 register/heartbeat carry product (409 WRONG_PRODUCT on a mismatch),
  register stores the install's public key, stats stored per product
- v2 replies add linkedProducts (the church's other installs in use with a
  public key); v1 replies unchanged
- Licence tokens carry customerId and product
- Until releases per product, only Events installs get releases / "behind"
- Tests: every contract sample through the real routes, replies checked
  against the contract response schemas

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 15:37:02 +02:00
co-authored by Claude Opus 5.5
parent 56370419bb
commit ab6a0c6914
6 changed files with 378 additions and 19 deletions
+58 -17
View File
@@ -1,7 +1,11 @@
/**
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request
* (and withdrawing it).
* (and withdrawing it), AI.
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
*
* Protocol v1 (Cross Events 2.1) and v2 (every product, @crosscode/contracts `hub`) are both
* accepted (utils/protocol.js). v2 bodies are checked with the contract schemas, and v2 replies
* add `linkedProducts`; v1 is handled and answered exactly as before.
*/
const express = require('express');
@@ -18,10 +22,11 @@ const { releasesForInstall } = require('../utils/releases');
const { noticesForInstall } = require('../utils/notices');
const ai = require('../utils/ai');
const { PRODUCT_NAMES } = require('../utils/products');
const { hub } = require('@crosscode/contracts');
const { PROTOCOL_VERSIONS, isV2, parseV2, linkedProductsFor } = require('../utils/protocol');
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' } });
@@ -49,6 +54,15 @@ function cleanUrl(url) {
}
}
/**
* Releases and the latest version are Cross Events' until releases per product (Hub 2.0 step 3):
* other products are told nothing rather than Events versions.
*/
async function releaseInfo(install, version, settings) {
if (install.product !== 'events') return { latestVersion: null, releases: [] };
return { latestVersion: settings.latest_version || null, releases: await releasesForInstall(version) };
}
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;
@@ -77,14 +91,32 @@ async function signedInstall(req, res) {
return install;
}
/**
* The request body: a v2 body checked against its contract schema (null once the 400 is sent),
* a v1 body as it came.
*/
function bodyFor(req, res, schema) {
if (!isV2(req.body)) return req.body || {};
const parsed = parseV2(schema, req.body);
if (!parsed.ok) { fail(res, parsed.status, parsed.code, parsed.message); return null; }
return parsed.data;
}
const wrongProduct = (res, got, want) =>
fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[got]} licence, not a ${PRODUCT_NAMES[want]} one. Check you copied the right key.`);
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 raw = req.body || {};
if (!protocolOk(raw)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${raw.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
const v2 = isV2(raw);
// A key as typed (lower case, spaces) is tidied before the v2 schema checks its shape.
const body = bodyFor({ body: v2 ? { ...raw, licenceKey: normaliseLicenceKey(raw.licenceKey) } : raw }, res, hub.registerRequestSchema);
if (!body) return;
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://…).');
@@ -92,11 +124,9 @@ 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.`);
}
// v2 says which product is registering; v1 is always Cross Events.
const product = v2 ? body.product : 'events';
if (licence.product !== product) return wrongProduct(res, licence.product, product);
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.');
}
@@ -112,6 +142,8 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
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,
// v2: shared with the church's other installs (linkedProducts). A v1 re-register keeps it.
publicKey: v2 ? info.publicKey : undefined,
releasedAt: null,
};
// Same licence, same site → re-register (new secret, same id).
@@ -126,9 +158,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
installSecret: secret,
licence: await tokenFor(install),
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(install.version),
...(await releaseInfo(install, install.version, settings)),
notices: await noticesForInstall(install.id),
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
});
} catch (e) {
console.error('[register]', e);
@@ -140,7 +172,10 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
if (!install) return;
const body = req.body;
const body = bodyFor(req, res, hub.heartbeatRequestSchema);
if (!body) return;
const v2 = isV2(body);
if (v2 && body.product !== install.product) return wrongProduct(res, install.product, body.product);
const now = new Date();
const version = str(body.version, 40);
@@ -161,9 +196,9 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
const settings = await getSettings();
res.json({
licence: await tokenFor(install),
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(version || install.version),
...(await releaseInfo(install, version || install.version, settings)),
notices: await noticesForInstall(install.id, now),
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
serverTime: now.toISOString(),
});
} catch (e) {
@@ -178,10 +213,12 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
try {
const install = await signedInstall(req, res);
if (!install) return;
const body = bodyFor(req, res, hub.updateRequestSchema);
if (!body) return;
const settings = await getSettings();
const latest = settings.latest_version || null;
const current = str(req.body.version, 40) || install.version;
const latest = (await releaseInfo(install, null, settings)).latestVersion;
const current = str(body.version, 40) || install.version;
if (!latest || compareVersions(current, latest) >= 0) {
return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.');
}
@@ -232,6 +269,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
try {
const install = await signedInstall(req, res);
if (!install) return;
if (!bodyFor(req, res, hub.updateRequestCancelSchema)) return;
const now = new Date();
const open = await prisma.installEvent.findMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null } });
@@ -262,6 +300,7 @@ router.post('/installs/ai/status', aiLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
if (!install) return;
if (!bodyFor(req, res, hub.aiStatusRequestSchema)) return;
res.json(await ai.statusFor(install));
} catch (e) {
console.error('[ai/status]', e);
@@ -275,7 +314,9 @@ router.post('/installs/ai/complete', aiLimiter, async (req, res) => {
try {
install = await signedInstall(req, res);
if (!install) return;
res.json(await ai.complete(install, req.body));
const body = bodyFor(req, res, hub.aiCompleteRequestSchema);
if (!body) return;
res.json(await ai.complete(install, body));
} catch (e) {
if (e.status && e.code) return res.status(e.status).json({ code: e.code, message: e.message, ...(e.aiStatus ? { status: e.aiStatus } : {}) });
console.error('[ai/complete]', e);