From ea1575f7165c4fe17d0e2c934af50b80142291d6 Mon Sep 17 00:00:00 2001 From: joshua Date: Wed, 4 Nov 2026 09:47:40 +0200 Subject: [PATCH 1/2] 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 --- CHANGELOG.md | 19 ++ packages/contracts/README.md | 81 ++++- packages/contracts/package.json | 10 + packages/contracts/samples/church.json | 50 +++ packages/contracts/samples/event-changed.json | 6 + packages/contracts/samples/event-feed.json | 30 ++ packages/contracts/samples/event-simple.json | 32 ++ packages/contracts/samples/event.json | 36 ++ .../samples/hub-heartbeat-accounts.json | 19 ++ .../contracts/samples/hub-heartbeat-app.json | 21 ++ .../samples/hub-heartbeat-events.json | 26 ++ .../samples/hub-heartbeat-response.json | 33 ++ .../samples/hub-heartbeat-website.json | 21 ++ .../samples/hub-licence-payload.json | 15 + .../samples/hub-register-request.json | 15 + .../samples/hub-register-response.json | 17 + .../contracts/samples/identity-claims.json | 15 + .../contracts/samples/user-deleted-reply.json | 6 + packages/contracts/samples/user-deleted.json | 8 + .../contracts/samples/user-export-reply.json | 21 ++ packages/contracts/samples/user-export.json | 8 + packages/contracts/samples/user-updated.json | 17 + packages/contracts/src/church.ts | 99 ++++++ packages/contracts/src/common.ts | 57 ++++ packages/contracts/src/event.ts | 193 +++++++++++ packages/contracts/src/hub.ts | 307 ++++++++++++++++++ packages/contracts/src/identity.ts | 133 ++++++++ packages/contracts/src/index.ts | 12 +- packages/contracts/src/return-to.ts | 139 ++++++++ packages/contracts/src/signing.ts | 76 +++++ .../contracts/tests/church-identity.test.ts | 49 +++ packages/contracts/tests/event.test.ts | 102 ++++++ packages/contracts/tests/helpers.ts | 9 + packages/contracts/tests/hub-signing.test.ts | 78 +++++ packages/contracts/tests/return-to.test.ts | 95 ++++++ packages/contracts/tests/samples.test.ts | 55 ++++ packages/contracts/tsup.config.ts | 2 +- 37 files changed, 1889 insertions(+), 23 deletions(-) create mode 100644 packages/contracts/samples/church.json create mode 100644 packages/contracts/samples/event-changed.json create mode 100644 packages/contracts/samples/event-feed.json create mode 100644 packages/contracts/samples/event-simple.json create mode 100644 packages/contracts/samples/event.json create mode 100644 packages/contracts/samples/hub-heartbeat-accounts.json create mode 100644 packages/contracts/samples/hub-heartbeat-app.json create mode 100644 packages/contracts/samples/hub-heartbeat-events.json create mode 100644 packages/contracts/samples/hub-heartbeat-response.json create mode 100644 packages/contracts/samples/hub-heartbeat-website.json create mode 100644 packages/contracts/samples/hub-licence-payload.json create mode 100644 packages/contracts/samples/hub-register-request.json create mode 100644 packages/contracts/samples/hub-register-response.json create mode 100644 packages/contracts/samples/identity-claims.json create mode 100644 packages/contracts/samples/user-deleted-reply.json create mode 100644 packages/contracts/samples/user-deleted.json create mode 100644 packages/contracts/samples/user-export-reply.json create mode 100644 packages/contracts/samples/user-export.json create mode 100644 packages/contracts/samples/user-updated.json create mode 100644 packages/contracts/src/church.ts create mode 100644 packages/contracts/src/common.ts create mode 100644 packages/contracts/src/event.ts create mode 100644 packages/contracts/src/hub.ts create mode 100644 packages/contracts/src/identity.ts create mode 100644 packages/contracts/src/return-to.ts create mode 100644 packages/contracts/src/signing.ts create mode 100644 packages/contracts/tests/church-identity.test.ts create mode 100644 packages/contracts/tests/event.test.ts create mode 100644 packages/contracts/tests/helpers.ts create mode 100644 packages/contracts/tests/hub-signing.test.ts create mode 100644 packages/contracts/tests/return-to.test.ts create mode 100644 packages/contracts/tests/samples.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index daf2cc5..d08a2f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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./`). - `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. diff --git a/packages/contracts/README.md b/packages/contracts/README.md index 714ab9d..87aebb0 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -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./`. +- Every payload carries its `schema` name: `crosscode./` (`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 diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 6e6c812..7393b64 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -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": [ diff --git a/packages/contracts/samples/church.json b/packages/contracts/samples/church.json new file mode 100644 index 0000000..9fbdbad --- /dev/null +++ b/packages/contracts/samples/church.json @@ -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" + } +} diff --git a/packages/contracts/samples/event-changed.json b/packages/contracts/samples/event-changed.json new file mode 100644 index 0000000..dddd42f --- /dev/null +++ b/packages/contracts/samples/event-changed.json @@ -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"] +} diff --git a/packages/contracts/samples/event-feed.json b/packages/contracts/samples/event-feed.json new file mode 100644 index 0000000..d5633a5 --- /dev/null +++ b/packages/contracts/samples/event-feed.json @@ -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" } + ] +} diff --git a/packages/contracts/samples/event-simple.json b/packages/contracts/samples/event-simple.json new file mode 100644 index 0000000..942e651 --- /dev/null +++ b/packages/contracts/samples/event-simple.json @@ -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 + } +} diff --git a/packages/contracts/samples/event.json b/packages/contracts/samples/event.json new file mode 100644 index 0000000..0afc4dd --- /dev/null +++ b/packages/contracts/samples/event.json @@ -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" } + } +} diff --git a/packages/contracts/samples/hub-heartbeat-accounts.json b/packages/contracts/samples/hub-heartbeat-accounts.json new file mode 100644 index 0000000..793df17 --- /dev/null +++ b/packages/contracts/samples/hub-heartbeat-accounts.json @@ -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 + } +} diff --git a/packages/contracts/samples/hub-heartbeat-app.json b/packages/contracts/samples/hub-heartbeat-app.json new file mode 100644 index 0000000..d2385c8 --- /dev/null +++ b/packages/contracts/samples/hub-heartbeat-app.json @@ -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 } + } +} diff --git a/packages/contracts/samples/hub-heartbeat-events.json b/packages/contracts/samples/hub-heartbeat-events.json new file mode 100644 index 0000000..71e82fa --- /dev/null +++ b/packages/contracts/samples/hub-heartbeat-events.json @@ -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" } + } +} diff --git a/packages/contracts/samples/hub-heartbeat-response.json b/packages/contracts/samples/hub-heartbeat-response.json new file mode 100644 index 0000000..cbec433 --- /dev/null +++ b/packages/contracts/samples/hub-heartbeat-response.json @@ -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" +} diff --git a/packages/contracts/samples/hub-heartbeat-website.json b/packages/contracts/samples/hub-heartbeat-website.json new file mode 100644 index 0000000..b4c1abd --- /dev/null +++ b/packages/contracts/samples/hub-heartbeat-website.json @@ -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 } + } +} diff --git a/packages/contracts/samples/hub-licence-payload.json b/packages/contracts/samples/hub-licence-payload.json new file mode 100644 index 0000000..1d55331 --- /dev/null +++ b/packages/contracts/samples/hub-licence-payload.json @@ -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 } +} diff --git a/packages/contracts/samples/hub-register-request.json b/packages/contracts/samples/hub-register-request.json new file mode 100644 index 0000000..23c5f95 --- /dev/null +++ b/packages/contracts/samples/hub-register-request.json @@ -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" + } +} diff --git a/packages/contracts/samples/hub-register-response.json b/packages/contracts/samples/hub-register-response.json new file mode 100644 index 0000000..c7b3eb9 --- /dev/null +++ b/packages/contracts/samples/hub-register-response.json @@ -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" + } + ] +} diff --git a/packages/contracts/samples/identity-claims.json b/packages/contracts/samples/identity-claims.json new file mode 100644 index 0000000..8e542dc --- /dev/null +++ b/packages/contracts/samples/identity-claims.json @@ -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 +} diff --git a/packages/contracts/samples/user-deleted-reply.json b/packages/contracts/samples/user-deleted-reply.json new file mode 100644 index 0000000..c8a5dc5 --- /dev/null +++ b/packages/contracts/samples/user-deleted-reply.json @@ -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" +} diff --git a/packages/contracts/samples/user-deleted.json b/packages/contracts/samples/user-deleted.json new file mode 100644 index 0000000..c61731a --- /dev/null +++ b/packages/contracts/samples/user-deleted.json @@ -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" +} diff --git a/packages/contracts/samples/user-export-reply.json b/packages/contracts/samples/user-export-reply.json new file mode 100644 index 0000000..29a4cf2 --- /dev/null +++ b/packages/contracts/samples/user-export-reply.json @@ -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": [] + } + ] +} diff --git a/packages/contracts/samples/user-export.json b/packages/contracts/samples/user-export.json new file mode 100644 index 0000000..11bee65 --- /dev/null +++ b/packages/contracts/samples/user-export.json @@ -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" +} diff --git a/packages/contracts/samples/user-updated.json b/packages/contracts/samples/user-updated.json new file mode 100644 index 0000000..1cce332 --- /dev/null +++ b/packages/contracts/samples/user-updated.json @@ -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 } + } +} diff --git a/packages/contracts/src/church.ts b/packages/contracts/src/church.ts new file mode 100644 index 0000000..911a51f --- /dev/null +++ b/packages/contracts/src/church.ts @@ -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; + +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; +export type Campus = z.infer; +export type ServiceTime = z.infer; diff --git a/packages/contracts/src/common.ts b/packages/contracts/src/common.ts new file mode 100644 index 0000000..0afbc39 --- /dev/null +++ b/packages/contracts/src/common.ts @@ -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; + +/** 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; + +/** 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; + +/** 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"); diff --git a/packages/contracts/src/event.ts b/packages/contracts/src/event.ts new file mode 100644 index 0000000..9c61391 --- /dev/null +++ b/packages/contracts/src/event.ts @@ -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; +export type EventSession = z.infer; +export type EventRegistration = z.infer; + +/** 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=` → `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; + +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; + +/** The key that identifies an event across products: `origin.product` + `id` (ROADMAP-v3 §4, "No duplicates"). */ +export function eventKey(event: Pick): string { + return `${event.origin.product}:${event.id}`; +} diff --git a/packages/contracts/src/hub.ts b/packages/contracts/src/hub.ts new file mode 100644 index 0000000..7a6dd6a --- /dev/null +++ b/packages/contracts/src/hub.ts @@ -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; + +// --------------------------------------------------------------------------------------------- +// 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; + +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; + +// --------------------------------------------------------------------------------------------- +// 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; + +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; + +// --------------------------------------------------------------------------------------------- +// 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; + +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; + +// --------------------------------------------------------------------------------------------- +// 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; + +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..">` +// --------------------------------------------------------------------------------------------- + +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; diff --git a/packages/contracts/src/identity.ts b/packages/contracts/src/identity.ts new file mode 100644 index 0000000..71f9479 --- /dev/null +++ b/packages/contracts/src/identity.ts @@ -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; + +export const newsConsentSchema = z.object({ + email: z.boolean(), + whatsapp: z.boolean(), +}); +export type NewsConsent = z.infer; + +/** 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; + +/** + * 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; + +// --------------------------------------------------------------------------------------------- +// Back-channel calls: Accounts → product, `POST /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; +export type UserUpdated = z.infer; +export type UserDeleted = z.infer; +export type UserExport = z.infer; + +/** 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; + +/** 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; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 93b82fd..970ca6e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -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"; diff --git a/packages/contracts/src/return-to.ts b/packages/contracts/src/return-to.ts new file mode 100644 index 0000000..362acc6 --- /dev/null +++ b/packages/contracts/src/return-to.ts @@ -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); +} diff --git a/packages/contracts/src/signing.ts b/packages/contracts/src/signing.ts new file mode 100644 index 0000000..e559d98 --- /dev/null +++ b/packages/contracts/src/signing.ts @@ -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 { + 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" }; +} diff --git a/packages/contracts/tests/church-identity.test.ts b/packages/contracts/tests/church-identity.test.ts new file mode 100644 index 0000000..ffca40c --- /dev/null +++ b/packages/contracts/tests/church-identity.test.ts @@ -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.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); + }); +}); diff --git a/packages/contracts/tests/event.test.ts b/packages/contracts/tests/event.test.ts new file mode 100644 index 0000000..6a4b718 --- /dev/null +++ b/packages/contracts/tests/event.test.ts @@ -0,0 +1,102 @@ +import { eventKey, eventSchema, parseEventFeed } from "../src"; +import type { CrosscodeEvent } from "../src"; +import { sample } from "./helpers"; + +const base = () => sample("event.json"); +const simple = () => sample("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); + }); +}); diff --git a/packages/contracts/tests/helpers.ts b/packages/contracts/tests/helpers.ts new file mode 100644 index 0000000..f82050b --- /dev/null +++ b/packages/contracts/tests/helpers.ts @@ -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>(file: string): T { + return JSON.parse(readFileSync(join(SAMPLES, file), "utf8")) as T; +} diff --git a/packages/contracts/tests/hub-signing.test.ts b/packages/contracts/tests/hub-signing.test.ts new file mode 100644 index 0000000..6668aa0 --- /dev/null +++ b/packages/contracts/tests/hub-signing.test.ts @@ -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>("hub-heartbeat-events.json"); + const website = sample>("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>("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 } }>("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" }); + }); +}); diff --git a/packages/contracts/tests/return-to.test.ts b/packages/contracts/tests/return-to.test.ts new file mode 100644 index 0000000..5b3b983 --- /dev/null +++ b/packages/contracts/tests/return-to.test.ts @@ -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); + } + }); +}); diff --git a/packages/contracts/tests/samples.test.ts b/packages/contracts/tests/samples.test.ts new file mode 100644 index 0000000..f246670 --- /dev/null +++ b/packages/contracts/tests/samples.test.ts @@ -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 = { + "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); + }); +}); diff --git a/packages/contracts/tsup.config.ts b/packages/contracts/tsup.config.ts index d2a87c3..5ddfa51 100644 --- a/packages/contracts/tsup.config.ts +++ b/packages/contracts/tsup.config.ts @@ -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, From 9e94c8250242d398c998dc0098e14c035b8305a7 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 4 Nov 2026 14:30:37 +0200 Subject: [PATCH 2/2] Contracts 1.0.0: generated JSON Schema for every contract - schemas/: JSON Schema (draft 2020-12) generated from the zod schemas by npm run build (scripts/json-schemas.cjs), exported as @crosscode/contracts/schemas/* - Test: files match the zod schemas, every sample passes them (Ajv) - Version 1.0.0, CHANGELOG and README Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +- eslint.config.mjs | 2 +- package-lock.json | 97 ++ packages/contracts/README.md | 11 +- packages/contracts/package.json | 9 +- packages/contracts/schemas/accounts-call.json | 204 ++++ packages/contracts/schemas/church.json | 549 +++++++++++ packages/contracts/schemas/event-changed.json | 35 + packages/contracts/schemas/event-feed.json | 440 +++++++++ packages/contracts/schemas/event.json | 395 ++++++++ packages/contracts/schemas/health.json | 96 ++ .../schemas/hub-ai-complete-request.json | 49 + .../schemas/hub-ai-complete-response.json | 86 ++ .../schemas/hub-ai-status-request.json | 14 + packages/contracts/schemas/hub-ai-status.json | 38 + packages/contracts/schemas/hub-error.json | 18 + .../schemas/hub-heartbeat-request.json | 922 ++++++++++++++++++ .../schemas/hub-heartbeat-response.json | 163 ++++ .../schemas/hub-licence-payload.json | 101 ++ .../schemas/hub-public-key-response.json | 32 + .../schemas/hub-register-request.json | 154 +++ .../schemas/hub-register-response.json | 174 ++++ .../hub-update-request-cancel-response.json | 13 + .../schemas/hub-update-request-cancel.json | 14 + .../schemas/hub-update-request-response.json | 32 + .../contracts/schemas/hub-update-request.json | 19 + .../contracts/schemas/identity-claims.json | 125 +++ .../contracts/schemas/user-deleted-reply.json | 52 + packages/contracts/schemas/user-deleted.json | 43 + .../contracts/schemas/user-export-reply.json | 77 ++ packages/contracts/schemas/user-export.json | 43 + .../contracts/schemas/user-updated-reply.json | 19 + packages/contracts/schemas/user-updated.json | 118 +++ packages/contracts/scripts/json-schemas.cjs | 101 ++ packages/contracts/tests/json-schemas.test.ts | 82 ++ 35 files changed, 4330 insertions(+), 5 deletions(-) create mode 100644 packages/contracts/schemas/accounts-call.json create mode 100644 packages/contracts/schemas/church.json create mode 100644 packages/contracts/schemas/event-changed.json create mode 100644 packages/contracts/schemas/event-feed.json create mode 100644 packages/contracts/schemas/event.json create mode 100644 packages/contracts/schemas/health.json create mode 100644 packages/contracts/schemas/hub-ai-complete-request.json create mode 100644 packages/contracts/schemas/hub-ai-complete-response.json create mode 100644 packages/contracts/schemas/hub-ai-status-request.json create mode 100644 packages/contracts/schemas/hub-ai-status.json create mode 100644 packages/contracts/schemas/hub-error.json create mode 100644 packages/contracts/schemas/hub-heartbeat-request.json create mode 100644 packages/contracts/schemas/hub-heartbeat-response.json create mode 100644 packages/contracts/schemas/hub-licence-payload.json create mode 100644 packages/contracts/schemas/hub-public-key-response.json create mode 100644 packages/contracts/schemas/hub-register-request.json create mode 100644 packages/contracts/schemas/hub-register-response.json create mode 100644 packages/contracts/schemas/hub-update-request-cancel-response.json create mode 100644 packages/contracts/schemas/hub-update-request-cancel.json create mode 100644 packages/contracts/schemas/hub-update-request-response.json create mode 100644 packages/contracts/schemas/hub-update-request.json create mode 100644 packages/contracts/schemas/identity-claims.json create mode 100644 packages/contracts/schemas/user-deleted-reply.json create mode 100644 packages/contracts/schemas/user-deleted.json create mode 100644 packages/contracts/schemas/user-export-reply.json create mode 100644 packages/contracts/schemas/user-export.json create mode 100644 packages/contracts/schemas/user-updated-reply.json create mode 100644 packages/contracts/schemas/user-updated.json create mode 100644 packages/contracts/scripts/json-schemas.cjs create mode 100644 packages/contracts/tests/json-schemas.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d08a2f1..f40b876 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a ## Unreleased +## contracts@1.0.0 - 2026-11-04 + ### Monorepo - Set up: npm workspaces (`packages/*`, `apps/*`), shared TypeScript, ESLint and Jest setup, @@ -12,7 +14,7 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a schema-name helpers every contract uses (`crosscode./`). - `packages/ui`, `apps/accounts`, `apps/website`, `apps/app`: placeholders. -### Contracts (towards 1.0.0) +### Contracts - `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 @@ -30,3 +32,7 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `a 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. +- **JSON Schema** (draft 2020-12) for every contract in `schemas/`, generated from the zod + schemas by `npm run build` (`scripts/json-schemas.cjs`), for consumers that don't use + TypeScript or zod. A test checks the files match the zod schemas and that every sample passes + them (Ajv). Checks JSON Schema can't express (e.g. `startsAt` matching the sessions) only run in zod. diff --git a/eslint.config.mjs b/eslint.config.mjs index 4f4f856..5844573 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -8,7 +8,7 @@ export default defineConfig([ ...tseslint.configs.recommended, { files: ["**/*.cjs", "**/jest.config.js"], - languageOptions: { sourceType: "commonjs", globals: { module: "writable", require: "readonly" } }, + languageOptions: { sourceType: "commonjs", globals: { module: "writable", require: "readonly", __dirname: "readonly", process: "readonly", console: "readonly" } }, rules: { "@typescript-eslint/no-require-imports": "off" }, }, { diff --git a/package-lock.json b/package-lock.json index 99271fc..4604a1a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3363,6 +3363,48 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -4318,6 +4360,23 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fb-watchman": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.4.tgz", @@ -6212,6 +6271,16 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/resolve-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", @@ -7210,8 +7279,36 @@ "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" + }, + "devDependencies": { + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1" } }, + "packages/contracts/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "packages/contracts/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "packages/ui": { "name": "@crosscode/ui", "version": "0.0.0" diff --git a/packages/contracts/README.md b/packages/contracts/README.md index 87aebb0..b7fbb65 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -1,7 +1,7 @@ # @crosscode/contracts Everything that crosses between Cross Code products is defined once, here (ROADMAP-v3 §2): -zod schemas, TypeScript types and sample payloads (`samples/`). Every product, including Cross +zod schemas, JSON Schema (`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 | Schema name | Used for | Source | @@ -62,6 +62,15 @@ for install → Hub; `LINK_HEADERS` (`X-Crosscode-Sender`, `-Timestamp`, `-Signa `event.changed` webhooks and Accounts back-channel calls, with the secret set up by **Connect**. Verify the raw bytes before parsing the JSON. +### JSON Schema + +`schemas/` has a JSON Schema (draft 2020-12) for every contract, for consumers that don't use +TypeScript or zod (e.g. `@crosscode/contracts/schemas/event.json`). They are generated from the +zod schemas by `npm run build`; commit them with the change (a test fails when they're out of +date). They allow unknown fields, like the zod schemas. The zod schemas stay the source of truth: +a few checks can't be written in JSON Schema (e.g. `startsAt` / `endsAt` matching the sessions, +only Cross Events using `registration.mode: "origin"`), so use the zod schemas where you can. + ## Versioning - Every payload carries its `schema` name: `crosscode./` (`parseSchemaName`, `isSchema`). diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 7393b64..9f1f12f 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/contracts", - "version": "0.1.0", + "version": "1.0.0", "description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads", "license": "UNLICENSED", "type": "commonjs", @@ -28,6 +28,7 @@ "default": "./dist/signing.js" } }, + "./schemas/*": "./schemas/*", "./package.json": "./package.json" }, "files": [ @@ -38,7 +39,7 @@ ], "sideEffects": false, "scripts": { - "build": "tsup", + "build": "tsup && node scripts/json-schemas.cjs", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "jest" }, @@ -52,5 +53,9 @@ "type": "git", "url": "https://c-git.crosscode.co.za/joshua/crosscode-platform.git", "directory": "packages/contracts" + }, + "devDependencies": { + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1" } } diff --git a/packages/contracts/schemas/accounts-call.json b/packages/contracts/schemas/accounts-call.json new file mode 100644 index 0000000..c0a59c2 --- /dev/null +++ b/packages/contracts/schemas/accounts-call.json @@ -0,0 +1,204 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/accounts-call.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "oneOf": [ + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.updated" + }, + "profile": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "given_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "family_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "email": { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + "email_verified": { + "type": "boolean" + }, + "phone_number": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + { + "type": "null" + } + ] + }, + "phone_number_verified": { + "type": "boolean" + }, + "news_consent": { + "type": "object", + "properties": { + "email": { + "type": "boolean" + }, + "whatsapp": { + "type": "boolean" + } + }, + "required": [ + "email", + "whatsapp" + ] + } + }, + "required": [ + "name", + "given_name", + "family_name", + "email", + "email_verified", + "phone_number", + "phone_number_verified", + "news_consent" + ] + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "profile" + ] + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.deleted" + }, + "approvedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "approvedAt" + ] + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.export" + }, + "exportId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "exportId" + ] + } + ] +} diff --git a/packages/contracts/schemas/church.json b/packages/contracts/schemas/church.json new file mode 100644 index 0000000..81f8b3b --- /dev/null +++ b/packages/contracts/schemas/church.json @@ -0,0 +1,549 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/church.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.church/1" + }, + "customerId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "shortName": { + "anyOf": [ + { + "type": "string", + "maxLength": 30 + }, + { + "type": "null" + } + ] + }, + "timezone": { + "type": "string", + "pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$" + }, + "locale": { + "type": "string", + "pattern": "^[a-z]{2,3}(-[A-Z]{2})?$" + }, + "branding": { + "type": "object", + "properties": { + "logoUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "iconUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "colours": { + "type": "object", + "properties": { + "primary": { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + }, + "accent": { + "anyOf": [ + { + "type": "string", + "pattern": "^#[0-9a-fA-F]{6}$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "primary", + "accent" + ] + } + }, + "required": [ + "logoUrl", + "iconUrl", + "colours" + ] + }, + "campuses": { + "maxItems": 50, + "type": "array", + "items": { + "type": "object", + "properties": { + "slug": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "address": { + "anyOf": [ + { + "type": "object", + "properties": { + "line1": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "line2": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "suburb": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "city": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "province": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "postalCode": { + "anyOf": [ + { + "type": "string", + "maxLength": 20 + }, + { + "type": "null" + } + ] + }, + "country": { + "type": "string", + "pattern": "^[A-Z]{2}$" + }, + "geo": { + "anyOf": [ + { + "type": "object", + "properties": { + "lat": { + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "lng": { + "type": "number", + "minimum": -180, + "maximum": 180 + } + }, + "required": [ + "lat", + "lng" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "line1", + "line2", + "suburb", + "city", + "province", + "postalCode", + "country", + "geo" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "slug", + "name", + "address" + ] + } + }, + "serviceTimes": { + "maxItems": 100, + "type": "array", + "items": { + "type": "object", + "properties": { + "day": { + "type": "string", + "enum": [ + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + "sunday" + ] + }, + "time": { + "type": "string", + "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$" + }, + "label": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "campus": { + "anyOf": [ + { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + }, + { + "type": "null" + } + ] + }, + "note": { + "anyOf": [ + { + "type": "string", + "maxLength": 300 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "day", + "time", + "label", + "campus", + "note" + ] + } + }, + "contact": { + "type": "object", + "properties": { + "email": { + "anyOf": [ + { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + { + "type": "null" + } + ] + }, + "phone": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + { + "type": "null" + } + ] + }, + "whatsapp": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + { + "type": "null" + } + ] + }, + "address": { + "anyOf": [ + { + "type": "object", + "properties": { + "line1": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "line2": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "suburb": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "city": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "province": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "postalCode": { + "anyOf": [ + { + "type": "string", + "maxLength": 20 + }, + { + "type": "null" + } + ] + }, + "country": { + "type": "string", + "pattern": "^[A-Z]{2}$" + }, + "geo": { + "anyOf": [ + { + "type": "object", + "properties": { + "lat": { + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "lng": { + "type": "number", + "minimum": -180, + "maximum": 180 + } + }, + "required": [ + "lat", + "lng" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "line1", + "line2", + "suburb", + "city", + "province", + "postalCode", + "country", + "geo" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "email", + "phone", + "whatsapp", + "address" + ] + }, + "social": { + "maxItems": 20, + "type": "array", + "items": { + "type": "object", + "properties": { + "network": { + "type": "string", + "enum": [ + "facebook", + "instagram", + "youtube", + "tiktok", + "x", + "spotify", + "whatsapp-channel", + "other" + ] + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "network", + "url" + ] + } + }, + "links": { + "type": "object", + "properties": { + "website": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "events": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "app": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "accounts": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "website", + "events", + "app", + "accounts" + ] + } + }, + "required": [ + "schema", + "customerId", + "updatedAt", + "name", + "shortName", + "timezone", + "locale", + "branding", + "campuses", + "serviceTimes", + "contact", + "social", + "links" + ] +} diff --git a/packages/contracts/schemas/event-changed.json b/packages/contracts/schemas/event-changed.json new file mode 100644 index 0000000..1ef7a49 --- /dev/null +++ b/packages/contracts/schemas/event-changed.json @@ -0,0 +1,35 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/event-changed.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event-feed/1" + }, + "type": { + "type": "string", + "const": "event.changed" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "eventIds": { + "maxItems": 100, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + } + }, + "required": [ + "schema", + "type", + "occurredAt", + "eventIds" + ] +} diff --git a/packages/contracts/schemas/event-feed.json b/packages/contracts/schemas/event-feed.json new file mode 100644 index 0000000..17247e8 --- /dev/null +++ b/packages/contracts/schemas/event-feed.json @@ -0,0 +1,440 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/event-feed.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event-feed/1" + }, + "generatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "events": { + "type": "array", + "items": { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event/1" + }, + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "origin": { + "type": "object", + "properties": { + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app" + ] + }, + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "product", + "installId", + "url" + ] + }, + "status": { + "type": "string", + "enum": [ + "published", + "cancelled" + ] + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "summary": { + "anyOf": [ + { + "type": "string", + "maxLength": 300 + }, + { + "type": "null" + } + ] + }, + "description": { + "anyOf": [ + { + "type": "string", + "maxLength": 20000 + }, + { + "type": "null" + } + ] + }, + "imageUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "timezone": { + "type": "string", + "pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$" + }, + "startsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "endsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "allDay": { + "type": "boolean" + }, + "sessions": { + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "label": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "startsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "endsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "location": { + "anyOf": [ + { + "type": "string", + "maxLength": 300 + }, + { + "type": "null" + } + ] + }, + "cancelled": { + "type": "boolean" + } + }, + "required": [ + "id", + "label", + "startsAt", + "endsAt", + "location", + "cancelled" + ] + } + }, + "location": { + "anyOf": [ + { + "type": "object", + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "address": { + "anyOf": [ + { + "type": "string", + "maxLength": 500 + }, + { + "type": "null" + } + ] + }, + "onlineUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name", + "address", + "onlineUrl" + ] + }, + { + "type": "null" + } + ] + }, + "campus": { + "anyOf": [ + { + "type": "object", + "properties": { + "slug": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "slug", + "name" + ] + }, + { + "type": "null" + } + ] + }, + "series": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "id", + "name" + ] + }, + { + "type": "null" + } + ] + }, + "tags": { + "maxItems": 20, + "type": "array", + "items": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + } + }, + "registration": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "origin", + "external", + "contact", + "none" + ] + }, + "url": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "status": { + "type": "string", + "enum": [ + "open", + "not_open", + "closed", + "full", + "waitlist" + ] + }, + "opensAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "closesAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "priceFrom": { + "anyOf": [ + { + "type": "object", + "properties": { + "amountCents": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "currency": { + "type": "string", + "pattern": "^[A-Z]{3}$" + } + }, + "required": [ + "amountCents", + "currency" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "mode", + "url", + "status", + "opensAt", + "closesAt", + "priceFrom" + ] + } + }, + "required": [ + "schema", + "id", + "origin", + "status", + "updatedAt", + "title", + "summary", + "description", + "imageUrl", + "timezone", + "startsAt", + "endsAt", + "allDay", + "sessions", + "location", + "campus", + "series", + "tags", + "registration" + ] + } + }, + "deleted": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "deletedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "id", + "deletedAt" + ] + } + } + }, + "required": [ + "schema", + "generatedAt", + "events", + "deleted" + ] +} diff --git a/packages/contracts/schemas/event.json b/packages/contracts/schemas/event.json new file mode 100644 index 0000000..7063a08 --- /dev/null +++ b/packages/contracts/schemas/event.json @@ -0,0 +1,395 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/event.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.event/1" + }, + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "origin": { + "type": "object", + "properties": { + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app" + ] + }, + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "product", + "installId", + "url" + ] + }, + "status": { + "type": "string", + "enum": [ + "published", + "cancelled" + ] + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "summary": { + "anyOf": [ + { + "type": "string", + "maxLength": 300 + }, + { + "type": "null" + } + ] + }, + "description": { + "anyOf": [ + { + "type": "string", + "maxLength": 20000 + }, + { + "type": "null" + } + ] + }, + "imageUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "timezone": { + "type": "string", + "pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$" + }, + "startsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "endsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "allDay": { + "type": "boolean" + }, + "sessions": { + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "label": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "startsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "endsAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "location": { + "anyOf": [ + { + "type": "string", + "maxLength": 300 + }, + { + "type": "null" + } + ] + }, + "cancelled": { + "type": "boolean" + } + }, + "required": [ + "id", + "label", + "startsAt", + "endsAt", + "location", + "cancelled" + ] + } + }, + "location": { + "anyOf": [ + { + "type": "object", + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "address": { + "anyOf": [ + { + "type": "string", + "maxLength": 500 + }, + { + "type": "null" + } + ] + }, + "onlineUrl": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name", + "address", + "onlineUrl" + ] + }, + { + "type": "null" + } + ] + }, + "campus": { + "anyOf": [ + { + "type": "object", + "properties": { + "slug": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "slug", + "name" + ] + }, + { + "type": "null" + } + ] + }, + "series": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "id", + "name" + ] + }, + { + "type": "null" + } + ] + }, + "tags": { + "maxItems": 20, + "type": "array", + "items": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" + } + }, + "registration": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "origin", + "external", + "contact", + "none" + ] + }, + "url": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + { + "type": "null" + } + ] + }, + "status": { + "type": "string", + "enum": [ + "open", + "not_open", + "closed", + "full", + "waitlist" + ] + }, + "opensAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "closesAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "priceFrom": { + "anyOf": [ + { + "type": "object", + "properties": { + "amountCents": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "currency": { + "type": "string", + "pattern": "^[A-Z]{3}$" + } + }, + "required": [ + "amountCents", + "currency" + ] + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "mode", + "url", + "status", + "opensAt", + "closesAt", + "priceFrom" + ] + } + }, + "required": [ + "schema", + "id", + "origin", + "status", + "updatedAt", + "title", + "summary", + "description", + "imageUrl", + "timezone", + "startsAt", + "endsAt", + "allDay", + "sessions", + "location", + "campus", + "series", + "tags", + "registration" + ] +} diff --git a/packages/contracts/schemas/health.json b/packages/contracts/schemas/health.json new file mode 100644 index 0000000..45e16b6 --- /dev/null +++ b/packages/contracts/schemas/health.json @@ -0,0 +1,96 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/health.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "uptimeSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "db": { + "type": "boolean" + }, + "jobs": { + "type": "object", + "properties": { + "mode": { + "type": "string" + }, + "failedLast24h": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "mode", + "failedLast24h" + ] + }, + "lastBackupAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "disk": { + "anyOf": [ + { + "type": "object", + "properties": { + "freeBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totalBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "freeBytes", + "totalBytes" + ] + }, + { + "type": "null" + } + ] + }, + "errorsLast24h": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "pendingMigrations": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "uptimeSeconds", + "db", + "jobs", + "lastBackupAt", + "disk", + "errorsLast24h", + "pendingMigrations" + ] +} diff --git a/packages/contracts/schemas/hub-ai-complete-request.json b/packages/contracts/schemas/hub-ai-complete-request.json new file mode 100644 index 0000000..e178648 --- /dev/null +++ b/packages/contracts/schemas/hub-ai-complete-request.json @@ -0,0 +1,49 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-ai-complete-request.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "helper": { + "type": "string", + "maxLength": 60, + "pattern": "^[a-z][a-z0-9_]*$" + }, + "system": { + "type": "string" + }, + "input": { + "type": "string" + }, + "schema": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "maxTokens": { + "type": "integer", + "minimum": 1, + "maximum": 8000 + }, + "effort": { + "type": "string", + "enum": [ + "low", + "medium", + "high" + ] + } + }, + "required": [ + "protocolVersion", + "helper", + "system", + "input", + "maxTokens" + ] +} diff --git a/packages/contracts/schemas/hub-ai-complete-response.json b/packages/contracts/schemas/hub-ai-complete-response.json new file mode 100644 index 0000000..b421071 --- /dev/null +++ b/packages/contracts/schemas/hub-ai-complete-response.json @@ -0,0 +1,86 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-ai-complete-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "output": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + } + ] + }, + "usage": { + "type": "object", + "properties": { + "inputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "outputTokens": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "inputTokens", + "outputTokens" + ] + }, + "chargedCents": { + "type": "number", + "minimum": 0 + }, + "status": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "capReached": { + "type": "boolean" + }, + "capCents": { + "type": "number", + "minimum": 0 + }, + "usedCents": { + "type": "number", + "minimum": 0 + }, + "usedPercent": { + "type": "number", + "minimum": 0 + }, + "renewsOn": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + } + }, + "required": [ + "enabled", + "capReached", + "capCents", + "usedCents", + "usedPercent", + "renewsOn" + ] + } + }, + "required": [ + "output", + "usage", + "chargedCents", + "status" + ] +} diff --git a/packages/contracts/schemas/hub-ai-status-request.json b/packages/contracts/schemas/hub-ai-status-request.json new file mode 100644 index 0000000..9923b1c --- /dev/null +++ b/packages/contracts/schemas/hub-ai-status-request.json @@ -0,0 +1,14 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-ai-status-request.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + } + }, + "required": [ + "protocolVersion" + ] +} diff --git a/packages/contracts/schemas/hub-ai-status.json b/packages/contracts/schemas/hub-ai-status.json new file mode 100644 index 0000000..4e05a65 --- /dev/null +++ b/packages/contracts/schemas/hub-ai-status.json @@ -0,0 +1,38 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-ai-status.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "capReached": { + "type": "boolean" + }, + "capCents": { + "type": "number", + "minimum": 0 + }, + "usedCents": { + "type": "number", + "minimum": 0 + }, + "usedPercent": { + "type": "number", + "minimum": 0 + }, + "renewsOn": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$" + } + }, + "required": [ + "enabled", + "capReached", + "capCents", + "usedCents", + "usedPercent", + "renewsOn" + ] +} diff --git a/packages/contracts/schemas/hub-error.json b/packages/contracts/schemas/hub-error.json new file mode 100644 index 0000000..fbdda4a --- /dev/null +++ b/packages/contracts/schemas/hub-error.json @@ -0,0 +1,18 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-error.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]*$" + } + }, + "required": [ + "message", + "code" + ] +} diff --git a/packages/contracts/schemas/hub-heartbeat-request.json b/packages/contracts/schemas/hub-heartbeat-request.json new file mode 100644 index 0000000..de10033 --- /dev/null +++ b/packages/contracts/schemas/hub-heartbeat-request.json @@ -0,0 +1,922 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-heartbeat-request.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "oneOf": [ + { + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "health": { + "type": "object", + "properties": { + "uptimeSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "db": { + "type": "boolean" + }, + "jobs": { + "type": "object", + "properties": { + "mode": { + "type": "string" + }, + "failedLast24h": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "mode", + "failedLast24h" + ] + }, + "lastBackupAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "disk": { + "anyOf": [ + { + "type": "object", + "properties": { + "freeBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totalBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "freeBytes", + "totalBytes" + ] + }, + { + "type": "null" + } + ] + }, + "errorsLast24h": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "pendingMigrations": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "uptimeSeconds", + "db", + "jobs", + "lastBackupAt", + "disk", + "errorsLast24h", + "pendingMigrations" + ] + }, + "product": { + "type": "string", + "const": "events" + }, + "stats": { + "type": "object", + "properties": { + "users": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "events": { + "type": "object", + "properties": { + "active": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "upcoming": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "active", + "upcoming", + "total" + ] + }, + "registrations": { + "type": "object", + "properties": { + "last30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "last30d", + "total" + ] + }, + "tickets": { + "type": "object", + "properties": { + "last30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "last30d", + "total" + ] + }, + "checkIns": { + "type": "object", + "properties": { + "last30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "last30d" + ] + }, + "messages": { + "anyOf": [ + { + "type": "object", + "properties": { + "email30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "whatsapp30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "email30d", + "whatsapp30d" + ] + }, + { + "type": "null" + } + ] + }, + "paymentProviders": { + "type": "array", + "items": { + "type": "string" + } + }, + "campuses": { + "type": "boolean" + }, + "campusCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "income": { + "type": "object", + "properties": { + "last30d": { + "type": "string", + "enum": [ + "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" + ] + }, + "allTime": { + "type": "string", + "enum": [ + "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" + ] + }, + "eventIncome12m": { + "type": "string", + "enum": [ + "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" + ] + } + }, + "required": [ + "last30d", + "allTime", + "eventIncome12m" + ] + } + }, + "required": [ + "users", + "events", + "registrations", + "tickets", + "checkIns", + "messages", + "paymentProviders", + "campuses", + "campusCount", + "income" + ] + } + }, + "required": [ + "protocolVersion", + "version", + "health", + "product", + "stats" + ] + }, + { + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "health": { + "type": "object", + "properties": { + "uptimeSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "db": { + "type": "boolean" + }, + "jobs": { + "type": "object", + "properties": { + "mode": { + "type": "string" + }, + "failedLast24h": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "mode", + "failedLast24h" + ] + }, + "lastBackupAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "disk": { + "anyOf": [ + { + "type": "object", + "properties": { + "freeBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totalBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "freeBytes", + "totalBytes" + ] + }, + { + "type": "null" + } + ] + }, + "errorsLast24h": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "pendingMigrations": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "uptimeSeconds", + "db", + "jobs", + "lastBackupAt", + "disk", + "errorsLast24h", + "pendingMigrations" + ] + }, + "product": { + "type": "string", + "const": "website" + }, + "stats": { + "type": "object", + "properties": { + "pages": { + "type": "object", + "properties": { + "published": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "drafts": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "published", + "drafts" + ] + }, + "messages": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "last30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "total", + "last30d" + ] + }, + "events": { + "type": "object", + "properties": { + "upcomingSimple": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "imported": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "upcomingSimple", + "imported" + ] + }, + "editors": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "storage": { + "type": "object", + "properties": { + "usedBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "includedBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "usedBytes", + "includedBytes" + ] + } + }, + "required": [ + "pages", + "messages", + "events", + "editors", + "storage" + ] + } + }, + "required": [ + "protocolVersion", + "version", + "health", + "product", + "stats" + ] + }, + { + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "health": { + "type": "object", + "properties": { + "uptimeSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "db": { + "type": "boolean" + }, + "jobs": { + "type": "object", + "properties": { + "mode": { + "type": "string" + }, + "failedLast24h": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "mode", + "failedLast24h" + ] + }, + "lastBackupAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "disk": { + "anyOf": [ + { + "type": "object", + "properties": { + "freeBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totalBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "freeBytes", + "totalBytes" + ] + }, + { + "type": "null" + } + ] + }, + "errorsLast24h": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "pendingMigrations": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "uptimeSeconds", + "db", + "jobs", + "lastBackupAt", + "disk", + "errorsLast24h", + "pendingMigrations" + ] + }, + "product": { + "type": "string", + "const": "app" + }, + "stats": { + "type": "object", + "properties": { + "activeMembers90d": { + "type": "string", + "enum": [ + "0–100", + "101–300", + "301–750", + "751–2 000", + "2 001–5 000", + "over 5 000" + ] + }, + "modules": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]*$" + } + }, + "prayer": { + "type": "object", + "properties": { + "coverageLast7dPercent": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "activeCommitments": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "coverageLast7dPercent", + "activeCommitments" + ] + }, + "announcements": { + "type": "object", + "properties": { + "last30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "last30d" + ] + }, + "messages": { + "type": "object", + "properties": { + "email30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "whatsapp30d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "email30d", + "whatsapp30d" + ] + } + }, + "required": [ + "activeMembers90d", + "modules", + "prayer", + "announcements", + "messages" + ] + } + }, + "required": [ + "protocolVersion", + "version", + "health", + "product", + "stats" + ] + }, + { + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "health": { + "type": "object", + "properties": { + "uptimeSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "db": { + "type": "boolean" + }, + "jobs": { + "type": "object", + "properties": { + "mode": { + "type": "string" + }, + "failedLast24h": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "mode", + "failedLast24h" + ] + }, + "lastBackupAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "disk": { + "anyOf": [ + { + "type": "object", + "properties": { + "freeBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totalBytes": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "freeBytes", + "totalBytes" + ] + }, + { + "type": "null" + } + ] + }, + "errorsLast24h": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "pendingMigrations": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "uptimeSeconds", + "db", + "jobs", + "lastBackupAt", + "disk", + "errorsLast24h", + "pendingMigrations" + ] + }, + "product": { + "type": "string", + "const": "accounts" + }, + "stats": { + "type": "object", + "properties": { + "accounts": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "active90d": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "total", + "active90d" + ] + }, + "twoFactor": { + "type": "object", + "properties": { + "email": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "whatsapp": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "totp": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "off": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "email", + "whatsapp", + "totp", + "off" + ] + }, + "linkedProducts": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "accounts", + "twoFactor", + "linkedProducts" + ] + } + }, + "required": [ + "protocolVersion", + "version", + "health", + "product", + "stats" + ] + } + ] +} diff --git a/packages/contracts/schemas/hub-heartbeat-response.json b/packages/contracts/schemas/hub-heartbeat-response.json new file mode 100644 index 0000000..4e7805c --- /dev/null +++ b/packages/contracts/schemas/hub-heartbeat-response.json @@ -0,0 +1,163 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-heartbeat-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "licence": { + "type": "string" + }, + "latestVersion": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + { + "type": "null" + } + ] + }, + "releases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "releasedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "urgent": { + "type": "boolean" + }, + "notes": { + "type": "string" + } + }, + "required": [ + "version", + "releasedAt", + "urgent", + "notes" + ] + } + }, + "notices": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "level": { + "type": "string", + "enum": [ + "info", + "maintenance", + "warning" + ] + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "startsAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "endsAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "id", + "level", + "title", + "message", + "startsAt", + "endsAt", + "updatedAt" + ] + } + }, + "linkedProducts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app", + "accounts" + ] + }, + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + } + }, + "required": [ + "product", + "installId", + "url", + "publicKey" + ] + } + }, + "serverTime": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "licence", + "latestVersion", + "releases", + "notices", + "linkedProducts", + "serverTime" + ] +} diff --git a/packages/contracts/schemas/hub-licence-payload.json b/packages/contracts/schemas/hub-licence-payload.json new file mode 100644 index 0000000..17c5a84 --- /dev/null +++ b/packages/contracts/schemas/hub-licence-payload.json @@ -0,0 +1,101 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-licence-payload.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "v": { + "type": "number", + "const": 1 + }, + "licenceId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "customerId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app", + "accounts" + ] + }, + "customer": { + "type": "string" + }, + "plan": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "active", + "suspended", + "revoked" + ] + }, + "licenceExpiresAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "graceDays": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "issuedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "validUntil": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "limits": { + "type": "object", + "properties": { + "aiMonthlyCapCents": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "aiMonthlyCapCents" + ] + } + }, + "required": [ + "v", + "licenceId", + "installId", + "customer", + "plan", + "status", + "licenceExpiresAt", + "graceDays", + "issuedAt", + "validUntil", + "limits" + ] +} diff --git a/packages/contracts/schemas/hub-public-key-response.json b/packages/contracts/schemas/hub-public-key-response.json new file mode 100644 index 0000000..e0dfc7a --- /dev/null +++ b/packages/contracts/schemas/hub-public-key-response.json @@ -0,0 +1,32 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-public-key-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersions": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "keyId": { + "type": "string" + }, + "algorithm": { + "type": "string", + "const": "Ed25519" + }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + } + }, + "required": [ + "protocolVersions", + "keyId", + "algorithm", + "publicKey" + ] +} diff --git a/packages/contracts/schemas/hub-register-request.json b/packages/contracts/schemas/hub-register-request.json new file mode 100644 index 0000000..77fa686 --- /dev/null +++ b/packages/contracts/schemas/hub-register-request.json @@ -0,0 +1,154 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-register-request.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "licenceKey": { + "type": "string", + "pattern": "^[A-Z]{3}(-[A-Z0-9]{4}){4}$" + }, + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app", + "accounts" + ] + }, + "install": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + "adminContact": { + "anyOf": [ + { + "type": "object", + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ] + }, + "email": { + "anyOf": [ + { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name", + "email" + ] + }, + { + "type": "null" + } + ] + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "timezone": { + "type": "string", + "pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$" + }, + "server": { + "type": "object", + "properties": { + "node": { + "type": "string" + }, + "postgres": { + "type": [ + "string", + "null" + ] + }, + "os": { + "type": "string" + } + }, + "required": [ + "node", + "postgres", + "os" + ] + }, + "features": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + } + }, + "required": [ + "name", + "url", + "adminContact", + "version", + "timezone", + "server", + "features", + "publicKey" + ] + } + }, + "required": [ + "protocolVersion", + "licenceKey", + "product", + "install" + ] +} diff --git a/packages/contracts/schemas/hub-register-response.json b/packages/contracts/schemas/hub-register-response.json new file mode 100644 index 0000000..6b7ea22 --- /dev/null +++ b/packages/contracts/schemas/hub-register-response.json @@ -0,0 +1,174 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-register-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "installSecret": { + "type": "string", + "minLength": 32 + }, + "licence": { + "type": "string" + }, + "heartbeatIntervalMinutes": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "latestVersion": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + { + "type": "null" + } + ] + }, + "releases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "releasedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "urgent": { + "type": "boolean" + }, + "notes": { + "type": "string" + } + }, + "required": [ + "version", + "releasedAt", + "urgent", + "notes" + ] + } + }, + "notices": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "level": { + "type": "string", + "enum": [ + "info", + "maintenance", + "warning" + ] + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "startsAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "endsAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + { + "type": "null" + } + ] + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "id", + "level", + "title", + "message", + "startsAt", + "endsAt", + "updatedAt" + ] + } + }, + "linkedProducts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app", + "accounts" + ] + }, + "installId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + } + }, + "required": [ + "product", + "installId", + "url", + "publicKey" + ] + } + } + }, + "required": [ + "installId", + "installSecret", + "licence", + "heartbeatIntervalMinutes", + "latestVersion", + "releases", + "notices", + "linkedProducts" + ] +} diff --git a/packages/contracts/schemas/hub-update-request-cancel-response.json b/packages/contracts/schemas/hub-update-request-cancel-response.json new file mode 100644 index 0000000..e39e2a3 --- /dev/null +++ b/packages/contracts/schemas/hub-update-request-cancel-response.json @@ -0,0 +1,13 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-update-request-cancel-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "cancelled": { + "type": "boolean" + } + }, + "required": [ + "cancelled" + ] +} diff --git a/packages/contracts/schemas/hub-update-request-cancel.json b/packages/contracts/schemas/hub-update-request-cancel.json new file mode 100644 index 0000000..c5004e0 --- /dev/null +++ b/packages/contracts/schemas/hub-update-request-cancel.json @@ -0,0 +1,14 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-update-request-cancel.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + } + }, + "required": [ + "protocolVersion" + ] +} diff --git a/packages/contracts/schemas/hub-update-request-response.json b/packages/contracts/schemas/hub-update-request-response.json new file mode 100644 index 0000000..01868d5 --- /dev/null +++ b/packages/contracts/schemas/hub-update-request-response.json @@ -0,0 +1,32 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-update-request-response.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "requestedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + }, + "alreadyRequested": { + "type": "boolean" + }, + "changed": { + "type": "boolean" + }, + "previousVersion": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "requestedAt", + "version", + "alreadyRequested", + "changed" + ] +} diff --git a/packages/contracts/schemas/hub-update-request.json b/packages/contracts/schemas/hub-update-request.json new file mode 100644 index 0000000..d815eba --- /dev/null +++ b/packages/contracts/schemas/hub-update-request.json @@ -0,0 +1,19 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/hub-update-request.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "protocolVersion": { + "type": "number", + "const": 2 + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "protocolVersion", + "version" + ] +} diff --git a/packages/contracts/schemas/identity-claims.json b/packages/contracts/schemas/identity-claims.json new file mode 100644 index 0000000..b8200ba --- /dev/null +++ b/packages/contracts/schemas/identity-claims.json @@ -0,0 +1,125 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/identity-claims.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "given_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "family_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "email": { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + "email_verified": { + "type": "boolean" + }, + "phone_number": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + { + "type": "null" + } + ] + }, + "phone_number_verified": { + "type": "boolean" + }, + "news_consent": { + "type": "object", + "properties": { + "email": { + "type": "boolean" + }, + "whatsapp": { + "type": "boolean" + } + }, + "required": [ + "email", + "whatsapp" + ] + }, + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "amr": { + "maxItems": 10, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 20 + } + }, + "two_factor": { + "anyOf": [ + { + "type": "string", + "enum": [ + "email", + "whatsapp", + "totp" + ] + }, + { + "type": "null" + } + ] + }, + "privacy_notice_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "name", + "given_name", + "family_name", + "email", + "email_verified", + "phone_number", + "phone_number_verified", + "news_consent", + "schema", + "sub", + "amr", + "two_factor", + "privacy_notice_version" + ] +} diff --git a/packages/contracts/schemas/user-deleted-reply.json b/packages/contracts/schemas/user-deleted-reply.json new file mode 100644 index 0000000..ba1b562 --- /dev/null +++ b/packages/contracts/schemas/user-deleted-reply.json @@ -0,0 +1,52 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-deleted-reply.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "oneOf": [ + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "status": { + "type": "string", + "const": "deleted" + } + }, + "required": [ + "schema", + "status" + ] + }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "status": { + "type": "string", + "const": "deferred" + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "retryAfter": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "schema", + "status", + "reason", + "retryAfter" + ] + } + ] +} diff --git a/packages/contracts/schemas/user-deleted.json b/packages/contracts/schemas/user-deleted.json new file mode 100644 index 0000000..78732a1 --- /dev/null +++ b/packages/contracts/schemas/user-deleted.json @@ -0,0 +1,43 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-deleted.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.deleted" + }, + "approvedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "approvedAt" + ] +} diff --git a/packages/contracts/schemas/user-export-reply.json b/packages/contracts/schemas/user-export-reply.json new file mode 100644 index 0000000..f4ec14c --- /dev/null +++ b/packages/contracts/schemas/user-export-reply.json @@ -0,0 +1,77 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-export-reply.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "exportId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "product": { + "type": "string", + "enum": [ + "events", + "website", + "app", + "accounts" + ] + }, + "generatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sections": { + "maxItems": 100, + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "maxLength": 50, + "pattern": "^[a-z][a-z0-9_]*$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "records": { + "type": "array", + "items": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + } + } + }, + "required": [ + "key", + "title", + "records" + ] + } + } + }, + "required": [ + "schema", + "exportId", + "sub", + "product", + "generatedAt", + "sections" + ] +} diff --git a/packages/contracts/schemas/user-export.json b/packages/contracts/schemas/user-export.json new file mode 100644 index 0000000..e0e8285 --- /dev/null +++ b/packages/contracts/schemas/user-export.json @@ -0,0 +1,43 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-export.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.export" + }, + "exportId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "exportId" + ] +} diff --git a/packages/contracts/schemas/user-updated-reply.json b/packages/contracts/schemas/user-updated-reply.json new file mode 100644 index 0000000..eacca17 --- /dev/null +++ b/packages/contracts/schemas/user-updated-reply.json @@ -0,0 +1,19 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-updated-reply.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "ok": { + "type": "boolean", + "const": true + } + }, + "required": [ + "schema", + "ok" + ] +} diff --git a/packages/contracts/schemas/user-updated.json b/packages/contracts/schemas/user-updated.json new file mode 100644 index 0000000..f2bf95c --- /dev/null +++ b/packages/contracts/schemas/user-updated.json @@ -0,0 +1,118 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/user-updated.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.identity/1" + }, + "callId": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "occurredAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "sub": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "type": { + "type": "string", + "const": "user.updated" + }, + "profile": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "given_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "family_name": { + "anyOf": [ + { + "type": "string", + "maxLength": 100 + }, + { + "type": "null" + } + ] + }, + "email": { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + }, + "email_verified": { + "type": "boolean" + }, + "phone_number": { + "anyOf": [ + { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + { + "type": "null" + } + ] + }, + "phone_number_verified": { + "type": "boolean" + }, + "news_consent": { + "type": "object", + "properties": { + "email": { + "type": "boolean" + }, + "whatsapp": { + "type": "boolean" + } + }, + "required": [ + "email", + "whatsapp" + ] + } + }, + "required": [ + "name", + "given_name", + "family_name", + "email", + "email_verified", + "phone_number", + "phone_number_verified", + "news_consent" + ] + } + }, + "required": [ + "schema", + "callId", + "occurredAt", + "sub", + "type", + "profile" + ] +} diff --git a/packages/contracts/scripts/json-schemas.cjs b/packages/contracts/scripts/json-schemas.cjs new file mode 100644 index 0000000..5464e4e --- /dev/null +++ b/packages/contracts/scripts/json-schemas.cjs @@ -0,0 +1,101 @@ +// Generates the JSON Schema files in `schemas/` from the zod schemas (ROADMAP-v3 §2), for +// consumers that don't use TypeScript or zod. Run after the build (`npm run build` does it): +// node scripts/json-schemas.cjs write schemas/ +// node scripts/json-schemas.cjs --check fail if schemas/ is out of date +// The test (tests/json-schemas.test.ts) uses `buildSchemas` with the source, so the files in git +// always match the zod schemas. +const { z } = require("zod"); +const fs = require("node:fs"); +const path = require("node:path"); + +const BASE_ID = "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/"; + +/** File name (without .json) → schema, from the package exports (`c`) and `c.hub`. */ +function contracts(c) { + return { + "event": c.eventSchema, + "event-feed": c.eventFeedSchema, + "event-changed": c.eventChangedSchema, + "church": c.churchSchema, + "identity-claims": c.identityClaimsSchema, + "accounts-call": c.accountsCallSchema, + "user-updated": c.userUpdatedSchema, + "user-updated-reply": c.userUpdatedReplySchema, + "user-deleted": c.userDeletedSchema, + "user-deleted-reply": c.userDeletedReplySchema, + "user-export": c.userExportSchema, + "user-export-reply": c.userExportReplySchema, + "hub-register-request": c.hub.registerRequestSchema, + "hub-register-response": c.hub.registerResponseSchema, + "hub-heartbeat-request": c.hub.heartbeatRequestSchema, + "hub-heartbeat-response": c.hub.heartbeatResponseSchema, + "hub-licence-payload": c.hub.licencePayloadSchema, + "hub-public-key-response": c.hub.publicKeyResponseSchema, + "hub-update-request": c.hub.updateRequestSchema, + "hub-update-request-response": c.hub.updateRequestResponseSchema, + "hub-update-request-cancel": c.hub.updateRequestCancelSchema, + "hub-update-request-cancel-response": c.hub.updateRequestCancelResponseSchema, + "hub-ai-status-request": c.hub.aiStatusRequestSchema, + "hub-ai-status": c.hub.aiStatusSchema, + "hub-ai-complete-request": c.hub.aiCompleteRequestSchema, + "hub-ai-complete-response": c.hub.aiCompleteResponseSchema, + "hub-error": c.hub.hubErrorSchema, + "health": c.hub.healthSchema, + }; +} + +// zod writes .startsWith() / .endsWith() / .includes() as a `format` that isn't a JSON Schema +// format (strict validators such as Ajv refuse it) next to a `pattern` that does the real check. +const ZOD_ONLY_FORMATS = new Set(["starts_with", "ends_with", "includes"]); +function dropZodFormats(ctx) { + const json = ctx.jsonSchema; + if (ZOD_ONLY_FORMATS.has(json.format) && json.pattern) delete json.format; +} + +/** + * name → JSON Schema (draft 2020-12). `io: "input"` describes what may be sent: unknown fields + * are allowed (consumers drop them, never refuse them) and defaults are optional. + * Checks zod can't express in JSON Schema (refinements, e.g. startsAt matching the sessions) + * only run in zod. + */ +function buildSchemas(c) { + const out = {}; + for (const [name, schema] of Object.entries(contracts(c))) { + if (!schema) throw new Error(`json-schemas: no schema exported for "${name}"`); + out[name] = { $id: `${BASE_ID}${name}.json`, ...z.toJSONSchema(schema, { io: "input", override: dropZodFormats }) }; + } + return out; +} + +const serialise = (json) => `${JSON.stringify(json, null, 2)}\n`; + +function main() { + const dir = path.join(__dirname, "..", "schemas"); + const schemas = buildSchemas(require("../dist/index.js")); + const check = process.argv.includes("--check"); + const stale = []; + if (!check) fs.mkdirSync(dir, { recursive: true }); + const wanted = new Set(Object.keys(schemas).map((n) => `${n}.json`)); + for (const [name, json] of Object.entries(schemas)) { + const file = path.join(dir, `${name}.json`); + const text = serialise(json); + const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; + if (current === text) continue; + if (check) stale.push(`${name}.json`); + else fs.writeFileSync(file, text); + } + for (const file of fs.existsSync(dir) ? fs.readdirSync(dir) : []) { + if (!file.endsWith(".json") || wanted.has(file)) continue; + if (check) stale.push(`${file} (no longer generated)`); + else fs.unlinkSync(path.join(dir, file)); + } + if (check && stale.length) { + console.error(`schemas/ is out of date: ${stale.join(", ")}. Run npm run build.`); + process.exit(1); + } + console.log(check ? "schemas/ is up to date" : `Wrote ${Object.keys(schemas).length} JSON Schema files to schemas/`); +} + +if (require.main === module) main(); + +module.exports = { buildSchemas, serialise }; diff --git a/packages/contracts/tests/json-schemas.test.ts b/packages/contracts/tests/json-schemas.test.ts new file mode 100644 index 0000000..ab557e5 --- /dev/null +++ b/packages/contracts/tests/json-schemas.test.ts @@ -0,0 +1,82 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import Ajv2020 from "ajv/dist/2020"; +import addFormats from "ajv-formats"; +import * as contracts from "../src"; +import { SAMPLES, sample } from "./helpers"; + +// eslint-disable-next-line @typescript-eslint/no-require-imports +const { buildSchemas, serialise } = require("../scripts/json-schemas.cjs") as { + buildSchemas: (c: typeof contracts) => Record; + serialise: (json: object) => string; +}; + +const SCHEMAS_DIR = join(__dirname, "..", "schemas"); +const schemas = buildSchemas(contracts); + +/** Every sample file and the JSON Schema (file name without .json) it must pass. */ +const SAMPLE_SCHEMA: Record = { + "event.json": "event", + "event-simple.json": "event", + "event-feed.json": "event-feed", + "event-changed.json": "event-changed", + "church.json": "church", + "identity-claims.json": "identity-claims", + "user-updated.json": "user-updated", + "user-deleted.json": "user-deleted", + "user-deleted-reply.json": "user-deleted-reply", + "user-export.json": "user-export", + "user-export-reply.json": "user-export-reply", + "hub-register-request.json": "hub-register-request", + "hub-register-response.json": "hub-register-response", + "hub-heartbeat-events.json": "hub-heartbeat-request", + "hub-heartbeat-website.json": "hub-heartbeat-request", + "hub-heartbeat-app.json": "hub-heartbeat-request", + "hub-heartbeat-accounts.json": "hub-heartbeat-request", + "hub-heartbeat-response.json": "hub-heartbeat-response", + "hub-licence-payload.json": "hub-licence-payload", +}; + +describe("JSON Schema (schemas/)", () => { + it("the files in schemas/ match the zod schemas (run npm run build after changing a contract)", () => { + const files = readdirSync(SCHEMAS_DIR).filter((f) => f.endsWith(".json")).sort(); + expect(files).toEqual(Object.keys(schemas).map((n) => `${n}.json`).sort()); + for (const [name, json] of Object.entries(schemas)) { + expect(readFileSync(join(SCHEMAS_DIR, `${name}.json`), "utf8").replace(/\r\n/g, "\n")).toBe(serialise(json)); + } + }); + + const ajv = new Ajv2020({ allErrors: true, strict: true }); + addFormats(ajv); + for (const json of Object.values(schemas)) ajv.addSchema(json); + const validatorFor = (name: string) => { + const validate = ajv.getSchema((schemas[name] as { $id: string }).$id); + if (!validate) throw new Error(`no JSON Schema "${name}"`); + return validate; + }; + + it("every JSON Schema compiles", () => { + for (const name of Object.keys(schemas)) expect(() => validatorFor(name)).not.toThrow(); + }); + + it("every sample has a JSON Schema", () => { + const files = readdirSync(SAMPLES).filter((f) => f.endsWith(".json")); + expect(files.filter((f) => !(f in SAMPLE_SCHEMA))).toEqual([]); + }); + + it.each(Object.entries(SAMPLE_SCHEMA))("%s passes the JSON Schema %s", (file, name) => { + const validate = validatorFor(name); + validate(sample(file)); + expect(validate.errors ?? []).toEqual([]); + }); + + it("refuses a payload with a wrong schema name", () => { + const validate = validatorFor("event"); + expect(validate({ ...(sample("event.json") as object), schema: "crosscode.event/2" })).toBe(false); + }); + + it("allows fields it doesn't know (consumers drop them, never refuse them)", () => { + const validate = validatorFor("event"); + expect(validate({ ...(sample("event.json") as object), somethingNew: true })).toBe(true); + }); +});