/** * The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request * (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'); const rateLimit = require('express-rate-limit'); const prisma = require('../config/db'); const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../utils/crypto'); const licenceToken = require('../utils/licenceToken'); const { checkSignature } = require('../utils/signing'); const { getSettings } = require('../utils/settings'); const { compareVersions } = require('../utils/alerts'); const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/updateRequests'); const { sendMail } = require('../utils/mail'); const { render } = require('../utils/emailLayout'); const storage = require('../utils/storage'); /** An update-request email to Joshua (2.10.0: laid out as the Hub's other emails). */ const updateRequestEmail = ({ heading, note, rows, link }) => render({ heading, blocks: [note, { rows }, { button: { label: 'Open the install', url: link } }], footer: 'Sent by the Cross Code Hub to the alert address in Settings.', }); const { releasesForInstall, latestVersions, unmetRequirementsFor, requirementMessage } = 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 { ed25519PublicFromPem } = require('@crosscode/contracts/signing'); const { PROTOCOL_VERSIONS, isV2, parseV2, linkedProductsFor } = require('../utils/protocol'); const router = express.Router(); 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' } }); const updateRequestLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } }); // AI is limited by money (the cap); this only stops a runaway loop. const aiLimiter = rateLimit({ windowMs: 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many AI requests — wait a minute.', code: 'RATE_LIMITED' } }); const fail = (res, status, code, message) => res.status(status).json({ code, message }); function protocolOk(body) { const minSupported = Math.max(...PROTOCOL_VERSIONS) - 1; const v = body?.protocolVersion; return Number.isInteger(v) && v >= minSupported && v <= Math.max(...PROTOCOL_VERSIONS); } // Only small, known pieces of what an install says about itself are kept. const str = (v, max = 200) => (v == null ? null : String(v).slice(0, max)); function cleanUrl(url) { try { const u = new URL(String(url)); if (!/^https?:$/.test(u.protocol)) return null; return `${u.protocol}//${u.host}${u.pathname.replace(/\/$/, '')}`; } catch { return null; } } /** * The install's product's latest version and the releases newer than `version` (Hub 2.0: per * product). v2 replies carry each release's requirements; v1 replies are as before. */ async function releaseInfo(install, version, { v2 = false } = {}) { const latest = (await latestVersions())[install.product] || null; return { latestVersion: latest, releases: await releasesForInstall(install.product, version, { withRequires: v2 }) }; } async function tokenFor(install) { const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true, aiMonthlyCapCents: true } } } }) : null; if (!licence) return null; // The AI cap in the token is the church's (Hub 2.0). return licenceToken.sign(licenceToken.buildPayload({ ...licence, aiMonthlyCapCents: licence.customer.aiMonthlyCapCents }, install, licence.customer.name)); } /** * The install a signed request comes from (§3), or null once the error has been sent: * unknown/released install, stale timestamp, bad signature or unsupported protocol. */ async function signedInstall(req, res) { const installId = String(req.headers['x-hub-install'] || ''); const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null; if (!install || install.releasedAt) { fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.'); return null; } const problem = checkSignature({ secret: decrypt(install.secret), timestamp: String(req.headers['x-hub-timestamp'] || ''), rawBody: req.rawBody || '', given: String(req.headers['x-hub-signature'] || ''), }); if (problem === 'STALE_REQUEST') { fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock."); return null; } if (problem) { fail(res, 401, problem, 'The request signature is not valid.'); return null; } if (!protocolOk(req.body)) { fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${req.body?.protocolVersion} is not supported.`); return null; } 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 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://…).'); 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.'); // 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.'); } const secret = randomSecret(); const data = { name: str(info.name) || licence.customer.name, url, secret: encrypt(secret), version: str(info.version, 40), protocolVersion: body.protocolVersion, adminContact: info.adminContact ? { name: str(info.adminContact.name), email: str(info.adminContact.email) } : undefined, 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). const install = licence.install ? await prisma.install.update({ where: { id: licence.install.id }, data }) : 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() } }); // A site the Hub installed (Servers → New install) is linked to its registration, so its // update and closing banners reach it (found in the VM test: they never did). try { await prisma.deployment.updateMany({ where: { licenceId: licence.id, installId: null }, data: { installId: install.id } }); } catch (e) { console.warn('[hub] linking the deployment to its install failed:', e?.message || e); } res.status(201).json({ installId: install.id, installSecret: secret, licence: await tokenFor(install), heartbeatIntervalMinutes: HEARTBEAT_MINUTES, ...(await releaseInfo(install, install.version, { v2 })), notices: await noticesForInstall(install.id), ...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}), }); } catch (e) { console.error('[register]', e); fail(res, 500, 'SERVER_ERROR', 'The Hub could not register this install. Try again later.'); } }); /** The same key, ignoring line endings and surrounding whitespace. */ function samePem(a, b) { const norm = s => String(s || '').replace(/\r\n/g, '\n').trim(); return norm(a) === norm(b); } /** * A public key sent on a v2 heartbeat (Hub 2.2.0): `saved` when the install had none, `matches`, * or `mismatch` (the saved key stays; an alert is opened once). Lets an install that registered * with protocol v1 move to v2 without its licence key. Never fails the heartbeat: the licence * must keep refreshing whatever happens to the key. */ async function acceptPublicKey(install, pem, now) { try { ed25519PublicFromPem(pem); } catch { return 'mismatch'; } if (!install.publicKey) { await prisma.install.update({ where: { id: install.id }, data: { publicKey: `${pem.replace(/\r\n/g, '\n').trim()}\n` } }); await prisma.installEvent.create({ data: { installId: install.id, type: 'public_key', level: 'info', message: 'Public key saved: the church\'s other products can now link to this install.', resolvedAt: now } }); return 'saved'; } if (samePem(install.publicKey, pem)) return 'matches'; const open = await prisma.installEvent.findFirst({ where: { installId: install.id, type: 'public_key_mismatch', resolvedAt: null } }); if (!open) { await prisma.installEvent.create({ data: { installId: install.id, type: 'public_key_mismatch', level: 'warning', message: 'The install sent a different public key from the one saved. Linked products keep using the saved key. If the server was restored or rebuilt, clear the saved key on this install\'s page.' } }); } return 'mismatch'; } router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { try { const install = await signedInstall(req, res); if (!install) return; 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); const health = body.health && typeof body.health === 'object' ? body.health : null; const stats = body.stats && typeof body.stats === 'object' ? body.stats : null; await prisma.$transaction([ prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }), prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }), ]); // Hub 2.6.0: a site the Hub installed is tied to its registration on every heartbeat too, not // only when it first registers (so a missed one is mended). A site with no install record at // all has its server asked what's on it (a status job), which adds it. Neither fails the heartbeat. try { const tied = await prisma.deployment.updateMany({ where: { licenceId: install.licenceId, installId: null, status: { notIn: ['removed', 'failed'] } }, data: { installId: install.id } }); if (!tied.count) await require('../utils/jobs').lookForUnlinked(install, now); // Hub 2.23.1: the install record's version follows the heartbeat (it only followed the Hub's // own jobs, so a product updated alongside another kept its old version there). if (version) await prisma.deployment.updateMany({ where: { installId: install.id, OR: [{ version: null }, { version: { not: version } }] }, data: { version } }); } catch (e) { console.warn('[hub] tying the install record to its site failed:', e?.message || e); } if (version && install.version && version !== install.version) { await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } }); // An update the church asked for is done once the install runs a newer version. if (compareVersions(version, install.version) > 0) { await prisma.installEvent.updateMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, data: { resolvedAt: now } }); } } // Hub 2.22.0: a Website's storage at 80% or full emails the church once (decision 12). if (install.product === 'website' && stats) { try { const withCustomer = await prisma.install.findUnique({ where: { id: install.id }, include: { customer: true } }); await storage.storageLevels(prisma, withCustomer || install, stats, { sendMail, now }); } catch (e) { console.warn('[storage] checking the storage level failed:', e?.message || e); } } const publicKeyStatus = v2 && body.publicKey ? await acceptPublicKey(install, body.publicKey, now) : null; res.json({ licence: await tokenFor(install), ...(await releaseInfo(install, version || install.version, { v2 })), notices: await noticesForInstall(install.id, now), ...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}), serverTime: now.toISOString(), ...(publicKeyStatus ? { publicKeyStatus } : {}), }); } catch (e) { console.error('[heartbeat]', e); fail(res, 500, 'SERVER_ERROR', 'The Hub could not record this heartbeat.'); } }); // Hub 2.22.0 (contracts 1.18.0): a Website's Owner or Admin pressed "Get more storage". Recorded on // the install and emailed to Joshua once per request; it closes when the licence gets more steps. router.post('/installs/storage-request', updateRequestLimiter, async (req, res) => { try { const install = await signedInstall(req, res); if (!install) return; if (install.product !== 'website') return fail(res, 409, 'WRONG_PRODUCT', 'Only a Church Website has storage to add.'); const body = bodyFor(req, res, hub.storageRequestSchema); if (!body) return; const settings = await getSettings(); const withCustomer = await prisma.install.findUnique({ where: { id: install.id }, include: { customer: true } }); const reply = await storage.storageRequested(prisma, withCustomer || install, body, { alertEmail: settings.alert_email, sendMail }); res.status(reply.alreadyRequested ? 200 : 201).json(reply); } catch (e) { console.error('[storage-request]', e); fail(res, 500, 'SERVER_ERROR', 'The Hub could not record the request. Try again later.'); } }); // A site admin pressed "Request update": open an alert (emailed once) until the install reports a // newer version. Asking again while a request is open doesn't email again. 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 = (await latestVersions())[install.product] || null; 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.'); } // Hub 2.0: the update may need the church's other products updated first. const unmet = await unmetRequirementsFor({ ...install, version: current }, latest); if (unmet.length) { return res.status(409).json({ code: 'REQUIREMENT_NOT_MET', message: `This update needs another product first. ${requirementMessage(unmet)}`, requirements: unmet }); } const customerName = async () => (await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } }))?.name || install.name; const link = `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`; const open = await prisma.installEvent.findFirst({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, orderBy: { createdAt: 'desc' } }); if (open) { // Asked for a version that has since been overtaken: the request moves on to the latest one // (Joshua is told once). Otherwise nothing changes and nobody is emailed again. if (!isOutdated(open.message, latest)) { return res.json({ requestedAt: open.createdAt.toISOString(), version: latest, alreadyRequested: true, changed: false }); } const previous = requestedVersionOf(open.message); const now = new Date(); await prisma.installEvent.update({ where: { id: open.id }, data: { message: requestMessage(current, latest, previous) } }); if (settings.alert_email) { const name = await customerName(); await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update request changed by ${name}`, ...updateRequestEmail({ heading: `${name} changed their update request`, note: { note: { kind: 'info', text: `${name} now asks to be updated to ${latest}${previous ? ` instead of ${previous}` : ''}.` } }, rows: [['Church', name], ['Site', install.url], ['Running', current], ['Wants', latest]], link, }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } return res.json({ requestedAt: now.toISOString(), version: latest, alreadyRequested: true, changed: true, previousVersion: previous }); } const event = await prisma.installEvent.create({ data: { installId: install.id, type: 'update_requested', level: 'warning', message: requestMessage(current, latest) } }); if (settings.alert_email) { const name = await customerName(); await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update requested by ${name}`, ...updateRequestEmail({ heading: `${name} would like an update`, note: { note: { kind: 'info', text: `${name} asked to be updated from ${current} to ${latest}.` } }, rows: [['Church', name], ['Site', install.url], ['Running', current], ['Wants', latest]], link, }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } res.status(201).json({ requestedAt: event.createdAt.toISOString(), version: latest, alreadyRequested: false, changed: false }); } catch (e) { console.error('[update-request]', e); fail(res, 500, 'SERVER_ERROR', 'The Hub could not record the update request. Try again later.'); } }); // A site admin withdrew their update request: resolve the open request, and tell Joshua if he was // emailed about it, so he doesn't update the site after all. router.post('/installs/update-request/cancel', updateRequestLimiter, async (req, res) => { 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 } }); if (!open.length) return res.json({ cancelled: false }); await prisma.installEvent.updateMany({ where: { id: { in: open.map(e => e.id) } }, data: { resolvedAt: now } }); await prisma.installEvent.create({ data: { installId: install.id, type: 'update_request_withdrawn', level: 'info', message: 'Update request withdrawn by the site', resolvedAt: now } }); const settings = await getSettings(); if (settings.alert_email) { const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } }); await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update request withdrawn by ${customer?.name || install.name}`, ...updateRequestEmail({ heading: `${customer?.name || install.name} withdrew their update request`, note: { note: { kind: 'success', text: 'No need to update the site for now.' } }, rows: [['Church', customer?.name || install.name], ['Site', install.url]], link: `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`, }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } res.json({ cancelled: true }); } catch (e) { console.error('[update-request/cancel]', e); fail(res, 500, 'SERVER_ERROR', 'The Hub could not withdraw the update request. Try again later.'); } }); // ─── AI (Cross Events 2.0, §3b) ─────────────────────────────────────────────── // What the install's AI buttons should do: hidden, working, or disabled until the allowance renews. 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); fail(res, 500, 'SERVER_ERROR', 'The Hub could not check the AI allowance.'); } }); // One helper call: the Hub adds the key, checks the cap, calls Claude and meters the call. router.post('/installs/ai/complete', aiLimiter, async (req, res) => { let install; try { install = await signedInstall(req, res); if (!install) return; 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); fail(res, 500, 'SERVER_ERROR', 'The Hub could not run this AI request.'); } }); module.exports = router; module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;