/** * Accounts and the Hub (docs/hub-protocol.md §6, protocol v2 from the start, product `accounts`): * register with a `CCA-` licence key (from `/setup`, or 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. */ import crypto from 'node:crypto'; import { hub } from '@crosscode/contracts'; import type { Ctx } from '../context.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { keyPair, saveLinkedProducts } from '../links/store.js'; import { appVersion } from '../lib/version.js'; import { lastBackupAt } from '../backups/backups.js'; export const PROTOCOL_VERSION = 2; const TIMEOUT_MS = 15000; const DAY = 24 * 60 * 60 * 1000; const STARTED_AT = Date.now(); 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; } const version = appVersion; export async function health(ctx: Ctx) { let db = true; try { await ctx.db.$queryRawUnsafe('SELECT 1'); } catch { db = false; } return { uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000), db, jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 }, lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null, disk: null, errorsLast24h: null, pendingMigrations: 0, }; } /** Aggregate counts only (hub.accountsStatsSchema): never anyone's details. */ export async function stats(ctx: Ctx) { const since = new Date(ctx.now().getTime() - 90 * DAY); const active = { status: 'active' as const }; const [total, active90d, email, whatsapp, totp, off, links] = await Promise.all([ ctx.db.account.count({ where: active }), ctx.db.account.count({ where: { ...active, lastSignInAt: { gte: since } } }), ctx.db.account.count({ where: { ...active, twoFactorMethod: 'email' } }), ctx.db.account.count({ where: { ...active, twoFactorMethod: 'whatsapp' } }), ctx.db.account.count({ where: { ...active, twoFactorMethod: 'totp' } }), ctx.db.account.count({ where: { ...active, twoFactorMethod: null } }), ctx.db.productLink.count(), ]); return { accounts: { total, active90d }, twoFactor: { email, whatsapp, totp, off }, linkedProducts: links }; } /** Register with a licence key (from /setup or 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('ACCOUNTS_URL isn\'t set.', 'NO_SITE_URL', 400); const { publicKeyPem } = await keyPair(ctx); const profile = await ctx.settings.json<{ name?: string }>('church_profile', {}); const body = { protocolVersion: PROTOCOL_VERSION, licenceKey: licenceKey.trim().toUpperCase(), product: 'accounts', install: { name: profile.name || 'Accounts', url: ctx.config.publicUrl, adminContact, version: version(), timezone: ctx.config.timezone, server: { node: process.versions.node, postgres: null, os: `${process.platform}` }, features: { whatsapp: await ctx.messenger.whatsappReady() }, publicKey: publicKeyPem, }, }; const check = hub.registerRequestSchema.safeParse(body); if (!check.success) throw new HubError(`That doesn't look like an Accounts licence key (CCA-…).`, '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); return claims; } /** The `hub-heartbeat` job. 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: 'accounts', version: version(), 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); 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 (as Events 2.3). 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' }; }