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:
@@ -11,3 +11,22 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a
|
||||
- `packages/contracts`: package set up with a dual CommonJS / ESM build (tsup) and the
|
||||
schema-name helpers every contract uses (`crosscode.<name>/<major>`).
|
||||
- `packages/ui`, `apps/accounts`, `apps/website`, `apps/app`: placeholders.
|
||||
|
||||
### Contracts (towards 1.0.0)
|
||||
|
||||
- `crosscode.event/1` and `crosscode.event-feed/1`: the event, the feed response and the
|
||||
`event.changed` webhook. Checks that `startsAt` / `endsAt` match the sessions and that only
|
||||
Cross Events takes registrations. `parseEventFeed` skips and reports a bad event instead of
|
||||
failing the whole feed; `eventKey` is the cross-product id.
|
||||
- `crosscode.church/1`: the church profile (branding, campuses, service times, contact, links).
|
||||
- `crosscode.identity/1`: sign-in claims (no roles; 2FA method including the authenticator app,
|
||||
news consent, privacy notice version) and the `user.updated`, `user.deleted` (with a
|
||||
"deferred" reply) and `user.export` back-channel calls.
|
||||
- Sign-in return: `isSafeReturnPath`, `safeReturnPath`, `encodeState` / `decodeState` and
|
||||
`isRegisteredRedirectUri`, so every product sends people back to the page they came from in
|
||||
the same safe way.
|
||||
- Hub protocol v2: `product` on register and heartbeat, stats per product (Events as in v1;
|
||||
Website storage and App active-member bands for billing), the install's public key, linked
|
||||
products in the replies, `customerId` / `product` in the licence token.
|
||||
- `@crosscode/contracts/signing` (Node only): the Hub's HMAC scheme for the Hub and product links.
|
||||
- Sample payloads for every contract in `samples/`, checked by the tests.
|
||||
|
||||
@@ -1,29 +1,74 @@
|
||||
# @crosscode/contracts
|
||||
|
||||
Everything that crosses between Cross Code products is defined once, here (ROADMAP-v3 §2):
|
||||
zod schemas, generated JSON Schema, TypeScript types and sample payloads. Every product, including
|
||||
Cross Events and the Hub, uses it, so the key fields are the same in every product's JSON.
|
||||
zod schemas, TypeScript types and sample payloads (`samples/`). Every product, including Cross
|
||||
Events and the Hub, uses it, so the key fields are the same in every product's JSON.
|
||||
|
||||
| Contract | Used for | Status |
|
||||
|----------|----------|--------|
|
||||
| `crosscode.event/1` | The event feed every product publishes and reads | To do |
|
||||
| `crosscode.church/1` | The church profile: name, logo, colours, campuses, service times, contact details | To do |
|
||||
| `crosscode.identity/1` | Accounts' sign-in token claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) | To do |
|
||||
| Hub protocol v3 | Register, heartbeat, licence token, AI calls, for every product | To do |
|
||||
| Contract | Schema name | Used for | Source |
|
||||
|----------|-------------|----------|--------|
|
||||
| Event | `crosscode.event/1` | One event, as every product publishes and reads it | `src/event.ts` |
|
||||
| Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` |
|
||||
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
|
||||
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
|
||||
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
|
||||
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
|
||||
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
|
||||
|
||||
## Using it
|
||||
|
||||
```ts
|
||||
import { eventSchema, parseEventFeed, eventKey, hub } from "@crosscode/contracts";
|
||||
import { verify, LINK_HEADERS } from "@crosscode/contracts/signing"; // Node only
|
||||
|
||||
const result = parseEventFeed(await res.json());
|
||||
if (result.ok) {
|
||||
for (const event of result.feed.events) upsert(eventKey(event), event);
|
||||
for (const bad of result.rejected) log.warn("Skipped an event from the feed", bad);
|
||||
}
|
||||
```
|
||||
|
||||
- Parse at the edge: `schema.safeParse(body)` on everything that comes in, and build what goes
|
||||
out with the types (`CrosscodeEvent`, `Church`, `hub.HeartbeatRequest`, …).
|
||||
- **Feeds:** use `parseEventFeed`. A bad event is skipped and reported, never blocking the rest.
|
||||
- **Unknown fields are dropped, not refused**, so a newer producer never breaks an older consumer.
|
||||
|
||||
### Sign-in return (ROADMAP-v3 §3)
|
||||
|
||||
```ts
|
||||
import { encodeState, decodeState, safeReturnPath, isRegisteredRedirectUri } from "@crosscode/contracts";
|
||||
|
||||
// Product, before redirecting to Accounts:
|
||||
const nonce = randomBase64Url(24); // also set as an HttpOnly cookie
|
||||
const state = encodeState({ nonce, returnTo: req.originalUrl });
|
||||
|
||||
// Product, on /auth/callback:
|
||||
const s = decodeState(req.query.state);
|
||||
if (!s || s.nonce !== req.cookies.signInNonce) return res.redirect("/");
|
||||
res.redirect(s.returnTo); // always a safe same-site path
|
||||
|
||||
// Accounts, on the authorisation request:
|
||||
if (!isRegisteredRedirectUri(params.redirect_uri, client.redirectUris)) refuse();
|
||||
```
|
||||
|
||||
`isSafeReturnPath` accepts a path on the same site only (a single leading `/`, no scheme or host,
|
||||
no `\`, control characters or whitespace, even after percent-decoding). Anything else falls back
|
||||
to the product's home page.
|
||||
|
||||
### Signing
|
||||
|
||||
`hex(HMAC-SHA256(secret, timestamp + "." + rawBody))`, the same scheme as the Hub heartbeat, with
|
||||
a five-minute clock window. `HUB_HEADERS` (`X-Hub-Install`, `X-Hub-Timestamp`, `X-Hub-Signature`)
|
||||
for install → Hub; `LINK_HEADERS` (`X-Crosscode-Sender`, `-Timestamp`, `-Signature`) for
|
||||
`event.changed` webhooks and Accounts back-channel calls, with the secret set up by **Connect**.
|
||||
Verify the raw bytes before parsing the JSON.
|
||||
|
||||
## Versioning
|
||||
|
||||
- Every payload carries its `schema` name: `crosscode.<name>/<major>`.
|
||||
- Every payload carries its `schema` name: `crosscode.<name>/<major>` (`parseSchemaName`, `isSchema`).
|
||||
- Adding an **optional** field keeps the version. Consumers ignore fields they don't know.
|
||||
- Removing or renaming a field, or changing its meaning, needs a new major (`/2`). The old one
|
||||
is served alongside it until every install has updated.
|
||||
|
||||
```ts
|
||||
import { parseSchemaName, isSchema } from "@crosscode/contracts";
|
||||
|
||||
parseSchemaName("crosscode.event/1"); // { name: "event", major: 1 }
|
||||
isSchema(payload.schema, "event", 1); // true / false
|
||||
```
|
||||
- Removing or renaming a field, adding a value to an enum, or changing a meaning needs a new
|
||||
major (`/2`). The old one is served alongside it until every install has updated.
|
||||
- Hub protocol: the Hub accepts the current and the previous `protocolVersion` (`HUB_PROTOCOL_VERSIONS`).
|
||||
|
||||
## Installing
|
||||
|
||||
|
||||
@@ -18,6 +18,16 @@
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./signing": {
|
||||
"import": {
|
||||
"types": "./dist/signing.d.mts",
|
||||
"default": "./dist/signing.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/signing.d.ts",
|
||||
"default": "./dist/signing.js"
|
||||
}
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"schema": "crosscode.church/1",
|
||||
"customerId": "c7a1e2d3-4b5c-4d6e-8f70-81a2b3c4d5e6",
|
||||
"updatedAt": "2026-11-01T09:00:00.000Z",
|
||||
"name": "Hope Family Church",
|
||||
"shortName": "Hope Family",
|
||||
"timezone": "Africa/Johannesburg",
|
||||
"locale": "en-ZA",
|
||||
"branding": {
|
||||
"logoUrl": "https://www.hopefamily.co.za/uploads/logo.png",
|
||||
"iconUrl": "https://www.hopefamily.co.za/uploads/icon-512.png",
|
||||
"colours": { "primary": "#1f4e79", "accent": "#f2a900" }
|
||||
},
|
||||
"campuses": [
|
||||
{
|
||||
"slug": "meyerton",
|
||||
"name": "Meyerton",
|
||||
"address": {
|
||||
"line1": "12 Church Street",
|
||||
"line2": null,
|
||||
"suburb": "Meyerton Central",
|
||||
"city": "Meyerton",
|
||||
"province": "Gauteng",
|
||||
"postalCode": "1961",
|
||||
"country": "ZA",
|
||||
"geo": { "lat": -26.5559, "lng": 28.0141 }
|
||||
}
|
||||
}
|
||||
],
|
||||
"serviceTimes": [
|
||||
{ "day": "sunday", "time": "09:00", "label": "Morning service", "campus": "meyerton", "note": "Kids church during the service" },
|
||||
{ "day": "wednesday", "time": "18:30", "label": "Prayer evening", "campus": "meyerton", "note": null }
|
||||
],
|
||||
"contact": {
|
||||
"email": "office@hopefamily.co.za",
|
||||
"phone": "+27161234567",
|
||||
"whatsapp": "+27821234567",
|
||||
"address": null
|
||||
},
|
||||
"social": [
|
||||
{ "network": "facebook", "url": "https://www.facebook.com/hopefamilychurch" },
|
||||
{ "network": "youtube", "url": "https://www.youtube.com/@hopefamilychurch" }
|
||||
],
|
||||
"links": {
|
||||
"website": "https://www.hopefamily.co.za",
|
||||
"events": "https://events.hopefamily.co.za",
|
||||
"app": null,
|
||||
"accounts": "https://accounts.hopefamily.co.za"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"schema": "crosscode.event-feed/1",
|
||||
"type": "event.changed",
|
||||
"occurredAt": "2026-11-03T10:00:01.000Z",
|
||||
"eventIds": ["8f1c2a4e-5b6d-4c7e-9f80-a1b2c3d4e5f6"]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"schema": "crosscode.event-feed/1",
|
||||
"generatedAt": "2026-11-03T10:05:00.000Z",
|
||||
"events": [
|
||||
{
|
||||
"schema": "crosscode.event/1",
|
||||
"id": "8f1c2a4e-5b6d-4c7e-9f80-a1b2c3d4e5f6",
|
||||
"origin": { "product": "events", "installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e01", "url": "https://events.hopefamily.co.za/events/youth-camp" },
|
||||
"status": "published",
|
||||
"updatedAt": "2026-11-03T10:00:00.000Z",
|
||||
"title": "Youth Camp 2027",
|
||||
"summary": "Three days at Camp Wartburg",
|
||||
"description": null,
|
||||
"imageUrl": null,
|
||||
"timezone": "Africa/Johannesburg",
|
||||
"startsAt": "2027-03-14T06:00:00.000Z",
|
||||
"endsAt": "2027-03-16T12:00:00.000Z",
|
||||
"allDay": false,
|
||||
"sessions": [],
|
||||
"location": null,
|
||||
"campus": null,
|
||||
"series": null,
|
||||
"tags": [],
|
||||
"registration": { "mode": "origin", "url": "https://events.hopefamily.co.za/events/youth-camp", "status": "full", "opensAt": null, "closesAt": null, "priceFrom": { "amountCents": 45000, "currency": "ZAR" } }
|
||||
}
|
||||
],
|
||||
"deleted": [
|
||||
{ "id": "0f9e8d7c-6b5a-4493-8271-605f4e3d2c1b", "deletedAt": "2026-11-02T08:00:00.000Z" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"schema": "crosscode.event/1",
|
||||
"id": "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090",
|
||||
"origin": {
|
||||
"product": "website",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02",
|
||||
"url": "https://www.hopefamily.co.za/events/carols-by-candlelight"
|
||||
},
|
||||
"status": "published",
|
||||
"updatedAt": "2026-11-02T14:30:00.000Z",
|
||||
"title": "Carols by Candlelight",
|
||||
"summary": null,
|
||||
"description": "Bring a blanket and the family. No booking needed; ask the church office about parking for the elderly.",
|
||||
"imageUrl": null,
|
||||
"timezone": "Africa/Johannesburg",
|
||||
"startsAt": "2026-12-20T16:00:00.000Z",
|
||||
"endsAt": "2026-12-20T18:00:00.000Z",
|
||||
"allDay": false,
|
||||
"sessions": [],
|
||||
"location": { "name": "Church lawn", "address": null, "onlineUrl": null },
|
||||
"campus": null,
|
||||
"series": null,
|
||||
"tags": ["christmas", "family"],
|
||||
"registration": {
|
||||
"mode": "contact",
|
||||
"url": null,
|
||||
"status": "open",
|
||||
"opensAt": null,
|
||||
"closesAt": null,
|
||||
"priceFrom": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"schema": "crosscode.event/1",
|
||||
"id": "8f1c2a4e-5b6d-4c7e-9f80-a1b2c3d4e5f6",
|
||||
"origin": {
|
||||
"product": "events",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e01",
|
||||
"url": "https://events.hopefamily.co.za/events/youth-camp"
|
||||
},
|
||||
"status": "published",
|
||||
"updatedAt": "2026-11-03T10:00:00.000Z",
|
||||
"title": "Youth Camp 2027",
|
||||
"summary": "Three days at Camp Wartburg",
|
||||
"description": "Three days of worship, teaching and adventure for grades 8 to 12.\n\n**Bring:** a sleeping bag and a Bible.",
|
||||
"imageUrl": "https://events.hopefamily.co.za/uploads/youth-camp-2027.jpg",
|
||||
"timezone": "Africa/Johannesburg",
|
||||
"startsAt": "2027-03-14T06:00:00.000Z",
|
||||
"endsAt": "2027-03-16T12:00:00.000Z",
|
||||
"allDay": false,
|
||||
"sessions": [
|
||||
{ "id": "1a2b3c4d-0001-4a00-8a00-000000000001", "label": "Day 1", "startsAt": "2027-03-14T06:00:00.000Z", "endsAt": "2027-03-14T19:00:00.000Z", "location": null, "cancelled": false },
|
||||
{ "id": "1a2b3c4d-0001-4a00-8a00-000000000002", "label": "Day 2", "startsAt": "2027-03-15T06:00:00.000Z", "endsAt": "2027-03-15T19:00:00.000Z", "location": null, "cancelled": false },
|
||||
{ "id": "1a2b3c4d-0001-4a00-8a00-000000000003", "label": "Day 3", "startsAt": "2027-03-16T06:00:00.000Z", "endsAt": "2027-03-16T12:00:00.000Z", "location": null, "cancelled": false }
|
||||
],
|
||||
"location": { "name": "Camp Wartburg", "address": "R103, Wartburg, KwaZulu-Natal", "onlineUrl": null },
|
||||
"campus": { "slug": "meyerton", "name": "Meyerton" },
|
||||
"series": { "id": "2b3c4d5e-6f70-4a81-9b92-a3b4c5d6e7f8", "name": "Youth Camp" },
|
||||
"tags": ["youth"],
|
||||
"registration": {
|
||||
"mode": "origin",
|
||||
"url": "https://events.hopefamily.co.za/events/youth-camp",
|
||||
"status": "open",
|
||||
"opensAt": null,
|
||||
"closesAt": "2027-03-10T22:00:00.000Z",
|
||||
"priceFrom": { "amountCents": 45000, "currency": "ZAR" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"protocolVersion": 2,
|
||||
"product": "accounts",
|
||||
"version": "1.0.0",
|
||||
"health": {
|
||||
"uptimeSeconds": 7200,
|
||||
"db": true,
|
||||
"jobs": { "mode": "queue", "failedLast24h": 0 },
|
||||
"lastBackupAt": "2026-11-03T00:00:02.000Z",
|
||||
"disk": null,
|
||||
"errorsLast24h": 0,
|
||||
"pendingMigrations": 0
|
||||
},
|
||||
"stats": {
|
||||
"accounts": { "total": 640, "active90d": 288 },
|
||||
"twoFactor": { "email": 30, "whatsapp": 12, "totp": 6, "off": 592 },
|
||||
"linkedProducts": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"protocolVersion": 2,
|
||||
"product": "app",
|
||||
"version": "1.0.0",
|
||||
"health": {
|
||||
"uptimeSeconds": 7200,
|
||||
"db": true,
|
||||
"jobs": { "mode": "queue", "failedLast24h": 1 },
|
||||
"lastBackupAt": "2026-11-03T00:00:09.000Z",
|
||||
"disk": null,
|
||||
"errorsLast24h": 2,
|
||||
"pendingMigrations": 0
|
||||
},
|
||||
"stats": {
|
||||
"activeMembers90d": "101–300",
|
||||
"modules": ["house-of-prayer", "announcements", "devotionals", "events"],
|
||||
"prayer": { "coverageLast7dPercent": 62.5, "activeCommitments": 87 },
|
||||
"announcements": { "last30d": 6 },
|
||||
"messages": { "email30d": 410, "whatsapp30d": 1290 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"protocolVersion": 2,
|
||||
"product": "events",
|
||||
"version": "2.3.0",
|
||||
"health": {
|
||||
"uptimeSeconds": 86400,
|
||||
"db": true,
|
||||
"jobs": { "mode": "queue", "failedLast24h": 0 },
|
||||
"lastBackupAt": "2026-11-03T00:00:12.000Z",
|
||||
"disk": { "freeBytes": 21474836480, "totalBytes": 53687091200 },
|
||||
"errorsLast24h": 0,
|
||||
"pendingMigrations": 0
|
||||
},
|
||||
"stats": {
|
||||
"users": 412,
|
||||
"events": { "active": 3, "upcoming": 5, "total": 61 },
|
||||
"registrations": { "last30d": 88, "total": 2310 },
|
||||
"tickets": { "last30d": 140, "total": 3901 },
|
||||
"checkIns": { "last30d": 96 },
|
||||
"messages": null,
|
||||
"paymentProviders": ["yoco", "payfast"],
|
||||
"campuses": true,
|
||||
"campusCount": 2,
|
||||
"income": { "last30d": "R5 001–R20 000", "allTime": "R150 001–R250 000", "eventIncome12m": "R100 001–R150 000" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"licence": "hel1.eyJ2IjoxfQ.c2lnbmF0dXJl",
|
||||
"latestVersion": "2.3.1",
|
||||
"releases": [
|
||||
{ "version": "2.3.1", "releasedAt": "2026-11-10T10:00:00.000Z", "urgent": false, "notes": "- Fixed: feed sync after a campus is renamed" }
|
||||
],
|
||||
"notices": [
|
||||
{
|
||||
"id": "notice-1",
|
||||
"level": "maintenance",
|
||||
"title": "Planned maintenance",
|
||||
"message": "The Hub will be offline for about 30 minutes. Your site keeps working.",
|
||||
"startsAt": "2026-11-15T16:00:00.000Z",
|
||||
"endsAt": "2026-11-15T16:30:00.000Z",
|
||||
"updatedAt": "2026-11-03T08:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"linkedProducts": [
|
||||
{
|
||||
"product": "website",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02",
|
||||
"url": "https://www.hopefamily.co.za",
|
||||
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEARF8kVdPtJTKGFGxkcYFGy9lIB+ccsZGH4cTWlJSyGAc=\n-----END PUBLIC KEY-----\n"
|
||||
},
|
||||
{
|
||||
"product": "accounts",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04",
|
||||
"url": "https://accounts.hopefamily.co.za",
|
||||
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsQbIsjVsJY9k9jLjMSbscXdD9wONmLw90MrMHptfmSQ=\n-----END PUBLIC KEY-----\n"
|
||||
}
|
||||
],
|
||||
"serverTime": "2026-11-03T10:15:00.120Z"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"protocolVersion": 2,
|
||||
"product": "website",
|
||||
"version": "1.0.0",
|
||||
"health": {
|
||||
"uptimeSeconds": 3600,
|
||||
"db": true,
|
||||
"jobs": { "mode": "queue", "failedLast24h": 0 },
|
||||
"lastBackupAt": "2026-11-03T00:00:05.000Z",
|
||||
"disk": null,
|
||||
"errorsLast24h": null,
|
||||
"pendingMigrations": 0
|
||||
},
|
||||
"stats": {
|
||||
"pages": { "published": 14, "drafts": 2 },
|
||||
"messages": { "total": 120, "last30d": 4 },
|
||||
"events": { "upcomingSimple": 1, "imported": 5 },
|
||||
"editors": 3,
|
||||
"storage": { "usedBytes": 1288490188, "includedBytes": 5368709120 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"v": 1,
|
||||
"licenceId": "4a5b6c7d-8e9f-4a0b-9c1d-2e3f4a5b6c7d",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e01",
|
||||
"customerId": "c7a1e2d3-4b5c-4d6e-8f70-81a2b3c4d5e6",
|
||||
"product": "events",
|
||||
"customer": "Hope Family Church",
|
||||
"plan": "grow",
|
||||
"status": "active",
|
||||
"licenceExpiresAt": "2027-10-31T21:59:59.000Z",
|
||||
"graceDays": 14,
|
||||
"issuedAt": "2026-11-03T10:15:00.000Z",
|
||||
"validUntil": "2026-12-03T10:15:00.000Z",
|
||||
"limits": { "aiMonthlyCapCents": 5000 }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"protocolVersion": 2,
|
||||
"licenceKey": "CEH-7K2M-9QXA-P4RT-WD8C",
|
||||
"product": "events",
|
||||
"install": {
|
||||
"name": "Hope Family Church",
|
||||
"url": "https://events.hopefamily.co.za",
|
||||
"adminContact": { "name": "Jane Admin", "email": "jane@hopefamily.co.za" },
|
||||
"version": "2.3.0",
|
||||
"timezone": "Africa/Johannesburg",
|
||||
"server": { "node": "20.18.0", "postgres": "16.4", "os": "linux 6.8" },
|
||||
"features": { "whatsapp": true, "paymentProviders": ["yoco", "payfast"], "campuses": true },
|
||||
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAWWClNYLC0mJBNO3fvZEKVWwN2zzUonnbxGtNxP5Aw6w=\n-----END PUBLIC KEY-----\n"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e01",
|
||||
"installSecret": "q8V3m1xT9bK2pL7wR4nZ6cY0dF5hJ8sA2gE1uI3oP9k",
|
||||
"licence": "hel1.eyJ2IjoxfQ.c2lnbmF0dXJl",
|
||||
"heartbeatIntervalMinutes": 15,
|
||||
"latestVersion": "2.3.0",
|
||||
"releases": [],
|
||||
"notices": [],
|
||||
"linkedProducts": [
|
||||
{
|
||||
"product": "website",
|
||||
"installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02",
|
||||
"url": "https://www.hopefamily.co.za",
|
||||
"publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEARF8kVdPtJTKGFGxkcYFGy9lIB+ccsZGH4cTWlJSyGAc=\n-----END PUBLIC KEY-----\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"sub": "5d2e8f10-3a4b-4c5d-8e6f-7a8b9c0d1e2f",
|
||||
"name": "Thandi Mokoena",
|
||||
"given_name": "Thandi",
|
||||
"family_name": "Mokoena",
|
||||
"email": "thandi@example.com",
|
||||
"email_verified": true,
|
||||
"phone_number": "+27831234567",
|
||||
"phone_number_verified": true,
|
||||
"news_consent": { "email": true, "whatsapp": false },
|
||||
"amr": ["pwd", "otp", "mfa"],
|
||||
"two_factor": "totp",
|
||||
"privacy_notice_version": 3
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"status": "deferred",
|
||||
"reason": "Has a registration for Youth Camp 2027 (14 March 2027)",
|
||||
"retryAfter": "2027-03-17T00:00:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"type": "user.deleted",
|
||||
"callId": "8d7c6b5a-4938-4271-a605-e4d3c2b1a09f",
|
||||
"occurredAt": "2026-11-03T12:00:00.000Z",
|
||||
"sub": "5d2e8f10-3a4b-4c5d-8e6f-7a8b9c0d1e2f",
|
||||
"approvedAt": "2026-11-03T12:00:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"exportId": "7c6b5a49-3827-4165-b4e3-d2c1b0a9f8e7",
|
||||
"sub": "5d2e8f10-3a4b-4c5d-8e6f-7a8b9c0d1e2f",
|
||||
"product": "events",
|
||||
"generatedAt": "2026-11-03T13:00:04.000Z",
|
||||
"sections": [
|
||||
{
|
||||
"key": "registrations",
|
||||
"title": "Registrations",
|
||||
"records": [
|
||||
{ "event": "Youth Camp 2027", "registeredAt": "2026-10-20T08:12:00.000Z", "tickets": 2, "status": "paid" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "check_ins",
|
||||
"title": "Check-ins",
|
||||
"records": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"type": "user.export",
|
||||
"callId": "7b6a5948-3726-4150-9f4e-d3c2b1a09f8e",
|
||||
"occurredAt": "2026-11-03T13:00:00.000Z",
|
||||
"sub": "5d2e8f10-3a4b-4c5d-8e6f-7a8b9c0d1e2f",
|
||||
"exportId": "7c6b5a49-3827-4165-b4e3-d2c1b0a9f8e7"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"schema": "crosscode.identity/1",
|
||||
"type": "user.updated",
|
||||
"callId": "9e8d7c6b-5a49-4382-a716-f5e4d3c2b1a0",
|
||||
"occurredAt": "2026-11-03T11:00:00.000Z",
|
||||
"sub": "5d2e8f10-3a4b-4c5d-8e6f-7a8b9c0d1e2f",
|
||||
"profile": {
|
||||
"name": "Thandi Mokoena",
|
||||
"given_name": "Thandi",
|
||||
"family_name": "Mokoena",
|
||||
"email": "thandi.mokoena@example.com",
|
||||
"email_verified": true,
|
||||
"phone_number": "+27831234567",
|
||||
"phone_number_verified": true,
|
||||
"news_consent": { "email": true, "whatsapp": true }
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -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");
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -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>;
|
||||
@@ -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";
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { accountsCallSchema, churchSchema, identityClaimsSchema, userDeletedReplySchema } from "../src";
|
||||
import type { Church } from "../src";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
describe("crosscode.church/1", () => {
|
||||
const church = () => sample<Church>("church.json");
|
||||
|
||||
it("refuses a service time for a campus that doesn't exist", () => {
|
||||
const c = church();
|
||||
c.serviceTimes[0]!.campus = "vereeniging";
|
||||
const r = churchSchema.safeParse(c);
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error?.issues[0]?.message).toBe('Unknown campus "vereeniging"');
|
||||
});
|
||||
|
||||
it("refuses duplicate campus slugs", () => {
|
||||
const c = church();
|
||||
c.campuses.push({ ...c.campuses[0]! });
|
||||
expect(churchSchema.safeParse(c).success).toBe(false);
|
||||
});
|
||||
|
||||
it("checks colours, times and phone numbers", () => {
|
||||
const c = church();
|
||||
expect(churchSchema.safeParse({ ...c, branding: { ...c.branding, colours: { primary: "blue", accent: null } } }).success).toBe(false);
|
||||
expect(churchSchema.safeParse({ ...c, serviceTimes: [{ ...c.serviceTimes[0]!, time: "9am" }] }).success).toBe(false);
|
||||
expect(churchSchema.safeParse({ ...c, contact: { ...c.contact, phone: "016 123 4567" } }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("crosscode.identity/1", () => {
|
||||
it("has no roles in the claims (roles stay in each product)", () => {
|
||||
const parsed = identityClaimsSchema.parse({ ...sample("identity-claims.json"), role: "admin" });
|
||||
expect(parsed).not.toHaveProperty("role");
|
||||
});
|
||||
|
||||
it("knows the authenticator app as a 2FA method", () => {
|
||||
expect(identityClaimsSchema.safeParse({ ...sample("identity-claims.json"), two_factor: "sms" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("tells the back-channel calls apart by type", () => {
|
||||
expect(accountsCallSchema.parse(sample("user-deleted.json")).type).toBe("user.deleted");
|
||||
expect(accountsCallSchema.safeParse({ ...sample("user-deleted.json"), type: "user.renamed" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("a deferred delete needs a reason and a retry time", () => {
|
||||
expect(userDeletedReplySchema.safeParse({ schema: "crosscode.identity/1", status: "deferred" }).success).toBe(false);
|
||||
expect(userDeletedReplySchema.safeParse({ schema: "crosscode.identity/1", status: "deleted" }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { eventKey, eventSchema, parseEventFeed } from "../src";
|
||||
import type { CrosscodeEvent } from "../src";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
const base = () => sample<CrosscodeEvent>("event.json");
|
||||
const simple = () => sample<CrosscodeEvent>("event-simple.json");
|
||||
const messages = (input: unknown) => {
|
||||
const r = eventSchema.safeParse(input);
|
||||
return r.success ? [] : r.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`);
|
||||
};
|
||||
|
||||
describe("crosscode.event/1", () => {
|
||||
it("ignores fields it doesn't know (a newer producer never breaks an older consumer)", () => {
|
||||
const parsed = eventSchema.parse({ ...base(), someFutureField: { a: 1 } });
|
||||
expect(parsed).not.toHaveProperty("someFutureField");
|
||||
});
|
||||
|
||||
it("refuses another schema or version", () => {
|
||||
expect(messages({ ...base(), schema: "crosscode.event/2" })).not.toEqual([]);
|
||||
expect(messages({ ...base(), schema: "crosscode.church/1" })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses an unknown origin product", () => {
|
||||
const e = base();
|
||||
expect(messages({ ...e, origin: { ...e.origin, product: "accounts" } })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("checks startsAt / endsAt against the sessions", () => {
|
||||
expect(messages({ ...base(), startsAt: "2027-03-14T07:00:00.000Z" })).toContain("startsAt: startsAt must be the first session's start");
|
||||
expect(messages({ ...base(), endsAt: "2027-03-16T13:00:00.000Z" })).toContain("endsAt: endsAt must be the last session's end");
|
||||
});
|
||||
|
||||
it("leaves cancelled sessions out of the first-start / last-end check", () => {
|
||||
const e = base();
|
||||
e.sessions[2]!.cancelled = true;
|
||||
expect(messages(e)).toContain("endsAt: endsAt must be the last session's end");
|
||||
e.endsAt = e.sessions[1]!.endsAt;
|
||||
expect(messages(e)).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses an event or session that ends before it starts", () => {
|
||||
const e = simple();
|
||||
expect(messages({ ...e, endsAt: "2026-12-20T15:00:00.000Z" })).toContain("endsAt: endsAt is before startsAt");
|
||||
const b = base();
|
||||
b.sessions[0]!.endsAt = "2027-03-14T05:00:00.000Z";
|
||||
expect(messages(b)).toContain("sessions.0.endsAt: Session ends before it starts");
|
||||
});
|
||||
|
||||
it("only lets Cross Events take registrations", () => {
|
||||
const e = simple();
|
||||
expect(messages({ ...e, registration: { ...e.registration, mode: "origin", url: e.origin.url } })).toContain(
|
||||
'registration.mode: Only Cross Events takes registrations (mode "origin")',
|
||||
);
|
||||
expect(messages({ ...e, registration: { ...e.registration, status: "full" } })).toContain(
|
||||
'registration.status: Only Cross Events sends a registration status other than "open"',
|
||||
);
|
||||
});
|
||||
|
||||
it("needs a url for origin / external registration and none otherwise", () => {
|
||||
const e = base();
|
||||
expect(messages({ ...e, registration: { ...e.registration, url: null } })).toContain('registration.url: A "origin" registration needs a url');
|
||||
const s = simple();
|
||||
expect(messages({ ...s, registration: { ...s.registration, url: "https://example.com" } })).toContain('registration.url: A "contact" registration has no url');
|
||||
expect(messages({ ...s, registration: { ...s.registration, mode: "external", url: "https://forms.example.com/carols" } })).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a negative or fractional price, and a currency that isn't ISO 4217", () => {
|
||||
const e = base();
|
||||
for (const priceFrom of [{ amountCents: -1, currency: "ZAR" }, { amountCents: 1.5, currency: "ZAR" }, { amountCents: 100, currency: "rand" }]) {
|
||||
expect(messages({ ...e, registration: { ...e.registration, priceFrom } })).not.toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses non-UTC-ISO times and non-http URLs", () => {
|
||||
expect(messages({ ...base(), updatedAt: "3 November 2026" })).not.toEqual([]);
|
||||
expect(messages({ ...simple(), imageUrl: "javascript:alert(1)" })).not.toEqual([]);
|
||||
expect(messages({ ...simple(), imageUrl: "ftp://example.com/a.jpg" })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("identifies an event by origin product and id", () => {
|
||||
expect(eventKey(base())).toBe("events:8f1c2a4e-5b6d-4c7e-9f80-a1b2c3d4e5f6");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEventFeed", () => {
|
||||
it("skips a bad event and reports it, keeping the rest", () => {
|
||||
const feed = sample<{ events: unknown[] }>("event-feed.json");
|
||||
feed.events.push({ ...simple(), title: "" }, "not an event", simple());
|
||||
const result = parseEventFeed(feed);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.feed.events).toHaveLength(2);
|
||||
expect(result.rejected.map((r) => [r.index, r.id])).toEqual([
|
||||
[1, simple().id],
|
||||
[2, null],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the envelope itself is wrong", () => {
|
||||
expect(parseEventFeed({ schema: "crosscode.event-feed/1", events: [] }).ok).toBe(false);
|
||||
expect(parseEventFeed(null).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const SAMPLES = join(__dirname, "..", "samples");
|
||||
|
||||
/** A fresh copy of a sample payload from samples/. */
|
||||
export function sample<T extends object = Record<string, unknown>>(file: string): T {
|
||||
return JSON.parse(readFileSync(join(SAMPLES, file), "utf8")) as T;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import { hub } from "../src";
|
||||
import { HUB_HEADERS, LINK_HEADERS, sign, signedHeaders, verify } from "../src/signing";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
describe("Hub protocol v2", () => {
|
||||
it("picks the stats by product", () => {
|
||||
const events = sample<Record<string, unknown>>("hub-heartbeat-events.json");
|
||||
const website = sample<Record<string, unknown>>("hub-heartbeat-website.json");
|
||||
expect(hub.heartbeatRequestSchema.safeParse({ ...events, stats: website.stats }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses protocol v1 bodies (the Hub routes those to its v1 handler)", () => {
|
||||
expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), protocolVersion: 1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a licence token payload from a Hub before 2.0 (no customerId or product)", () => {
|
||||
const payload = sample<Record<string, unknown>>("hub-licence-payload.json");
|
||||
delete payload.customerId;
|
||||
delete payload.product;
|
||||
expect(hub.licencePayloadSchema.safeParse(payload).success).toBe(true);
|
||||
});
|
||||
|
||||
it("only sends income as a band", () => {
|
||||
const hb = sample<{ stats: { income: Record<string, unknown> } }>("hub-heartbeat-events.json");
|
||||
hb.stats.income.last30d = 12345;
|
||||
expect(hub.heartbeatRequestSchema.safeParse(hb).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, "0–100"],
|
||||
[100, "0–100"],
|
||||
[101, "101–300"],
|
||||
[750, "301–750"],
|
||||
[751, "751–2 000"],
|
||||
[5000, "2 001–5 000"],
|
||||
[5001, "over 5 000"],
|
||||
] as const)("puts %d active members in the %s band", (n, band) => {
|
||||
expect(hub.activeMemberBand(n)).toBe(band);
|
||||
});
|
||||
});
|
||||
|
||||
describe("signing", () => {
|
||||
const secret = "s3cret-for-tests";
|
||||
const body = JSON.stringify({ hello: "world" });
|
||||
const now = new Date("2026-11-03T10:00:00.000Z");
|
||||
|
||||
it("signs exactly like the Hub protocol v1 heartbeat", () => {
|
||||
const timestamp = now.toISOString();
|
||||
const expected = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
||||
expect(sign(secret, timestamp, body)).toBe(expected);
|
||||
expect(sign(secret, timestamp, new TextEncoder().encode(body))).toBe(expected);
|
||||
});
|
||||
|
||||
it("builds the headers and verifies them", () => {
|
||||
const h = signedHeaders(LINK_HEADERS, { senderId: "inst-1", secret, rawBody: body, now });
|
||||
expect(h[LINK_HEADERS.sender]).toBe("inst-1");
|
||||
expect(verify({ secret, timestamp: h[LINK_HEADERS.timestamp], signature: h[LINK_HEADERS.signature], rawBody: body, now })).toEqual({ ok: true });
|
||||
expect(Object.keys(signedHeaders(HUB_HEADERS, { senderId: "i", secret, rawBody: body, now }))).toEqual(["x-hub-install", "x-hub-timestamp", "x-hub-signature"]);
|
||||
});
|
||||
|
||||
it("refuses a changed body, a wrong secret or a bad signature", () => {
|
||||
const timestamp = now.toISOString();
|
||||
const signature = sign(secret, timestamp, body);
|
||||
expect(verify({ secret, timestamp, signature, rawBody: body + " ", now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret: "other", timestamp, signature, rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret, timestamp, signature: "zz", rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret, timestamp, signature: undefined, rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
});
|
||||
|
||||
it("refuses requests more than five minutes off the clock", () => {
|
||||
const old = new Date(now.getTime() - 5 * 60 * 1000 - 1).toISOString();
|
||||
expect(verify({ secret, timestamp: old, signature: sign(secret, old, body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" });
|
||||
const edge = new Date(now.getTime() - 5 * 60 * 1000).toISOString();
|
||||
expect(verify({ secret, timestamp: edge, signature: sign(secret, edge, body), rawBody: body, now })).toEqual({ ok: true });
|
||||
expect(verify({ secret, timestamp: "yesterday", signature: sign(secret, "yesterday", body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { decodeState, encodeState, isRegisteredRedirectUri, isSafeReturnPath, safeReturnPath } from "../src";
|
||||
|
||||
describe("isSafeReturnPath", () => {
|
||||
it.each([
|
||||
"/",
|
||||
"/dashboard",
|
||||
"/events/youth-camp/register?ticket=adult",
|
||||
"/events/youth-camp#details",
|
||||
"/search?q=youth%20camp",
|
||||
"/a/b/../c",
|
||||
"/caf%C3%A9",
|
||||
])("accepts %p", (path) => {
|
||||
expect(isSafeReturnPath(path)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["absolute URL", "https://evil.com/"],
|
||||
["protocol-relative", "//evil.com"],
|
||||
["backslash host", "/\\evil.com"],
|
||||
["backslash anywhere", "/events\\x"],
|
||||
["encoded slashes", "/%2F%2Fevil.com"],
|
||||
["encoded backslash", "/%5Cevil.com"],
|
||||
["double-encoded slashes", "/%252F%252Fevil.com"],
|
||||
["javascript:", "javascript:alert(1)"],
|
||||
["no leading slash", "dashboard"],
|
||||
["empty", ""],
|
||||
["tab", "/\t/evil.com"],
|
||||
["newline", "/events\n"],
|
||||
["encoded CR/LF", "/events%0D%0ALocation:%20https://evil.com"],
|
||||
["encoded tab before slashes", "/%09/evil.com"],
|
||||
["space", "/events/youth camp"],
|
||||
["bad percent-encoding", "/%E0%A4%A"],
|
||||
["too long", "/" + "a".repeat(2048)],
|
||||
])("refuses %s", (_label, path) => {
|
||||
expect(isSafeReturnPath(path)).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses non-strings", () => {
|
||||
for (const v of [undefined, null, 1, {}, ["/"]]) expect(isSafeReturnPath(v)).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the product's home page", () => {
|
||||
expect(safeReturnPath("//evil.com")).toBe("/");
|
||||
expect(safeReturnPath(undefined, "/dashboard")).toBe("/dashboard");
|
||||
expect(safeReturnPath("/events")).toBe("/events");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sign-in state", () => {
|
||||
const nonce = "n0nce-AbCdEfGhIjKl_123";
|
||||
|
||||
it("round-trips the nonce and the return path, query included", () => {
|
||||
const state = encodeState({ nonce, returnTo: "/events/youth-camp/register?ticket=adult&qty=2" });
|
||||
expect(state).toMatch(/^[A-Za-z0-9_-]+$/);
|
||||
expect(decodeState(state)).toEqual({ nonce, returnTo: "/events/youth-camp/register?ticket=adult&qty=2" });
|
||||
});
|
||||
|
||||
it("never carries an unsafe return path", () => {
|
||||
expect(decodeState(encodeState({ nonce, returnTo: "https://evil.com" }))).toEqual({ nonce, returnTo: "/" });
|
||||
const forged = Buffer.from(JSON.stringify({ n: nonce, r: "//evil.com" })).toString("base64url");
|
||||
expect(decodeState(forged, "/home")).toEqual({ nonce, returnTo: "/home" });
|
||||
});
|
||||
|
||||
it("refuses a short or missing nonce", () => {
|
||||
expect(() => encodeState({ nonce: "short", returnTo: "/" })).toThrow();
|
||||
expect(decodeState(Buffer.from(JSON.stringify({ r: "/" })).toString("base64url"))).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for anything that isn't a state", () => {
|
||||
for (const v of [undefined, "", "not base64!", Buffer.from("not json").toString("base64url"), Buffer.from("[1]").toString("base64url")]) {
|
||||
expect(decodeState(v)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("handles non-ASCII paths", () => {
|
||||
expect(decodeState(encodeState({ nonce, returnTo: "/caf%C3%A9" }))?.returnTo).toBe("/caf%C3%A9");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRegisteredRedirectUri", () => {
|
||||
const registered = ["https://events.hopefamily.co.za/auth/callback"];
|
||||
|
||||
it("only matches exactly", () => {
|
||||
expect(isRegisteredRedirectUri("https://events.hopefamily.co.za/auth/callback", registered)).toBe(true);
|
||||
for (const uri of [
|
||||
"https://events.hopefamily.co.za/auth/callback/",
|
||||
"https://events.hopefamily.co.za/auth/callback?x=1",
|
||||
"https://EVENTS.hopefamily.co.za/auth/callback",
|
||||
"https://events.hopefamily.co.za.evil.com/auth/callback",
|
||||
"http://events.hopefamily.co.za/auth/callback",
|
||||
]) {
|
||||
expect(isRegisteredRedirectUri(uri, registered)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readdirSync } from "node:fs";
|
||||
import type { z } from "zod";
|
||||
import {
|
||||
accountsCallSchema,
|
||||
churchSchema,
|
||||
eventChangedSchema,
|
||||
eventFeedSchema,
|
||||
eventSchema,
|
||||
hub,
|
||||
identityClaimsSchema,
|
||||
userDeletedReplySchema,
|
||||
userExportReplySchema,
|
||||
} from "../src";
|
||||
import { SAMPLES, sample } from "./helpers";
|
||||
|
||||
/** Every sample file and the schema it must pass. A new sample without an entry fails the test. */
|
||||
const SCHEMAS: Record<string, z.ZodType> = {
|
||||
"event.json": eventSchema,
|
||||
"event-simple.json": eventSchema,
|
||||
"event-feed.json": eventFeedSchema,
|
||||
"event-changed.json": eventChangedSchema,
|
||||
"church.json": churchSchema,
|
||||
"identity-claims.json": identityClaimsSchema,
|
||||
"user-updated.json": accountsCallSchema,
|
||||
"user-deleted.json": accountsCallSchema,
|
||||
"user-deleted-reply.json": userDeletedReplySchema,
|
||||
"user-export.json": accountsCallSchema,
|
||||
"user-export-reply.json": userExportReplySchema,
|
||||
"hub-register-request.json": hub.registerRequestSchema,
|
||||
"hub-register-response.json": hub.registerResponseSchema,
|
||||
"hub-heartbeat-events.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-website.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-app.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-accounts.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-response.json": hub.heartbeatResponseSchema,
|
||||
"hub-licence-payload.json": hub.licencePayloadSchema,
|
||||
};
|
||||
|
||||
describe("samples", () => {
|
||||
const files = readdirSync(SAMPLES).filter((f) => f.endsWith(".json"));
|
||||
|
||||
it("every sample has a schema", () => {
|
||||
expect(files.filter((f) => !(f in SCHEMAS))).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(Object.entries(SCHEMAS))("%s is valid", (file, schema) => {
|
||||
const result = schema.safeParse(sample(file));
|
||||
expect(result.success ? [] : result.error.issues).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(Object.entries(SCHEMAS))("%s keeps every field it sends (no field is silently dropped)", (file, schema) => {
|
||||
const input = sample(file);
|
||||
expect(schema.parse(input)).toEqual(input);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { defineConfig } from "tsup";
|
||||
// Dual build: CommonJS for the Cross Events backend and the Hub (they `require`), ESM for the
|
||||
// Next.js apps. Types for both.
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
entry: ["src/index.ts", "src/signing.ts"],
|
||||
format: ["cjs", "esm"],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
|
||||
Reference in New Issue
Block a user