/** * The Website and the Hub (docs/hub-protocol.md §6, protocol v2, product `website`), as Accounts' * hub/client.ts: register with a `CCW-` licence key (by itself from HUB_LICENCE_KEY on a Hub * install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's * `linkedProducts` (the church's other installs) is cached for Connect, and the Website connects * itself to the church's Accounts once the Hub lists it (links/connect.ts). * * The install id the Hub gives is also this site's OIDC client id at Accounts. */ import crypto from 'node:crypto'; import { hub } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { appVersion } from '../lib/version.js'; import { connectAccountsIfListed } from '../links/connect.js'; import { keyPair, saveLinkedProducts } from '../links/store.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { storage } from '../admin/media.js'; import { lastBackupAt } from '../backups/backups.js'; import { jobsHealth } from '../jobs.js'; export const PROTOCOL_VERSION = 2; const TIMEOUT_MS = 15000; const DAY = 24 * 60 * 60 * 1000; const STARTED_AT = Date.now(); /** 5 GB included (ROADMAP-v3 §10); the licence's `limits.storageBytes` says more when steps were bought. */ export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3; export class HubError extends Error { constructor(message: string, public code: string, public status: number) { super(message); } } async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise> { const raw = JSON.stringify(body); const headers: Record = { 'Content-Type': 'application/json' }; if (sign) { const timestamp = ctx.now().toISOString(); headers['X-Hub-Install'] = sign.installId; headers['X-Hub-Timestamp'] = timestamp; headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex'); } let res: Response; try { res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) }); } catch (e) { throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502); } const data = (await res.json().catch(() => ({}))) as Record; if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status); return data; } export async function dbUp(ctx: Ctx): Promise { try { await ctx.db.$queryRaw`SELECT 1`; return true; } catch { return false; } } export async function health(ctx: Ctx) { return { uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000), db: await dbUp(ctx), // 1.4.0: the real job mode and failures, and the newest backup (before: always null, so the // Hub warned "No backup reported"). jobs: await jobsHealth(ctx), lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null, disk: null, errorsLast24h: null, pendingMigrations: 0, }; } /** Aggregate counts only (hub.websiteStatsSchema): never anyone's details. */ export async function stats(ctx: Ctx) { const now = ctx.now(); const since = new Date(now.getTime() - 30 * DAY); const [published, drafts, total, last30d, upcomingSimple, imported, editors, media] = await Promise.all([ ctx.db.siteVersion.count(), ctx.db.page.count({ where: { archivedAt: null } }), ctx.db.message.count({ where: { hidden: false } }), ctx.db.message.count({ where: { hidden: false, date: { gte: since } } }), ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }), ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }), ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }), storage(ctx), ]); return { // Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions). pages: { published: published > 0 ? drafts : 0, drafts: published > 0 ? 0 : drafts }, messages: { total, last30d }, events: { upcomingSimple, imported }, editors, // The limit the licence gives (5 GB plus steps bought): the Hub emails the church's admin at // 80% and 100% (decision 12). storage: { usedBytes: media.usedBytes, includedBytes: media.limitBytes }, }; } /** Register with a licence key (HUB_LICENCE_KEY). */ export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) { if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('WEBSITE_URL isn\'t set.', 'NO_SITE_URL', 400); const { publicKeyPem } = await keyPair(ctx); const body = { protocolVersion: PROTOCOL_VERSION, licenceKey: licenceKey.trim().toUpperCase(), product: 'website', install: { name: 'Website', url: ctx.config.publicUrl, adminContact, version: appVersion(), timezone: ctx.config.timezone, server: { node: process.versions.node, postgres: null, os: `${process.platform}` }, features: {}, publicKey: publicKeyPem, }, }; const check = hub.registerRequestSchema.safeParse(body); if (!check.success) throw new HubError('That doesn\'t look like a Website licence key (CCW-…).', 'INVALID_REQUEST', 400); const data = await post(ctx, '/api/installs/register', check.data); const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx)); if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502); await ctx.settings.setMany({ hub_install_id: String(data.installId), hub_install_secret: String(data.installSecret), hub_licence: String(data.licence), hub_last_heartbeat_at: ctx.now().toISOString(), hub_last_error: null, hub_public_key_status: 'matches', }); await saveLinkedProducts(ctx, data.linkedProducts); await connectAccountsIfListed(ctx); return claims; } /** The heartbeat (every 15 minutes). Skips quietly when not connected. */ export async function heartbeat(ctx: Ctx) { const installId = await ctx.settings.get('hub_install_id'); const secret = await ctx.settings.get('hub_install_secret'); if (!installId || !secret) return { skipped: 'not connected' }; const status = await ctx.settings.get('hub_public_key_status'); const { publicKeyPem } = await keyPair(ctx); const body = { protocolVersion: PROTOCOL_VERSION, product: 'website', version: appVersion(), health: await health(ctx), stats: await stats(ctx), ...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }), }; try { const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret }); const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx)); await ctx.settings.setMany({ ...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}), hub_last_heartbeat_at: ctx.now().toISOString(), hub_last_error: null, ...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}), }); await saveLinkedProducts(ctx, data.linkedProducts); await connectAccountsIfListed(ctx); return { ok: true }; } catch (e) { const err = e as HubError; await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500)); if (err.code === 'INSTALL_NOT_FOUND') { await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null }); return { ok: false, reconnect: true }; } throw e; } } /** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */ export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) { const key = ctx.config.hubLicenceKey; if (!key) return { connected: false, reason: 'no_key' }; for (let i = 1; i <= attempts; i++) { try { if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' }; await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null); return { connected: true }; } catch (e) { const err = e as HubError; console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message); if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code }; if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.()); } } return { connected: false, reason: 'unreachable' }; } /** * "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more * 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer. */ export async function requestStorage(ctx: Ctx, steps: number, requestedBy: string | null, now: { usedBytes: number; limitBytes: number }) { const installId = await ctx.settings.get('hub_install_id'); const secret = await ctx.settings.get('hub_install_secret'); if (!installId || !secret) throw new HubError('This site isn\'t connected to the Hub yet, so it can\'t ask for more storage.', 'NOT_CONNECTED', 503); const body = hub.storageRequestSchema.parse({ protocolVersion: PROTOCOL_VERSION, steps, usedBytes: now.usedBytes, limitBytes: now.limitBytes, requestedBy }); const data = await post(ctx, '/api/installs/storage-request', body, { installId, secret }); const reply = hub.storageRequestResponseSchema.safeParse(data); if (!reply.success) throw new HubError('The Hub answered in a way this site doesn\'t understand.', 'BAD_REPLY', 502); return reply.data; }