Files
crosscode-platform/packages/contracts/src/hub.ts
T
joshuaandClaude Opus 5.5 ea1575f716 Contracts: event, event feed, church, identity, sign-in return, Hub protocol v2
- crosscode.event/1 and crosscode.event-feed/1 (feed, event.changed
  webhook), with session and registration rules; parseEventFeed skips
  and reports bad events instead of failing the whole feed.
- crosscode.church/1: branding, campuses, service times, contact, links.
- crosscode.identity/1: sign-in claims and the user.updated /
  user.deleted / user.export back-channel calls and replies.
- Sign-in return helpers (isSafeReturnPath, encodeState/decodeState,
  isRegisteredRedirectUri) so every product returns people to the page
  they came from in the same safe way.
- Hub protocol v2: product on register/heartbeat, stats per product,
  install public key, linked products, customerId/product in licences.
- @crosscode/contracts/signing (Node only): the Hub's HMAC scheme.
- Samples for every contract in samples/, checked by the tests (120).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:40 +02:00

308 lines
13 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 `hope-events/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();
export const releaseSchema = z.object({
version: semverSchema,
releasedAt: dateTimeSchema,
urgent: z.boolean(),
notes: z.string(),
});
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,
}),
});
/** 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 });
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 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,
});
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,
});
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>;