Files
crosscode-platform/packages/contracts/src/hub.ts
T
joshuaandClaude Opus 5.5 08b58ae310 Events 3.5.0, contracts 1.13.0, agent 1.3.1: demo data keeps the Accounts link; sign-in health for the Hub
- Events: loading demo data emptied ProductLink but kept auth_mode, so a site in Accounts mode had
  no link and nobody could sign in (ACCOUNTS_UNAVAILABLE on events-demo). set-demo.js keeps
  ProductLink and LinkNonce; a site in Accounts mode without a link reconnects at its next
  heartbeat; sign-in failures are kept and sent in the heartbeat (stats.signIn).
- Contracts 1.13.0: stats.signIn in the Cross Events heartbeat.
- Agent 1.3.1: 1.3.0 reported itself as 1.2.0 (AGENT_VERSION not bumped).
- What's New notes for Events 3.4.0 / 3.5.0 and Accounts 1.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:56:37 +02:00

361 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { z } from "zod";
import { dateSchema, dateTimeSchema, emailSchema, idSchema, productSchema, semverSchema, timezoneSchema, urlSchema } from "./common";
import { TWO_FACTOR_METHODS } from "./identity";
/**
* Hub protocol v2 — between every Cross Code install and Cross Code Hub (ROADMAP-v3 §5).
* Protocol v1 is the one in `docs/hub-protocol.md` (Cross Events 2.1, Hub 1.7).
*
* What v2 changes:
* - `product` on register and heartbeat; the heartbeat's `stats` depend on the product.
* - Register sends the install's Ed25519 `publicKey`, so its siblings can verify it when they
* Connect (Settings → Linked products).
* - The register and heartbeat replies list the church's other installs (`linkedProducts`).
* - The licence token carries `customerId` and `product`.
*
* Unchanged from v1: install → Hub only, no personal information (aggregate counts and bands),
* signed requests (`HUB_HEADERS` in `@crosscode/contracts/signing`), offline licence checks,
* update requests and AI calls. The Hub accepts v2 and v1, so Events installs keep reporting
* until they update.
*/
export const HUB_PROTOCOL_VERSION = 2;
/** The Hub accepts the current and the previous version (`400 UNSUPPORTED_PROTOCOL` otherwise). */
export const HUB_PROTOCOL_VERSIONS = [1, 2] as const;
const protocolVersion = z.literal(HUB_PROTOCOL_VERSION);
export const hubErrorSchema = z.object({ message: z.string(), code: z.string().regex(/^[A-Z][A-Z0-9_]*$/) });
export type HubError = z.infer<typeof hubErrorSchema>;
// ---------------------------------------------------------------------------------------------
// Bands: amounts and member counts never leave the install, only the band they fall in.
// ---------------------------------------------------------------------------------------------
/** Income bands (as Cross Events 2.0.2+); every licence-tier edge is a band edge. */
export const INCOME_BANDS = [
"R0–R1 000",
"R1 001–R5 000",
"R5 001–R20 000",
"R20 001–R50 000",
"R50 001–R100 000",
"R100 001–R150 000",
"R150 001–R250 000",
"R250 001–R400 000",
"R400 001–R700 000",
"R700 001–R1 000 000",
"R1 000 001–R2 500 000",
"R2 500 001–R5 000 000",
"R5 000 001–R10 000 000",
"over R10 000 000",
] as const;
export const incomeBandSchema = z.enum(INCOME_BANDS);
/** Active-member bands for the Church App, one per pricing tier (ROADMAP-v3 §10). */
export const ACTIVE_MEMBER_BANDS = ["0–100", "101–300", "301–750", "751–2 000", "2 001–5 000", "over 5 000"] as const;
export const activeMemberBandSchema = z.enum(ACTIVE_MEMBER_BANDS);
/** The band for an active-member count (accounts that used the App in the last 90 days). */
export function activeMemberBand(count: number): (typeof ACTIVE_MEMBER_BANDS)[number] {
if (count <= 100) return "0–100";
if (count <= 300) return "101–300";
if (count <= 750) return "301–750";
if (count <= 2000) return "751–2 000";
if (count <= 5000) return "2 001–5 000";
return "over 5 000";
}
// ---------------------------------------------------------------------------------------------
// Shared pieces
// ---------------------------------------------------------------------------------------------
const count = z.int().nonnegative();
/** A minimum version of a sibling product that a release needs (`— requires accounts 1.2.0`). */
export const releaseRequirementSchema = z.object({ product: productSchema, version: semverSchema });
export type ReleaseRequirement = z.infer<typeof releaseRequirementSchema>;
export const releaseSchema = z.object({
version: semverSchema,
releasedAt: dateTimeSchema,
urgent: z.boolean(),
notes: z.string(),
/**
* contracts 1.1.0 (Hub 2.0): the sibling versions this release needs. The Hub refuses an update
* request (`409 REQUIREMENT_NOT_MET`) until the church's install of each product runs at least
* that version. Optional: absent from Hubs before 2.0 and from protocol v1 replies.
*/
requires: z.array(releaseRequirementSchema).optional(),
});
export const noticeSchema = z.object({
id: z.string(),
level: z.enum(["info", "maintenance", "warning"]),
title: z.string(),
message: z.string(),
startsAt: dateTimeSchema.nullable(),
endsAt: dateTimeSchema.nullable(),
updatedAt: dateTimeSchema,
});
/** One of the church's other installs, as the Hub lists it. Nothing else about it is shared. */
export const linkedProductSchema = z.object({
product: productSchema,
installId: idSchema,
url: urlSchema,
/** The install's Ed25519 public key (PEM), sent when it registered. */
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----"),
});
export type LinkedProduct = z.infer<typeof linkedProductSchema>;
export const healthSchema = z.object({
uptimeSeconds: count,
db: z.boolean(),
jobs: z.object({ mode: z.string(), failedLast24h: count }),
lastBackupAt: dateTimeSchema.nullable(),
disk: z.object({ freeBytes: count, totalBytes: count }).nullable(),
errorsLast24h: count.nullable(),
pendingMigrations: count,
});
export type Health = z.infer<typeof healthSchema>;
// ---------------------------------------------------------------------------------------------
// GET /api/public-key
// ---------------------------------------------------------------------------------------------
export const publicKeyResponseSchema = z.object({
protocolVersions: z.array(z.int().positive()),
keyId: z.string(),
algorithm: z.literal("Ed25519"),
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----"),
});
// ---------------------------------------------------------------------------------------------
// POST /api/installs/register
// ---------------------------------------------------------------------------------------------
export const registerRequestSchema = z.object({
protocolVersion,
/** Product licence keys: `CEH-…` (Events), and the new products' prefixes from Hub 2.0. */
licenceKey: z.string().regex(/^[A-Z]{3}(-[A-Z0-9]{4}){4}$/, "Expected a licence key like CEH-7K2M-9QXA-P4RT-WD8C"),
/** Must match the licence's product (`409 WRONG_PRODUCT` otherwise). */
product: productSchema,
install: z.object({
name: z.string().trim().min(1).max(200),
url: urlSchema,
/** The one piece of personal information: a work contact for the church's admin. */
adminContact: z.object({ name: z.string().max(200).nullable(), email: emailSchema.nullable() }).nullable(),
version: semverSchema,
timezone: timezoneSchema,
server: z.object({ node: z.string(), postgres: z.string().nullable(), os: z.string() }),
/** Product-specific switches, e.g. Events: `{ whatsapp, paymentProviders, campuses }`. */
features: z.record(z.string(), z.union([z.boolean(), z.string(), z.number(), z.array(z.string())])),
/** The install's Ed25519 public key (PEM). Its private key never leaves the install. */
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----"),
}),
});
export type RegisterRequest = z.infer<typeof registerRequestSchema>;
export const registerResponseSchema = z.object({
installId: idSchema,
/** Shown once; the install stores it encrypted. */
installSecret: z.string().min(32),
licence: z.string(),
heartbeatIntervalMinutes: z.int().positive(),
latestVersion: semverSchema.nullable(),
releases: z.array(releaseSchema),
notices: z.array(noticeSchema),
linkedProducts: z.array(linkedProductSchema),
});
export type RegisterResponse = z.infer<typeof registerResponseSchema>;
// ---------------------------------------------------------------------------------------------
// POST /api/installs/heartbeat — `stats` per product
// ---------------------------------------------------------------------------------------------
/** Cross Events: the same stats as protocol v1. */
export const eventsStatsSchema = z.object({
users: count,
events: z.object({ active: count, upcoming: count, total: count }),
registrations: z.object({ last30d: count, total: count }),
tickets: z.object({ last30d: count, total: count }),
checkIns: z.object({ last30d: count }),
messages: z.object({ email30d: count, whatsapp30d: count }).nullable(),
paymentProviders: z.array(z.string()),
campuses: z.boolean(),
campusCount: count,
income: z.object({
last30d: incomeBandSchema,
allTime: incomeBandSchema,
/** What the Events licence tier is billed on. */
eventIncome12m: incomeBandSchema,
}),
/**
* 1.10.0: what's happening now, so the Hub can warn before taking the site down (an emergency
* update "as soon as possible"): events with a session or a one-day event on now (give or take
* 30 minutes), and tickets checked in during the last hour. Optional: older installs don't send it.
*/
live: z.object({ eventsNow: count, checkInsLastHour: count }).optional(),
/**
* 1.13.0: how people sign in, so the Hub can flag a site that can't. `mode`: Cross Events' own
* sign-in or the church's Accounts; `accounts`: the Accounts install it's linked to (null: not
* linked, which with mode `accounts` means nobody can sign in); `lastError`: the last time
* starting or finishing a sign-in failed (cleared by the next one that works). Optional: older
* installs don't send it.
*/
signIn: z.object({
mode: z.enum(["local", "accounts"]),
accounts: z.object({ installId: z.string().max(100), url: z.string().max(500) }).nullable(),
lastError: z.object({ at: dateTimeSchema, code: z.string().max(60), message: z.string().max(500) }).nullable(),
}).optional(),
});
/** Church Website. `storage` is what the extra-storage add-on is billed on (ROADMAP-v3 §10). */
export const websiteStatsSchema = z.object({
pages: z.object({ published: count, drafts: count }),
messages: z.object({ total: count, last30d: count }),
events: z.object({ upcomingSimple: count, imported: count }),
editors: count,
storage: z.object({ usedBytes: count, includedBytes: count }),
});
/** Church App. `activeMembers90d` is what the App tier is billed on. */
export const appStatsSchema = z.object({
activeMembers90d: activeMemberBandSchema,
modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)),
prayer: z.object({
/** Share of the last 7 days' hours with at least one commitment, 0–100. */
coverageLast7dPercent: z.number().min(0).max(100),
activeCommitments: count,
}),
announcements: z.object({ last30d: count }),
messages: z.object({ email30d: count, whatsapp30d: count }),
});
/** Accounts. No charge of its own; reported for health and support. */
export const accountsStatsSchema = z.object({
accounts: z.object({ total: count, active90d: count }),
twoFactor: z.object(Object.fromEntries([...TWO_FACTOR_METHODS, "off"].map((m) => [m, count])) as Record<(typeof TWO_FACTOR_METHODS)[number] | "off", typeof count>),
linkedProducts: count,
});
const heartbeatBase = z.object({
protocolVersion,
version: semverSchema,
health: healthSchema,
/**
* The install's Ed25519 public key (PEM), contracts 1.4.0 / Hub 2.2.0. Lets an install that
* registered with protocol v1 move to v2 without its licence key (the heartbeat is already
* signed with the install secret). The Hub saves it when the install has none; see
* `publicKeyStatus` in the reply.
*/
publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----").optional(),
});
export const heartbeatRequestSchema = z.discriminatedUnion("product", [
heartbeatBase.extend({ product: z.literal("events"), stats: eventsStatsSchema }),
heartbeatBase.extend({ product: z.literal("website"), stats: websiteStatsSchema }),
heartbeatBase.extend({ product: z.literal("app"), stats: appStatsSchema }),
heartbeatBase.extend({ product: z.literal("accounts"), stats: accountsStatsSchema }),
]);
export type HeartbeatRequest = z.infer<typeof heartbeatRequestSchema>;
export const PUBLIC_KEY_STATUSES = ["saved", "matches", "mismatch"] as const;
export const heartbeatResponseSchema = z.object({
licence: z.string(),
latestVersion: semverSchema.nullable(),
releases: z.array(releaseSchema),
notices: z.array(noticeSchema),
/** The church's other installs. The install caches this, so a Hub outage changes nothing. */
linkedProducts: z.array(linkedProductSchema),
serverTime: dateTimeSchema,
/**
* Only when the heartbeat sent `publicKey` (Hub 2.2.0+): `saved` (the Hub had none),
* `matches`, or `mismatch` (the Hub has another key; it keeps its own and flags the install
* until Joshua clears it). Never a failed heartbeat: the licence keeps refreshing either way.
*/
publicKeyStatus: z.enum(PUBLIC_KEY_STATUSES).optional(),
});
export type HeartbeatResponse = z.infer<typeof heartbeatResponseSchema>;
// ---------------------------------------------------------------------------------------------
// Update requests (as v1)
// ---------------------------------------------------------------------------------------------
export const updateRequestSchema = z.object({ protocolVersion, version: semverSchema });
export const updateRequestResponseSchema = z.object({
requestedAt: dateTimeSchema,
version: semverSchema,
alreadyRequested: z.boolean(),
changed: z.boolean(),
previousVersion: semverSchema.optional(),
});
export const updateRequestCancelSchema = z.object({ protocolVersion });
export const updateRequestCancelResponseSchema = z.object({ cancelled: z.boolean() });
// ---------------------------------------------------------------------------------------------
// AI (as v1; usage is recorded per product on the Hub, the cap stays per customer)
// ---------------------------------------------------------------------------------------------
export const aiStatusRequestSchema = z.object({ protocolVersion });
export const aiStatusSchema = z.object({
enabled: z.boolean(),
capReached: z.boolean(),
capCents: z.number().nonnegative(),
usedCents: z.number().nonnegative(),
usedPercent: z.number().nonnegative(),
renewsOn: dateSchema,
// Hub 2.0.1: tokens, which is what churches see (the cents are for the Hub and older installs).
// The allowance is approximate: half the cap priced as input, half as output.
usedInputTokens: count.optional(),
usedOutputTokens: count.optional(),
capInputTokens: count.optional(),
capOutputTokens: count.optional(),
});
export type AiStatus = z.infer<typeof aiStatusSchema>;
export const aiCompleteRequestSchema = z.object({
protocolVersion,
helper: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60),
system: z.string(),
input: z.string(),
schema: z.record(z.string(), z.unknown()).optional(),
maxTokens: z.int().min(1).max(8000),
effort: z.enum(["low", "medium", "high"]).optional(),
});
export const aiCompleteResponseSchema = z.object({
output: z.union([z.string(), z.record(z.string(), z.unknown())]),
usage: z.object({ inputTokens: count, outputTokens: count }),
chargedCents: z.number().nonnegative(),
status: aiStatusSchema,
});
// ---------------------------------------------------------------------------------------------
// Licence token: `hel1.<base64url payload>.<base64url Ed25519 signature of "hel1.<payload>">`
// ---------------------------------------------------------------------------------------------
export const LICENCE_STATUSES = ["active", "suspended", "revoked"] as const;
/**
* The token's payload. Still `v: 1` — `customerId` and `product` are new optional fields (old
* Hubs don't send them); a Hub 2.0 token always has both, and an install refuses a token for
* another product.
*/
export const licencePayloadSchema = z.object({
v: z.literal(1),
licenceId: idSchema,
installId: idSchema,
customerId: idSchema.optional(),
product: productSchema.optional(),
customer: z.string(),
plan: z.string(),
status: z.enum(LICENCE_STATUSES),
licenceExpiresAt: dateTimeSchema.nullable(),
graceDays: z.int().nonnegative(),
issuedAt: dateTimeSchema,
validUntil: dateTimeSchema,
limits: z.object({ aiMonthlyCapCents: z.number().nonnegative() }),
});
export type LicencePayload = z.infer<typeof licencePayloadSchema>;