Events 2.4.0 backend: protocol v2, Linked products, the event feed

- Hub client: register and heartbeat on protocol v2 with the site's
  Ed25519 key (sent on the heartbeat until the Hub has it); falls back to
  v1 for a day if the Hub refuses v2, so the licence always refreshes.
- crosscode.link/1 Connect / Disconnect, both directions, trusted through
  the Hub's cached linkedProducts (ProductLink, LinkNonce).
- GET /api/feed/v1/events from FeedEntry (go-live, closing and selling
  out are changes; deactivated events go in deleted), event.changed to
  connected products, and showing their events (ImportedEvent).
- /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains
  crosscodeEvent and priceRangeCents for the JSON-LD.
- Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 12:24:29 +02:00
co-authored by Claude Opus 5.5
parent 390b80e56e
commit 8a930d07c6
30 changed files with 5874 additions and 17 deletions
+129 -8
View File
@@ -6,8 +6,18 @@
* hub_last_heartbeat_at, hub_last_error, hub_latest_version,
* hub_releases, hub_notices (JSON from the last heartbeat: what's new, provider's notices),
* hub_update_requested_at, hub_update_requested_version,
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub).
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub),
* hub_v1_until (the Hub refused protocol v2: speak v1 until then; 2.4.0),
* and this site's key pair and the Hub's list of the church's other products (links/store.ts).
* These keys are kept out of the generic settings endpoints (settingsController).
*
* Protocol (2.4.0, docs/EVENTS-2.4-PLAN.md §1): register and heartbeat speak **v2**
* (`product: "events"`, this site's public key, the church's other products in the reply). An
* install that registered with v1 moves over by sending its key on the heartbeat (Hub 2.2.0
* saves it), so nobody needs the licence key again. If the Hub refuses a v2 body (a Hub before
* 2.0, or a body the Hub's contract doesn't accept), the same heartbeat goes again as v1 and v1
* is used for a day: the licence must keep refreshing whatever happens. Update requests and AI
* calls stay v1, which every Hub accepts.
*/
const crypto = require('crypto');
@@ -15,10 +25,16 @@ const prisma = require('../config/db');
const { encrypt, decrypt } = require('../utils/encryption');
const { verifyToken, clearLicenceCache } = require('./licence');
const report = require('./report');
const { hub } = require('@crosscode/contracts');
const store = require('../links/store');
/** Update requests and AI calls (as in v1; the Hub answers both versions). */
const PROTOCOL_VERSION = 1;
/** Register and heartbeat (2.4.0). */
const HEARTBEAT_PROTOCOL = 2;
const V1_FALLBACK_MS = 24 * 60 * 60 * 1000;
const TIMEOUT_MS = 15000;
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version'];
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version', 'hub_v1_until', ...store.KEY_SETTINGS];
function hubUrl() {
return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, '');
@@ -100,11 +116,26 @@ async function connect(licenceKey, adminContact) {
if (!/^https?:\/\//.test(install.url)) {
throw new HubError('Set the site\'s web address first (FRONTEND_URL on the server, or Site settings → Organisation).', 'NO_SITE_URL', 400);
}
const data = await post('/api/installs/register', {
const v1Body = {
protocolVersion: PROTOCOL_VERSION,
licenceKey: String(licenceKey || '').trim(),
install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null },
});
};
// v2 (2.4.0): the product and this site's public key, so the church's other products can link.
// Anything wrong with the key (or a Hub that only speaks v1) registers with v1 instead.
const publicKeyPem = await ownPublicKey();
const v2Body = { ...v1Body, protocolVersion: HEARTBEAT_PROTOCOL, licenceKey: v1Body.licenceKey.toUpperCase(), product: 'events', install: { ...v1Body.install, publicKey: publicKeyPem } };
const v2 = !!publicKeyPem && !(await v1Only()) && hub.registerRequestSchema.safeParse(v2Body).success;
let data;
let sentV2 = v2;
try {
data = await post('/api/installs/register', v2 ? v2Body : v1Body);
} catch (e) {
if (!v2 || !refusedV2(e)) throw e;
await useV1ForADay();
sentV2 = false;
data = await post('/api/installs/register', v1Body);
}
const claims = verifyToken(data.licence);
if (!claims || claims.installId !== data.installId) {
throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL pointing at the right Hub?', 'BAD_LICENCE', 502);
@@ -118,16 +149,106 @@ async function connect(licenceKey, adminContact) {
hub_latest_version: data.latestVersion || null,
...fromHub(data),
});
if (sentV2) {
try {
await store.saveLinkedProducts(data.linkedProducts);
// Registered with the key, so the Hub has it.
await store.setPublicKeyStatus('matches');
} catch (e) {
console.warn('[hub] Could not save the linked products:', e?.message || e);
}
}
return claims;
}
/** This site's public key, or null when it can't be made or read (then v1 is used). */
async function ownPublicKey() {
try {
return (await store.keyPair()).publicKeyPem;
} catch (e) {
console.warn('[hub] No key pair for protocol v2, using v1:', e?.message || e);
return null;
}
}
/** Whether the Hub refused a v2 body (too old for v2, or a contract it doesn't accept): retry as v1. */
function refusedV2(e) {
return e instanceof HubError && e.statusCode === 400 && ['UNSUPPORTED_PROTOCOL', 'INVALID_REQUEST'].includes(e.code);
}
async function v1Only() {
const until = (await read(['hub_v1_until'])).hub_v1_until;
return !!until && new Date(until).getTime() > Date.now();
}
async function useV1ForADay() {
await save({ hub_v1_until: new Date(Date.now() + V1_FALLBACK_MS).toISOString() });
}
/**
* The health as protocol v2 wants it: every field there (a part that couldn't be read is
* reported as nothing wrong rather than left out).
*/
function v2Health(h) {
return {
...h,
jobs: h.jobs || { mode: 'unknown', failedLast24h: 0 },
pendingMigrations: Number.isInteger(h.pendingMigrations) ? h.pendingMigrations : 0,
};
}
/**
* The heartbeat body: v2 when it fits the contract (with the public key until the Hub has it),
* otherwise v1. Returns { body, v2 }.
*/
async function heartbeatBody() {
const health = await report.health();
const stats = await report.stats();
const v1 = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health, stats };
if (await v1Only()) return { body: v1, v2: false };
const publicKeyPem = await ownPublicKey();
if (!publicKeyPem) return { body: v1, v2: false };
const status = await store.publicKeyStatus().catch(() => null);
const v2 = {
protocolVersion: HEARTBEAT_PROTOCOL,
product: 'events',
version: report.APP_VERSION,
health: v2Health(health),
stats,
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
};
const check = hub.heartbeatRequestSchema.safeParse(v2);
if (!check.success) {
console.warn('[hub] The v2 heartbeat doesn\'t fit the contract, sending v1:', check.error.issues.slice(0, 3).map(i => `${i.path.join('.')} ${i.message}`).join('; '));
return { body: v1, v2: false };
}
return { body: v2, v2: true };
}
/** Send a heartbeat (the `hub-heartbeat` job). Skips quietly when not connected. */
async function heartbeat() {
const s = await read(['hub_install_id', 'hub_install_secret']);
if (!s.hub_install_id || !s.hub_install_secret) return { skipped: 'not connected' };
const body = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health: await report.health(), stats: await report.stats() };
let { body, v2 } = await heartbeatBody();
try {
const data = await signedPost('/api/installs/heartbeat', body);
let data;
try {
data = await signedPost('/api/installs/heartbeat', body);
} catch (e) {
if (!v2 || !refusedV2(e)) throw e;
console.warn(`[hub] The Hub refused a v2 heartbeat (${e.code}: ${e.message}); using v1 for a day.`);
await useV1ForADay();
({ body, v2 } = await heartbeatBody());
data = await signedPost('/api/installs/heartbeat', body);
}
if (v2) {
try {
await store.saveLinkedProducts(data.linkedProducts);
if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus);
} catch (e) {
console.warn('[hub] Could not save the linked products:', e?.message || e);
}
}
const claims = verifyToken(data.licence);
await save({
// Keep the old token if the new one doesn't check out (never accept an unverified one).
@@ -137,7 +258,7 @@ async function heartbeat() {
hub_latest_version: data.latestVersion || null,
...fromHub(data),
});
return { ok: true, status: claims?.status || null };
return { ok: true, status: claims?.status || null, protocol: v2 ? 2 : 1 };
} catch (e) {
await save({ hub_last_error: `${new Date().toISOString()} ${e.code || ''} ${e.message}`.slice(0, 500) });
// The Hub doesn't know this install any more (licence released): drop the connection and the
@@ -245,4 +366,4 @@ async function connectFromEnv({ attempts = 5, delayMs = 60 * 1000, sleep = ms =>
return { connected: false, reason: 'unreachable' };
}
module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
module.exports = { PROTOCOL_VERSION, HEARTBEAT_PROTOCOL, HUB_KEYS, heartbeatBody, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };