crosscode: scripts/products/website.sh (ports 5300/3300, uploads in the export), crosscode add <church> website (needs Accounts; www.<address> or the Cross Code address), one install_app for Accounts and the Website, env template copy, bats tests. Backend: Hub client (protocol v2, product website), crosscode.link/1 with automatic connect to the church's Accounts, sign-in through @crosscode/auth-client with the Website's own session and roles, the first Owner from HUB_ADMIN_EMAIL (verified), 2FA for Owners and Admins, back-channel logout, Accounts' user.* calls, and the church export. Frontend: admin sign-in/out and the sign-in problem page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
199 lines
8.8 KiB
TypeScript
199 lines
8.8 KiB
TypeScript
/**
|
|
* 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';
|
|
|
|
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<Record<string, unknown>> {
|
|
const raw = JSON.stringify(body);
|
|
const headers: Record<string, string> = { '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<string, unknown>;
|
|
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<boolean> {
|
|
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),
|
|
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
|
lastBackupAt: 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' } } }),
|
|
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
|
]);
|
|
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,
|
|
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
|
|
};
|
|
}
|
|
|
|
/** 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' };
|
|
}
|
|
|
|
/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */
|
|
export function startHeartbeats(ctx: Ctx): () => void {
|
|
if (!ctx.config.jobsEnabled) return () => {};
|
|
const timer = setInterval(() => {
|
|
heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message));
|
|
}, 15 * 60 * 1000);
|
|
timer.unref?.();
|
|
return () => clearInterval(timer);
|
|
}
|