Files
crosscode-platform/packages/contracts/README.md
T
joshuaandClaude Opus 5.5 2eef8d1da3 contracts 1.22.0: only free Bible translations in App 1.0, the publishers' notices
- Each translation has a licence; FREE_BIBLE_TRANSLATION_IDS (KJV and the new
  Berean Standard Bible) is what the Hub and App 1.0 offer, and the CSV import
  refuses any other when told to, naming the publisher to ask.
- The publishers' exact notices (NLT, ESV, AFR53, AFR83 corrected), an
  acknowledgement per translation, the Bible Society's disclaimer, publisher
  and permissionsUrl, FREE_QUOTE_VERSES and quotedVerses. AFR83 is named
  "Afrikaans 1983/1992-vertaling".
- docs/BIBLE-PERMISSIONS.md: what each publisher allows, the status and the
  drafted permission requests. APP-1.0-PLAN decision 14, HANDOVER (with the
  Website 1.8.0 approach), VERSIONS, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:48:38 +02:00

103 lines
7.5 KiB
Markdown

# @crosscode/contracts
Everything that crosses between Cross Code products is defined once, here (ROADMAP-v3 §2):
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 |
|----------|-------------|----------|--------|
| 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` |
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp); from 1.20.0 `messaging.get` (the church's settings for the App, with the `messaging.changed` hint back) and `whatsapp.optout` (a STOP, kept by Accounts for every product) | `src/identity-request.ts` |
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
| Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) |
| Devotional | `crosscode.devotional/1` | From 1.20.0: one day's devotional for the Church App (Cross Code's from the Hub at `GET /api/v2/devotionals`, or the church's own), the CSV import's columns and row checks (`checkDevotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`), shared by the Hub and the App | `src/devotional.ts` |
| Bible passages | — | From 1.20.0: the 66 books (USFM codes, English and Afrikaans names), the seven translations with their YouVersion ids and copyright lines, `parseBibleReference`, `formatBibleReference`, `youVersionUrl`. From 1.22.0: the Berean Standard Bible, `licence` and `FREE_BIBLE_TRANSLATION_IDS` (only those in App 1.0), each publisher's exact notices (`copyright` under the verse, `acknowledgement`, the Bible Society's `disclaimer`), who to ask (`publisher`, `permissionsUrl`), `FREE_QUOTE_VERSES` and `quotedVerses` (docs/BIBLE-PERMISSIONS.md) | `src/bible.ts` |
| Demo scenarios | — | From 1.21.0: `agent.DEMO_SCENARIOS`, eight preset churches that load every product of a demo client alike (Accounts first, `DEMO_SCENARIO_ORDER`), each product's profiles, the minimum releases and agent; `seed-demo` takes `scenario` | `src/agent.ts` (exported as `agent`) |
| 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.
**Connect** (`crosscode.link/1`) is signed with each install's Ed25519 key instead: `signLink(message,
privateKeyPem)` and `verifyLink(message, senderPem)`, over the message without `signature` as
canonical JSON. The receiver takes the sender's PEM from its own cached `linkedProducts` (never
from the message) and refuses a nonce it has seen. `ed25519PublicToPem` / `ed25519PublicFromPem`
convert between the raw keys `generateEd25519` makes and the PEM the Hub lists.
### 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.<name>/<major>` (`parseSchemaName`, `isSchema`).
- Adding an **optional** field keeps the version. Consumers ignore fields they don't know.
- 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
Published to Gitea's package registry. In the consuming repo's `.npmrc`:
```
@crosscode:registry=https://c-git.crosscode.co.za/api/packages/joshua/npm/
```
Works with both `require` (Cross Events backend, Hub) and `import` (Next.js apps).