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>
This commit is contained in:
2026-11-04 09:47:40 +02:00
co-authored by Claude Opus 5.5
parent 19f79dfb17
commit ea1575f716
37 changed files with 1889 additions and 23 deletions
+99
View File
@@ -0,0 +1,99 @@
import { z } from "zod";
import { dateTimeSchema, emailSchema, hexColourSchema, idSchema, phoneSchema, slugSchema, timeOfDaySchema, timezoneSchema, urlSchema } from "./common";
import { schemaName } from "./schema-name";
/**
* `crosscode.church/1` — the church profile, set once and shared by every product of a church
* (ROADMAP-v3 §2): name, logo, colours, campuses, service times and contact details. The Website,
* App and Accounts' sign-in page are branded from it.
*
* Public information only: the church's own contact details, never a person's.
*/
export const CHURCH_SCHEMA = schemaName("church", 1);
export const WEEKDAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] as const;
export const SOCIAL_NETWORKS = ["facebook", "instagram", "youtube", "tiktok", "x", "spotify", "whatsapp-channel", "other"] as const;
export const addressSchema = z.object({
line1: z.string().trim().min(1).max(200),
line2: z.string().trim().max(200).nullable(),
suburb: z.string().trim().max(100).nullable(),
city: z.string().trim().min(1).max(100),
province: z.string().trim().max(100).nullable(),
postalCode: z.string().trim().max(20).nullable(),
/** ISO 3166-1 alpha-2, e.g. `ZA`. */
country: z.string().regex(/^[A-Z]{2}$/, "Expected an ISO 3166-1 alpha-2 code"),
/** For a map pin. */
geo: z.object({ lat: z.number().min(-90).max(90), lng: z.number().min(-180).max(180) }).nullable(),
});
export type Address = z.infer<typeof addressSchema>;
export const campusSchema = z.object({
slug: slugSchema,
name: z.string().trim().min(1).max(200),
address: addressSchema.nullable(),
});
export const serviceTimeSchema = z.object({
day: z.enum(WEEKDAYS),
/** Local time in the church's timezone. */
time: timeOfDaySchema,
/** E.g. "Morning service", "Afrikaans service". */
label: z.string().trim().max(100).nullable(),
/** The campus's slug, or `null` when the church has no campuses. */
campus: slugSchema.nullable(),
/** E.g. "Kids church during the service". */
note: z.string().trim().max(300).nullable(),
});
export const churchSchema = z
.object({
schema: z.literal(CHURCH_SCHEMA),
/** The Hub customer id: the same for every product of the church. */
customerId: idSchema,
updatedAt: dateTimeSchema,
name: z.string().trim().min(1).max(200),
/** For tight spaces (app icon label, sign-in page title). */
shortName: z.string().trim().max(30).nullable(),
timezone: timezoneSchema,
/** BCP 47, e.g. `en-ZA`. */
locale: z.string().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/, "Expected a BCP 47 locale like en-ZA"),
branding: z.object({
logoUrl: urlSchema.nullable(),
/** Square, at least 512×512: app icon and favicon. */
iconUrl: urlSchema.nullable(),
colours: z.object({
primary: hexColourSchema,
accent: hexColourSchema.nullable(),
}),
}),
/** Empty when campuses are off. */
campuses: z.array(campusSchema).max(50),
serviceTimes: z.array(serviceTimeSchema).max(100),
contact: z.object({
email: emailSchema.nullable(),
phone: phoneSchema.nullable(),
whatsapp: phoneSchema.nullable(),
address: addressSchema.nullable(),
}),
social: z.array(z.object({ network: z.enum(SOCIAL_NETWORKS), url: urlSchema })).max(20),
/** The church's products, so each can link to the others. */
links: z.object({
website: urlSchema.nullable(),
events: urlSchema.nullable(),
app: urlSchema.nullable(),
accounts: urlSchema,
}),
})
.superRefine((church, ctx) => {
const slugs = new Set(church.campuses.map((c) => c.slug));
if (slugs.size !== church.campuses.length) ctx.addIssue({ code: "custom", path: ["campuses"], message: "Campus slugs must be unique" });
church.serviceTimes.forEach((s, i) => {
if (s.campus !== null && !slugs.has(s.campus)) ctx.addIssue({ code: "custom", path: ["serviceTimes", i, "campus"], message: `Unknown campus "${s.campus}"` });
});
});
export type Church = z.infer<typeof churchSchema>;
export type Campus = z.infer<typeof campusSchema>;
export type ServiceTime = z.infer<typeof serviceTimeSchema>;
+57
View File
@@ -0,0 +1,57 @@
import { z } from "zod";
/**
* Building blocks shared by the contracts. Objects strip fields they don't know instead of
* failing, so a newer producer that adds an optional field never breaks an older consumer
* (ROADMAP-v3 §2, "Versioning").
*/
/** The products of a church stack (ROADMAP-v3 §1). */
export const PRODUCTS = ["events", "website", "app", "accounts"] as const;
export const productSchema = z.enum(PRODUCTS);
export type Product = z.infer<typeof productSchema>;
/** The products that publish and show events (Accounts has none). */
export const EVENT_PRODUCTS = ["events", "website", "app"] as const;
export const eventProductSchema = z.enum(EVENT_PRODUCTS);
export type EventProduct = z.infer<typeof eventProductSchema>;
/** Ids are UUIDs everywhere: records, installs, licences, customers and account `sub`s. */
export const idSchema = z.uuid();
/** An ISO 8601 date-time in UTC, as sent by every product (`2026-11-03T10:00:00.000Z`). */
export const dateTimeSchema = z.iso.datetime();
/** A calendar date (`2026-12-01`). */
export const dateSchema = z.iso.date();
/** A 24-hour clock time (`09:30`). */
export const timeOfDaySchema = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "Expected HH:MM (24-hour)");
/** An IANA timezone name, e.g. `Africa/Johannesburg`. */
export const timezoneSchema = z.string().regex(/^[A-Za-z_]+(\/[A-Za-z0-9_+-]+){0,2}$|^UTC$/, "Expected an IANA timezone");
/** An absolute http(s) URL. Production URLs are https; http is allowed for local development. */
export const urlSchema = z.url({ protocol: /^https?$/ }).max(2048);
/** A web colour: `#rrggbb`. */
export const hexColourSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/, "Expected #rrggbb");
/** A slug: lower-case letters, digits and dashes (`meyerton`, `youth-camp`). */
export const slugSchema = z.string().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, "Expected a lower-case slug").max(100);
/** An amount of money in the smallest unit (cents) with its ISO 4217 currency. */
export const moneySchema = z.object({
amountCents: z.int().nonnegative(),
currency: z.string().regex(/^[A-Z]{3}$/, "Expected an ISO 4217 code"),
});
export type Money = z.infer<typeof moneySchema>;
/** A semantic version (`2.3.0`, `1.0.0-beta.1`). */
export const semverSchema = z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/, "Expected a semantic version");
/** An email address. */
export const emailSchema = z.email().max(254);
/** A phone number in E.164 form (`+27821234567`). */
export const phoneSchema = z.string().regex(/^\+[1-9]\d{6,14}$/, "Expected an E.164 phone number");
+193
View File
@@ -0,0 +1,193 @@
import { z } from "zod";
import { dateTimeSchema, eventProductSchema, idSchema, moneySchema, slugSchema, timezoneSchema, urlSchema } from "./common";
import { schemaName } from "./schema-name";
/**
* `crosscode.event/1` — the event every product publishes and reads (ROADMAP-v3 §4).
*
* Rules the schema enforces:
* - `sessions` is empty for a single-date event; otherwise `startsAt` / `endsAt` are the first
* start and the last end of the (non-cancelled) sessions.
* - Only Cross Events (`origin.product: "events"`) takes registrations, so only it may use
* `registration.mode: "origin"` or a `registration.status` other than `open`.
* - Public events only: nothing in here is personal information.
*/
export const EVENT_SCHEMA = schemaName("event", 1);
export const EVENT_FEED_SCHEMA = schemaName("event-feed", 1);
export const REGISTRATION_MODES = ["origin", "external", "contact", "none"] as const;
export const REGISTRATION_STATUSES = ["open", "not_open", "closed", "full", "waitlist"] as const;
export const EVENT_STATUSES = ["published", "cancelled"] as const;
const textLine = (max: number) => z.string().trim().min(1).max(max);
export const eventOriginSchema = z.object({
/** The product that owns the event. Only it can edit it (ROADMAP-v3 §1, rule 4). */
product: eventProductSchema,
/** The Hub install id of the origin. */
installId: idSchema,
/** The event's public page at the origin; imported copies link here. */
url: urlSchema,
});
export const eventSessionSchema = z.object({
id: idSchema,
label: z.string().trim().max(200).nullable(),
startsAt: dateTimeSchema,
endsAt: dateTimeSchema,
/** Only when it differs from the event's location. */
location: z.string().trim().max(300).nullable(),
cancelled: z.boolean(),
});
export const eventLocationSchema = z.object({
name: z.string().trim().max(200).nullable(),
address: z.string().trim().max(500).nullable(),
onlineUrl: urlSchema.nullable(),
});
export const eventCampusSchema = z.object({ slug: slugSchema, name: textLine(200) });
export const eventSeriesSchema = z.object({ id: idSchema, name: textLine(200) });
export const eventRegistrationSchema = z.object({
/** `origin`: register at the origin (Events only) · `external`: a link · `contact`: instructions in the description · `none`. */
mode: z.enum(REGISTRATION_MODES),
/** Where to register: the origin's page (`origin`) or the external link (`external`). `null` otherwise. */
url: urlSchema.nullable(),
status: z.enum(REGISTRATION_STATUSES),
opensAt: dateTimeSchema.nullable(),
closesAt: dateTimeSchema.nullable(),
/** The lowest current price, or `null` for free / not applicable. */
priceFrom: moneySchema.nullable(),
});
const eventObject = z.object({
schema: z.literal(EVENT_SCHEMA),
/** The origin's id for the event. With `origin.product` it identifies the event everywhere. */
id: idSchema,
origin: eventOriginSchema,
status: z.enum(EVENT_STATUSES),
updatedAt: dateTimeSchema,
title: textLine(200),
summary: z.string().trim().max(300).nullable(),
/** Sanitised markdown. Consumers render it as markdown with HTML switched off. */
description: z.string().max(20000).nullable(),
imageUrl: urlSchema.nullable(),
timezone: timezoneSchema,
startsAt: dateTimeSchema,
endsAt: dateTimeSchema,
allDay: z.boolean(),
sessions: z.array(eventSessionSchema).max(500),
location: eventLocationSchema.nullable(),
/** `null` = all campuses, or campuses are switched off. */
campus: eventCampusSchema.nullable(),
series: eventSeriesSchema.nullable(),
tags: z.array(slugSchema).max(20),
registration: eventRegistrationSchema,
});
export const eventSchema = eventObject.superRefine((event, ctx) => {
const issue = (path: (string | number)[], message: string) => ctx.addIssue({ code: "custom", path, message });
if (Date.parse(event.endsAt) < Date.parse(event.startsAt)) issue(["endsAt"], "endsAt is before startsAt");
event.sessions.forEach((s, i) => {
if (Date.parse(s.endsAt) < Date.parse(s.startsAt)) issue(["sessions", i, "endsAt"], "Session ends before it starts");
});
const live = event.sessions.filter((s) => !s.cancelled);
if (live.length > 0) {
const first = Math.min(...live.map((s) => Date.parse(s.startsAt)));
const last = Math.max(...live.map((s) => Date.parse(s.endsAt)));
if (Date.parse(event.startsAt) !== first) issue(["startsAt"], "startsAt must be the first session's start");
if (Date.parse(event.endsAt) !== last) issue(["endsAt"], "endsAt must be the last session's end");
}
const { registration: r, origin } = event;
if (origin.product !== "events") {
if (r.mode === "origin") issue(["registration", "mode"], "Only Cross Events takes registrations (mode \"origin\")");
if (r.status !== "open") issue(["registration", "status"], "Only Cross Events sends a registration status other than \"open\"");
}
if ((r.mode === "origin" || r.mode === "external") && r.url === null) issue(["registration", "url"], `A "${r.mode}" registration needs a url`);
if ((r.mode === "contact" || r.mode === "none") && r.url !== null) issue(["registration", "url"], `A "${r.mode}" registration has no url`);
if (r.opensAt && r.closesAt && Date.parse(r.closesAt) < Date.parse(r.opensAt)) issue(["registration", "closesAt"], "closesAt is before opensAt");
});
export type CrosscodeEvent = z.infer<typeof eventSchema>;
export type EventSession = z.infer<typeof eventSessionSchema>;
export type EventRegistration = z.infer<typeof eventRegistrationSchema>;
/** An event that was unpublished or deleted at the origin since `updatedSince`. */
export const deletedEventSchema = z.object({
id: idSchema,
deletedAt: dateTimeSchema,
});
/**
* `GET /api/feed/v1/events?updatedSince=<ISO>` → `crosscode.event-feed/1`.
*
* `events` is checked one by one with {@link parseEventFeed}: a single bad event is skipped and
* reported, it never blocks the rest of the feed (ROADMAP-v3 §4, "one failing source never blocks
* another" applies within a feed too).
*/
export const eventFeedSchema = z.object({
schema: z.literal(EVENT_FEED_SCHEMA),
generatedAt: dateTimeSchema,
events: z.array(eventSchema),
deleted: z.array(deletedEventSchema),
});
export type EventFeed = z.infer<typeof eventFeedSchema>;
const feedEnvelopeSchema = eventFeedSchema.extend({ events: z.array(z.unknown()) });
export interface RejectedEvent {
index: number;
/** The event's id, when it had a readable one. */
id: string | null;
issues: z.core.$ZodIssue[];
}
export type ParseEventFeedResult =
| { ok: true; feed: EventFeed; rejected: RejectedEvent[] }
| { ok: false; error: z.ZodError };
/**
* Parses a feed response. The envelope must be valid; each event is checked on its own, and
* invalid ones are left out and listed in `rejected` so the consumer can log them.
*/
export function parseEventFeed(input: unknown): ParseEventFeedResult {
const envelope = feedEnvelopeSchema.safeParse(input);
if (!envelope.success) return { ok: false, error: envelope.error };
const events: CrosscodeEvent[] = [];
const rejected: RejectedEvent[] = [];
envelope.data.events.forEach((raw, index) => {
const parsed = eventSchema.safeParse(raw);
if (parsed.success) events.push(parsed.data);
else {
const id = typeof raw === "object" && raw !== null && typeof (raw as { id?: unknown }).id === "string" ? (raw as { id: string }).id : null;
rejected.push({ index, id, issues: parsed.error.issues });
}
});
return { ok: true, feed: { ...envelope.data, events }, rejected };
}
/**
* The `event.changed` webhook: the origin tells a linked consumer to fetch its feed now instead
* of waiting for the 15-minute poll. Signed with the link's secret (`LINK_HEADERS`). `eventIds`
* is a hint; the consumer always fetches `?updatedSince=` its last sync.
*/
export const eventChangedSchema = z.object({
schema: z.literal(EVENT_FEED_SCHEMA),
type: z.literal("event.changed"),
occurredAt: dateTimeSchema,
eventIds: z.array(idSchema).max(100),
});
export type EventChanged = z.infer<typeof eventChangedSchema>;
/** The key that identifies an event across products: `origin.product` + `id` (ROADMAP-v3 §4, "No duplicates"). */
export function eventKey(event: Pick<CrosscodeEvent, "id" | "origin">): string {
return `${event.origin.product}:${event.id}`;
}
+307
View File
@@ -0,0 +1,307 @@
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>;
+133
View File
@@ -0,0 +1,133 @@
import { z } from "zod";
import { dateTimeSchema, emailSchema, idSchema, phoneSchema, productSchema } from "./common";
import { schemaName } from "./schema-name";
/**
* `crosscode.identity/1` — what Accounts tells the products about a person (ROADMAP-v3 §3):
* the claims in the sign-in token (and userinfo), and the back-channel calls Accounts makes to
* each linked product (`user.updated`, `user.deleted`, `user.export`).
*
* Roles are never in here: each product keeps its own, keyed by `sub`.
* Back-channel calls are signed (see `@crosscode/contracts/signing`) and retried through pg-boss.
*/
export const IDENTITY_SCHEMA = schemaName("identity", 1);
/** 2FA methods (Cross Events 2.2.0 adds `totp`, the authenticator app). */
export const TWO_FACTOR_METHODS = ["email", "whatsapp", "totp"] as const;
export const twoFactorMethodSchema = z.enum(TWO_FACTOR_METHODS);
export type TwoFactorMethod = z.infer<typeof twoFactorMethodSchema>;
export const newsConsentSchema = z.object({
email: z.boolean(),
whatsapp: z.boolean(),
});
export type NewsConsent = z.infer<typeof newsConsentSchema>;
/** The profile every product keeps a local copy of (for lists and messages). */
export const profileSchema = z.object({
name: z.string().trim().min(1).max(200),
given_name: z.string().trim().max(100).nullable(),
family_name: z.string().trim().max(100).nullable(),
email: emailSchema,
email_verified: z.boolean(),
phone_number: phoneSchema.nullable(),
phone_number_verified: z.boolean(),
/** Whether the church may send this person news, per channel. */
news_consent: newsConsentSchema,
});
export type Profile = z.infer<typeof profileSchema>;
/**
* The `crosscode.identity/1` claims in the ID token and the userinfo response, next to the
* standard JWT claims (`iss`, `aud`, `exp`, …) that openid-client checks.
*/
export const identityClaimsSchema = profileSchema.extend({
schema: z.literal(IDENTITY_SCHEMA),
/** The account id. Each product's user record uses it as its id. */
sub: idSchema,
/** How this sign-in was done (RFC 8176): `pwd`, plus `otp` / `mfa` when 2FA was used. */
amr: z.array(z.string().min(1).max(20)).max(10),
/** The account's 2FA method, or `null` when 2FA is off. Admins see it per staff account. */
two_factor: twoFactorMethodSchema.nullable(),
/** The privacy notice version the person has accepted. Accounts asks again before returning when there's a newer one. */
privacy_notice_version: z.int().positive(),
});
export type IdentityClaims = z.infer<typeof identityClaimsSchema>;
// ---------------------------------------------------------------------------------------------
// Back-channel calls: Accounts → product, `POST <product>/api/accounts/v1/events`
// ---------------------------------------------------------------------------------------------
const callBase = z.object({
schema: z.literal(IDENTITY_SCHEMA),
/** Unique per call; repeated on a retry, so products can ignore a call they've already handled. */
callId: idSchema,
occurredAt: dateTimeSchema,
sub: idSchema,
});
/** The person's profile or consent changed. Products update their local copy. */
export const userUpdatedSchema = callBase.extend({
type: z.literal("user.updated"),
profile: profileSchema,
});
/**
* An admin approved deleting the account. Products anonymise their data for `sub` (as Cross
* Events does today) and answer with {@link userDeletedReplySchema}.
*/
export const userDeletedSchema = callBase.extend({
type: z.literal("user.deleted"),
approvedAt: dateTimeSchema,
});
/** "Download my data": each product sends its part, which Accounts bundles. */
export const userExportSchema = callBase.extend({
type: z.literal("user.export"),
/** The export this part belongs to. */
exportId: idSchema,
});
export const accountsCallSchema = z.discriminatedUnion("type", [userUpdatedSchema, userDeletedSchema, userExportSchema]);
export type AccountsCall = z.infer<typeof accountsCallSchema>;
export type UserUpdated = z.infer<typeof userUpdatedSchema>;
export type UserDeleted = z.infer<typeof userDeletedSchema>;
export type UserExport = z.infer<typeof userExportSchema>;
/** The reply to `user.updated`. */
export const userUpdatedReplySchema = z.object({ schema: z.literal(IDENTITY_SCHEMA), ok: z.literal(true) });
/**
* The reply to `user.deleted`. `deferred` when the product can't anonymise yet (Cross Events:
* an open registration for an upcoming event); Accounts asks again after `retryAfter`.
*/
export const userDeletedReplySchema = z.discriminatedUnion("status", [
z.object({ schema: z.literal(IDENTITY_SCHEMA), status: z.literal("deleted") }),
z.object({
schema: z.literal(IDENTITY_SCHEMA),
status: z.literal("deferred"),
/** Shown to the admin, e.g. "Has a registration for Youth Camp (14 March)". */
reason: z.string().trim().min(1).max(500),
retryAfter: dateTimeSchema,
}),
]);
export type UserDeletedReply = z.infer<typeof userDeletedReplySchema>;
/** One part of a product's export, e.g. "Registrations" or "Prayer commitments". */
export const exportSectionSchema = z.object({
key: z.string().regex(/^[a-z][a-z0-9_]*$/).max(50),
title: z.string().trim().min(1).max(100),
records: z.array(z.record(z.string(), z.unknown())),
});
/** The reply to `user.export`: the product's part of "Download my data". */
export const userExportReplySchema = z.object({
schema: z.literal(IDENTITY_SCHEMA),
exportId: idSchema,
sub: idSchema,
product: productSchema,
generatedAt: dateTimeSchema,
sections: z.array(exportSectionSchema).max(100),
});
export type UserExportReply = z.infer<typeof userExportReplySchema>;
+8 -4
View File
@@ -1,7 +1,11 @@
/**
* @crosscode/contracts — the shared JSON formats used by every Cross Code product
* (ROADMAP-v3 §2). Contracts to come in 1.0.0: `crosscode.event/1`, `crosscode.church/1`,
* `crosscode.identity/1` and Hub protocol v3.
* (ROADMAP-v3 §2). Request signing is Node-only and lives in `@crosscode/contracts/signing`.
*/
export { schemaName, parseSchemaName, isSchema } from "./schema-name";
export type { SchemaName } from "./schema-name";
export * from "./schema-name";
export * from "./common";
export * from "./event";
export * from "./church";
export * from "./identity";
export * from "./return-to";
export * as hub from "./hub";
+139
View File
@@ -0,0 +1,139 @@
/**
* Sign-in always returns people to where they came from (ROADMAP-v3 §3). A product sends the
* page someone was on (path and query) in the OIDC `state`; after sign-in Accounts redirects back
* to the product's registered `redirect_uri`, and the product sends the person on to that page.
*
* Every product uses these helpers so the checks are the same everywhere:
* - {@link isSafeReturnPath} / {@link safeReturnPath}: only a relative path on the same site.
* - {@link encodeState} / {@link decodeState}: the `state` value, carrying a nonce for CSRF and
* the return path. The product must still check the nonce against the one it stored (cookie)
* before trusting the state.
* - {@link isRegisteredRedirectUri}: Accounts' exact-match check on `redirect_uri` and
* `post_logout_redirect_uri`.
*
* Works in Node and in the browser (no Buffer).
*/
export const MAX_RETURN_PATH_LENGTH = 2048;
// As sent: no control characters, whitespace or backslashes (browsers treat "\" like "/" and
// drop tabs and newlines, which turns "/\t/evil.com" into "//evil.com").
// eslint-disable-next-line no-control-regex
const FORBIDDEN_RAW = /[\u0000- \u007f\\]/;
// Once decoded (for code that decodes before redirecting): no control characters (CR/LF would
// split a Location header) or backslashes. An encoded space (`%20`) is fine.
// eslint-disable-next-line no-control-regex
const FORBIDDEN_DECODED = /[\u0000-\u001f\u007f\\]/;
function decodeFully(value: string): string | null {
let current = value;
for (let i = 0; i < 3; i++) {
let next: string;
try {
next = decodeURIComponent(current);
} catch {
return null;
}
if (next === current) return current;
current = next;
}
// Still changing after three rounds: treat as hostile.
return decodeURIComponent(current) === current ? current : null;
}
/**
* True when `value` is a path on the same site: starts with a single `/`, has no scheme or host
* (`//evil.com`, `/\evil.com`, `https://…`), no control characters, whitespace or backslashes,
* and stays that way however many times it's percent-decoded.
*/
export function isSafeReturnPath(value: unknown): value is string {
if (typeof value !== "string") return false;
if (value.length === 0 || value.length > MAX_RETURN_PATH_LENGTH) return false;
const decoded = decodeFully(value);
if (decoded === null) return false;
for (const [candidate, forbidden] of [
[value, FORBIDDEN_RAW],
[decoded, FORBIDDEN_DECODED],
] as const) {
if (!candidate.startsWith("/")) return false;
if (candidate.startsWith("//")) return false;
if (forbidden.test(candidate)) return false;
}
// Last check: resolving it against a site must stay on that site.
try {
const base = "https://return-to.invalid";
return new URL(value, base).origin === base;
} catch {
return false;
}
}
/** `value` when it's a safe return path, otherwise `fallback` (the product's home page). */
export function safeReturnPath(value: unknown, fallback = "/"): string {
return isSafeReturnPath(value) ? value : fallback;
}
/** What a product puts in the OIDC `state`. */
export interface SignInState {
/** Random, at least 16 characters; also stored by the product (cookie) and compared on return. */
nonce: string;
/** The page to return to after sign-in. */
returnTo: string;
}
const NONCE = /^[A-Za-z0-9_-]{16,128}$/;
function toBase64Url(text: string): string {
const bytes = new TextEncoder().encode(text);
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function fromBase64Url(value: string): string | null {
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null;
try {
const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
return null;
}
}
/** Builds the `state` value. Throws on a bad nonce; an unsafe `returnTo` becomes `/`. */
export function encodeState(state: SignInState): string {
if (!NONCE.test(state.nonce)) throw new Error("The state nonce must be 16–128 base64url characters");
return toBase64Url(JSON.stringify({ n: state.nonce, r: safeReturnPath(state.returnTo) }));
}
/**
* Reads a `state` value back. Returns `null` when it isn't one of ours; otherwise the nonce (to
* compare with the stored one) and a return path that is always safe (`fallback` if it wasn't).
*/
export function decodeState(value: unknown, fallback = "/"): SignInState | null {
if (typeof value !== "string" || value.length > 4096) return null;
const json = fromBase64Url(value);
if (json === null) return null;
let parsed: unknown;
try {
parsed = JSON.parse(json);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const { n, r } = parsed as { n?: unknown; r?: unknown };
if (typeof n !== "string" || !NONCE.test(n)) return null;
return { nonce: n, returnTo: safeReturnPath(r, fallback) };
}
/**
* Accounts' check on `redirect_uri` / `post_logout_redirect_uri`: an exact string match with one
* of the linked product's registered URIs. No wildcards, prefixes or normalising.
*/
export function isRegisteredRedirectUri(uri: unknown, registered: readonly string[]): boolean {
return typeof uri === "string" && registered.includes(uri);
}
+76
View File
@@ -0,0 +1,76 @@
import { createHmac, timingSafeEqual } from "node:crypto";
/**
* Signed requests between Cross Code installs (Node only: `@crosscode/contracts/signing`).
*
* The same scheme as the Hub protocol's heartbeat, so there's one way to sign everywhere:
* `signature = hex(HMAC-SHA256(secret, timestamp + "." + rawBody))`, where `timestamp` is the
* ISO 8601 time in the timestamp header and `rawBody` the exact bytes sent. Requests more than
* five minutes off the receiver's clock are refused.
*
* - Hub protocol (install → Hub): {@link HUB_HEADERS}, the install's `installSecret`.
* - Product links (`event.changed` webhooks, Accounts back-channel calls): {@link LINK_HEADERS},
* the secret of that link, set up by **Connect** under Settings → Linked products.
*/
export const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
export interface SignatureHeaders {
sender: string;
timestamp: string;
signature: string;
}
/** Install → Hub. `sender` carries the install id. */
export const HUB_HEADERS: SignatureHeaders = {
sender: "x-hub-install",
timestamp: "x-hub-timestamp",
signature: "x-hub-signature",
};
/** Install → linked install. `sender` carries the sending install's id. */
export const LINK_HEADERS: SignatureHeaders = {
sender: "x-crosscode-sender",
timestamp: "x-crosscode-timestamp",
signature: "x-crosscode-signature",
};
export type RawBody = string | Uint8Array;
/** The hex signature for a body sent at `timestamp`. */
export function sign(secret: string, timestamp: string, rawBody: RawBody): string {
const hmac = createHmac("sha256", secret);
hmac.update(`${timestamp}.`);
hmac.update(rawBody);
return hmac.digest("hex");
}
/** The three headers to send with a body. `now` is for tests. */
export function signedHeaders(headers: SignatureHeaders, opts: { senderId: string; secret: string; rawBody: RawBody; now?: Date }): Record<string, string> {
const timestamp = (opts.now ?? new Date()).toISOString();
return {
[headers.sender]: opts.senderId,
[headers.timestamp]: timestamp,
[headers.signature]: sign(opts.secret, timestamp, opts.rawBody),
};
}
export type VerifyResult = { ok: true } | { ok: false; code: "STALE_REQUEST" | "BAD_SIGNATURE" };
/**
* Checks a received signature. `timestamp` and `signature` are the header values as received;
* `rawBody` must be the exact bytes (parse JSON only after verifying).
*/
export function verify(opts: { secret: string; timestamp: unknown; signature: unknown; rawBody: RawBody; now?: Date; maxSkewMs?: number }): VerifyResult {
const { secret, timestamp, signature, rawBody } = opts;
if (typeof timestamp !== "string" || typeof signature !== "string") return { ok: false, code: "BAD_SIGNATURE" };
const sentAt = Date.parse(timestamp);
const now = (opts.now ?? new Date()).getTime();
if (!Number.isFinite(sentAt) || Math.abs(now - sentAt) > (opts.maxSkewMs ?? MAX_CLOCK_SKEW_MS)) return { ok: false, code: "STALE_REQUEST" };
if (!/^[0-9a-f]{64}$/.test(signature)) return { ok: false, code: "BAD_SIGNATURE" };
const expected = Buffer.from(sign(secret, timestamp, rawBody), "hex");
const given = Buffer.from(signature, "hex");
return timingSafeEqual(expected, given) ? { ok: true } : { ok: false, code: "BAD_SIGNATURE" };
}