diff --git a/packages/contracts/README.md b/packages/contracts/README.md index b7fbb65..1fac22f 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -11,6 +11,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J | 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` | +| 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`) | | Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) | @@ -62,6 +63,12 @@ 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. +**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 diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 3b399c8..52a50fc 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/contracts", - "version": "1.3.0", + "version": "1.4.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", diff --git a/packages/contracts/samples/hub-heartbeat-response.json b/packages/contracts/samples/hub-heartbeat-response.json index e008138..f176478 100644 --- a/packages/contracts/samples/hub-heartbeat-response.json +++ b/packages/contracts/samples/hub-heartbeat-response.json @@ -36,5 +36,6 @@ "publicKey": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAsQbIsjVsJY9k9jLjMSbscXdD9wONmLw90MrMHptfmSQ=\n-----END PUBLIC KEY-----\n" } ], - "serverTime": "2026-11-03T10:15:00.120Z" + "serverTime": "2026-11-03T10:15:00.120Z", + "publicKeyStatus": "saved" } diff --git a/packages/contracts/samples/link-connect.json b/packages/contracts/samples/link-connect.json new file mode 100644 index 0000000..1883774 --- /dev/null +++ b/packages/contracts/samples/link-connect.json @@ -0,0 +1,16 @@ +{ + "schema": "crosscode.link/1", + "type": "link.connect", + "from": { + "product": "events", + "installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c", + "url": "https://events.hopefamily.co.za" + }, + "to": { + "installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02" + }, + "secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "issuedAt": "2026-11-20T10:00:00.000Z", + "nonce": "n0nce-AbCdEfGhIjKlMnOpQr", + "signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA" +} diff --git a/packages/contracts/samples/link-connected.json b/packages/contracts/samples/link-connected.json new file mode 100644 index 0000000..bf84fc0 --- /dev/null +++ b/packages/contracts/samples/link-connected.json @@ -0,0 +1,16 @@ +{ + "schema": "crosscode.link/1", + "type": "link.connected", + "from": { + "product": "website", + "installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02", + "url": "https://www.hopefamily.co.za" + }, + "to": { + "installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c" + }, + "inReplyTo": "n0nce-AbCdEfGhIjKlMnOpQr", + "issuedAt": "2026-11-20T10:00:00.400Z", + "nonce": "n0nce-ZyXwVuTsRqPoNmLkJi", + "signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA" +} diff --git a/packages/contracts/samples/link-disconnect.json b/packages/contracts/samples/link-disconnect.json new file mode 100644 index 0000000..c57127c --- /dev/null +++ b/packages/contracts/samples/link-disconnect.json @@ -0,0 +1,15 @@ +{ + "schema": "crosscode.link/1", + "type": "link.disconnect", + "from": { + "product": "website", + "installId": "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02", + "url": "https://www.hopefamily.co.za" + }, + "to": { + "installId": "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c" + }, + "issuedAt": "2026-12-01T08:00:00.000Z", + "nonce": "n0nce-DiScOnNeCt0123456", + "signature": "QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQA" +} diff --git a/packages/contracts/schemas/hub-heartbeat-request.json b/packages/contracts/schemas/hub-heartbeat-request.json index de10033..d801dcd 100644 --- a/packages/contracts/schemas/hub-heartbeat-request.json +++ b/packages/contracts/schemas/hub-heartbeat-request.json @@ -107,6 +107,10 @@ "pendingMigrations" ] }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + }, "product": { "type": "string", "const": "events" @@ -430,6 +434,10 @@ "pendingMigrations" ] }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + }, "product": { "type": "string", "const": "website" @@ -641,6 +649,10 @@ "pendingMigrations" ] }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + }, "product": { "type": "string", "const": "app" @@ -840,6 +852,10 @@ "pendingMigrations" ] }, + "publicKey": { + "type": "string", + "pattern": "^-----BEGIN PUBLIC KEY-----.*" + }, "product": { "type": "string", "const": "accounts" diff --git a/packages/contracts/schemas/hub-heartbeat-response.json b/packages/contracts/schemas/hub-heartbeat-response.json index c0b6aba..b699d0e 100644 --- a/packages/contracts/schemas/hub-heartbeat-response.json +++ b/packages/contracts/schemas/hub-heartbeat-response.json @@ -175,6 +175,14 @@ "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))$" + }, + "publicKeyStatus": { + "type": "string", + "enum": [ + "saved", + "matches", + "mismatch" + ] } }, "required": [ diff --git a/packages/contracts/schemas/link-connect.json b/packages/contracts/schemas/link-connect.json new file mode 100644 index 0000000..a0634ab --- /dev/null +++ b/packages/contracts/schemas/link-connect.json @@ -0,0 +1,84 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-connect.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.link/1" + }, + "from": { + "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" + } + }, + "required": [ + "product", + "installId", + "url" + ] + }, + "to": { + "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)$" + } + }, + "required": [ + "installId" + ] + }, + "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))$" + }, + "nonce": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{22,64}$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "link.connect" + }, + "secret": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + } + }, + "required": [ + "schema", + "from", + "to", + "issuedAt", + "nonce", + "signature", + "type", + "secret" + ] +} diff --git a/packages/contracts/schemas/link-connected.json b/packages/contracts/schemas/link-connected.json new file mode 100644 index 0000000..7fde249 --- /dev/null +++ b/packages/contracts/schemas/link-connected.json @@ -0,0 +1,84 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-connected.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.link/1" + }, + "from": { + "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" + } + }, + "required": [ + "product", + "installId", + "url" + ] + }, + "to": { + "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)$" + } + }, + "required": [ + "installId" + ] + }, + "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))$" + }, + "nonce": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{22,64}$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "link.connected" + }, + "inReplyTo": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{22,64}$" + } + }, + "required": [ + "schema", + "from", + "to", + "issuedAt", + "nonce", + "signature", + "type", + "inReplyTo" + ] +} diff --git a/packages/contracts/schemas/link-disconnect.json b/packages/contracts/schemas/link-disconnect.json new file mode 100644 index 0000000..124dbcf --- /dev/null +++ b/packages/contracts/schemas/link-disconnect.json @@ -0,0 +1,79 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-disconnect.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.link/1" + }, + "from": { + "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" + } + }, + "required": [ + "product", + "installId", + "url" + ] + }, + "to": { + "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)$" + } + }, + "required": [ + "installId" + ] + }, + "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))$" + }, + "nonce": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{22,64}$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "link.disconnect" + } + }, + "required": [ + "schema", + "from", + "to", + "issuedAt", + "nonce", + "signature", + "type" + ] +} diff --git a/packages/contracts/schemas/link-disconnected.json b/packages/contracts/schemas/link-disconnected.json new file mode 100644 index 0000000..a56a091 --- /dev/null +++ b/packages/contracts/schemas/link-disconnected.json @@ -0,0 +1,19 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-disconnected.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.link/1" + }, + "type": { + "type": "string", + "const": "link.disconnected" + } + }, + "required": [ + "schema", + "type" + ] +} diff --git a/packages/contracts/schemas/link-error.json b/packages/contracts/schemas/link-error.json new file mode 100644 index 0000000..2618466 --- /dev/null +++ b/packages/contracts/schemas/link-error.json @@ -0,0 +1,26 @@ +{ + "$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/link-error.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "string", + "enum": [ + "NOT_LINKED", + "WRONG_INSTALL", + "BAD_SIGNATURE", + "STALE_REQUEST", + "REPLAYED", + "INVALID_REQUEST", + "LINKS_UNAVAILABLE" + ] + } + }, + "required": [ + "message", + "code" + ] +} diff --git a/packages/contracts/scripts/json-schemas.cjs b/packages/contracts/scripts/json-schemas.cjs index 671dc53..68789a3 100644 --- a/packages/contracts/scripts/json-schemas.cjs +++ b/packages/contracts/scripts/json-schemas.cjs @@ -52,6 +52,11 @@ function contracts(c) { "agent-job-config": c.agent.jobConfigSchema, "env-template": c.agent.envTemplateSchema, "church-export": c.churchExportSchema, + "link-connect": c.linkConnectSchema, + "link-connected": c.linkConnectedSchema, + "link-disconnect": c.linkDisconnectSchema, + "link-disconnected": c.linkDisconnectedSchema, + "link-error": c.linkErrorSchema, }; } diff --git a/packages/contracts/src/hub.ts b/packages/contracts/src/hub.ts index 75fc751..6ee97d9 100644 --- a/packages/contracts/src/hub.ts +++ b/packages/contracts/src/hub.ts @@ -221,7 +221,18 @@ export const accountsStatsSchema = z.object({ linkedProducts: count, }); -const heartbeatBase = z.object({ protocolVersion, version: semverSchema, health: healthSchema }); +const heartbeatBase = z.object({ + protocolVersion, + version: semverSchema, + health: healthSchema, + /** + * The install's Ed25519 public key (PEM), contracts 1.4.0 / Hub 2.2.0. Lets an install that + * registered with protocol v1 move to v2 without its licence key (the heartbeat is already + * signed with the install secret). The Hub saves it when the install has none; see + * `publicKeyStatus` in the reply. + */ + publicKey: z.string().startsWith("-----BEGIN PUBLIC KEY-----").optional(), +}); export const heartbeatRequestSchema = z.discriminatedUnion("product", [ heartbeatBase.extend({ product: z.literal("events"), stats: eventsStatsSchema }), @@ -231,6 +242,8 @@ export const heartbeatRequestSchema = z.discriminatedUnion("product", [ ]); export type HeartbeatRequest = z.infer; +export const PUBLIC_KEY_STATUSES = ["saved", "matches", "mismatch"] as const; + export const heartbeatResponseSchema = z.object({ licence: z.string(), latestVersion: semverSchema.nullable(), @@ -239,6 +252,12 @@ export const heartbeatResponseSchema = z.object({ /** The church's other installs. The install caches this, so a Hub outage changes nothing. */ linkedProducts: z.array(linkedProductSchema), serverTime: dateTimeSchema, + /** + * Only when the heartbeat sent `publicKey` (Hub 2.2.0+): `saved` (the Hub had none), + * `matches`, or `mismatch` (the Hub has another key; it keeps its own and flags the install + * until Joshua clears it). Never a failed heartbeat: the licence keeps refreshing either way. + */ + publicKeyStatus: z.enum(PUBLIC_KEY_STATUSES).optional(), }); export type HeartbeatResponse = z.infer; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index edeeaef..d75dbc4 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -8,6 +8,7 @@ export * from "./event"; export * from "./church"; export * from "./identity"; export * from "./return-to"; +export * from "./link"; export * as hub from "./hub"; export * as agent from "./agent"; export * from "./church-export"; diff --git a/packages/contracts/src/link.ts b/packages/contracts/src/link.ts new file mode 100644 index 0000000..4be64a0 --- /dev/null +++ b/packages/contracts/src/link.ts @@ -0,0 +1,73 @@ +import { z } from "zod"; +import { dateTimeSchema, idSchema, productSchema, urlSchema } from "./common"; +import { schemaName } from "./schema-name"; + +/** + * `crosscode.link/1` — **Connect** under Settings → Linked products (docs/EVENTS-2.4-PLAN.md §2). + * + * The Hub tells each install which of its church's other installs exist and their Ed25519 public + * keys (`linkedProducts` in the heartbeat reply). Connect turns that into a working link between + * two of them: a shared secret for signed calls (`LINK_HEADERS` in `@crosscode/contracts/signing`: + * the `event.changed` webhook, later Accounts' back-channel calls). + * + * ``` + * A → POST {B.url}/api/links/v1/connect link.connect (signed by A, carries the new secret) + * ← 200 link.connected (signed by B, echoes A's nonce) + * A → POST {B.url}/api/links/v1/disconnect link.disconnect (signed by A) + * ← 200 link.disconnected + * ``` + * + * B accepts A only when A is in **B's own cached** `linkedProducts` with the key that signed the + * message, so only installs of the same church can link, and the Hub isn't on the path at the time + * of the call. Signatures are Ed25519 over the message without `signature`, as canonical JSON + * (`signLink` / `verifyLink`). Messages more than five minutes off the receiver's clock are + * refused, and a nonce is only accepted once. + */ + +export const LINK_SCHEMA = schemaName("link", 1); + +/** Where the endpoints live on every product, relative to its address. */ +export const LINK_PATHS = { connect: "/api/links/v1/connect", disconnect: "/api/links/v1/disconnect" } as const; + +export const LINK_ERROR_CODES = ["NOT_LINKED", "WRONG_INSTALL", "BAD_SIGNATURE", "STALE_REQUEST", "REPLAYED", "INVALID_REQUEST", "LINKS_UNAVAILABLE"] as const; + +export const linkPartySchema = z.object({ + product: productSchema, + installId: idSchema, + url: urlSchema, +}); +export type LinkParty = z.infer; + +/** 32 random bytes, base64url without padding. */ +export const linkSecretSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "Expected 32 bytes, base64url"); +const nonceSchema = z.string().regex(/^[A-Za-z0-9_-]{22,64}$/, "Expected a random base64url nonce"); +const signatureSchema = z.string().regex(/^[A-Za-z0-9_-]{86}$/, "Expected an Ed25519 signature, base64url"); + +const signed = { + schema: z.literal(LINK_SCHEMA), + from: linkPartySchema, + to: z.object({ installId: idSchema }), + issuedAt: dateTimeSchema, + nonce: nonceSchema, + signature: signatureSchema, +}; + +/** A asks B to link, and hands it the secret both will sign calls with. */ +export const linkConnectSchema = z.object({ ...signed, type: z.literal("link.connect"), secret: linkSecretSchema }); +export type LinkConnect = z.infer; + +/** B's answer: signed by B and echoing A's nonce, so A knows the real B stored the secret. */ +export const linkConnectedSchema = z.object({ ...signed, type: z.literal("link.connected"), inReplyTo: nonceSchema }); +export type LinkConnected = z.infer; + +/** Either side ends the link; both drop the secret. */ +export const linkDisconnectSchema = z.object({ ...signed, type: z.literal("link.disconnect") }); +export type LinkDisconnect = z.infer; + +export const linkDisconnectedSchema = z.object({ schema: z.literal(LINK_SCHEMA), type: z.literal("link.disconnected") }); +export type LinkDisconnected = z.infer; + +export const linkErrorSchema = z.object({ message: z.string(), code: z.enum(LINK_ERROR_CODES) }); +export type LinkError = z.infer; + +export type LinkMessage = LinkConnect | LinkConnected | LinkDisconnect; diff --git a/packages/contracts/src/signing.ts b/packages/contracts/src/signing.ts index e18e230..4036742 100644 --- a/packages/contracts/src/signing.ts +++ b/packages/contracts/src/signing.ts @@ -234,3 +234,52 @@ export function decryptExport(file: Uint8Array, key: string): Buffer { decipher.setAuthTag(buf.subarray(buf.length - 16)); return Buffer.concat([decipher.update(buf.subarray(12, buf.length - 16)), decipher.final()]); } + +// --------------------------------------------------------------------------------------------- +// Product links (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2). The Hub lists each install's +// key as PEM (it's what register and the heartbeat send), so these take PEM. +// --------------------------------------------------------------------------------------------- + +/** An install's Ed25519 public key as PEM (SPKI), from the raw key `generateEd25519` returns. */ +export function ed25519PublicToPem(publicKey: string): string { + return okpPublic("Ed25519", publicKey).export({ format: "pem", type: "spki" }).toString(); +} + +/** The raw base64url key in an Ed25519 PEM. Throws for anything that isn't an Ed25519 public key. */ +export function ed25519PublicFromPem(pem: string): string { + const key = createPublicKey(pem); + if (key.asymmetricKeyType !== "ed25519") throw new Error("Not an Ed25519 public key"); + return rawPublic(key); +} + +/** A fresh link secret: 32 random bytes, base64url. */ +export function newLinkSecret(): string { + return b64u(randomBytes(32)); +} + +/** A fresh nonce for a link message. */ +export function newLinkNonce(): string { + return b64u(randomBytes(18)); +} + +/** Sign a `crosscode.link/1` message (everything but `signature`, as canonical JSON). */ +export function signLink>(message: T, privateKeyPem: string): T & { signature: string } { + return { ...message, signature: ed25519Sign(privateKeyPem, jobSigningInput(message)) }; +} + +/** + * Check a `crosscode.link/1` message against the sender's PEM key as the receiver's Hub list has + * it, and its `issuedAt` against the clock. Replays (`nonce`) are the receiver's to track. + */ +export function verifyLink(message: Record, publicKeyPem: string, opts: { now?: Date; maxSkewMs?: number } = {}): VerifyResult { + const issuedAt = typeof message.issuedAt === "string" ? Date.parse(message.issuedAt) : NaN; + const now = (opts.now ?? new Date()).getTime(); + if (!Number.isFinite(issuedAt) || Math.abs(now - issuedAt) > (opts.maxSkewMs ?? MAX_CLOCK_SKEW_MS)) return { ok: false, code: "STALE_REQUEST" }; + let raw: string; + try { + raw = ed25519PublicFromPem(publicKeyPem); + } catch { + return { ok: false, code: "BAD_SIGNATURE" }; + } + return ed25519Verify(raw, jobSigningInput(message), message.signature) ? { ok: true } : { ok: false, code: "BAD_SIGNATURE" }; +} diff --git a/packages/contracts/tests/hub-signing.test.ts b/packages/contracts/tests/hub-signing.test.ts index 6668aa0..b3753da 100644 --- a/packages/contracts/tests/hub-signing.test.ts +++ b/packages/contracts/tests/hub-signing.test.ts @@ -1,5 +1,6 @@ -import { createHmac } from "node:crypto"; -import { hub } from "../src"; +import { createHmac, generateKeyPairSync } from "node:crypto"; +import { hub, linkConnectSchema, linkConnectedSchema } from "../src"; +import * as s from "../src/signing"; import { HUB_HEADERS, LINK_HEADERS, sign, signedHeaders, verify } from "../src/signing"; import { sample } from "./helpers"; @@ -76,3 +77,65 @@ describe("signing", () => { expect(verify({ secret, timestamp: "yesterday", signature: sign(secret, "yesterday", body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" }); }); }); + +describe("product links (crosscode.link/1)", () => { + const a = s.generateEd25519(); + const b = s.generateEd25519(); + const aPem = s.ed25519PublicToPem(a.publicKey); + const now = new Date("2026-11-20T10:00:00.000Z"); + const connect = () => + s.signLink( + { + schema: "crosscode.link/1", + type: "link.connect", + from: { product: "events", installId: "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c", url: "https://events.hopefamily.co.za" }, + to: { installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02" }, + secret: s.newLinkSecret(), + issuedAt: now.toISOString(), + nonce: s.newLinkNonce(), + }, + a.privateKeyPem, + ); + + it("round-trips a key through PEM", () => { + expect(aPem.startsWith("-----BEGIN PUBLIC KEY-----")).toBe(true); + expect(s.ed25519PublicFromPem(aPem)).toBe(a.publicKey); + expect(() => s.ed25519PublicFromPem(generateKeyPairSync("x25519").publicKey.export({ format: "pem", type: "spki" }).toString())).toThrow(); + }); + + it("signs a connect message that passes the schema and verifies with the sender's PEM", () => { + const msg = connect(); + expect(linkConnectSchema.safeParse(msg).success).toBe(true); + expect(s.verifyLink(msg, aPem, { now })).toEqual({ ok: true }); + }); + + it("refuses another key, a changed body and a stale message", () => { + const msg = connect(); + expect(s.verifyLink(msg, s.ed25519PublicToPem(b.publicKey), { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" }); + expect(s.verifyLink({ ...msg, secret: s.newLinkSecret() }, aPem, { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" }); + expect(s.verifyLink({ ...msg, to: { installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e03" } }, aPem, { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" }); + expect(s.verifyLink(msg, aPem, { now: new Date(now.getTime() + 6 * 60 * 1000) })).toEqual({ ok: false, code: "STALE_REQUEST" }); + expect(s.verifyLink(msg, "not a key", { now })).toEqual({ ok: false, code: "BAD_SIGNATURE" }); + }); + + it("makes secrets and nonces the schema accepts", () => { + const reply = s.signLink( + { + schema: "crosscode.link/1", + type: "link.connected", + from: { product: "website", installId: "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02", url: "https://www.hopefamily.co.za" }, + to: { installId: "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c" }, + inReplyTo: s.newLinkNonce(), + issuedAt: now.toISOString(), + nonce: s.newLinkNonce(), + }, + b.privateKeyPem, + ); + expect(linkConnectedSchema.safeParse(reply).success).toBe(true); + }); + + it("lets a heartbeat carry the install's public key", () => { + expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), publicKey: aPem }).success).toBe(true); + expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), publicKey: "nope" }).success).toBe(false); + }); +}); diff --git a/packages/contracts/tests/json-schemas.test.ts b/packages/contracts/tests/json-schemas.test.ts index e951b27..984d614 100644 --- a/packages/contracts/tests/json-schemas.test.ts +++ b/packages/contracts/tests/json-schemas.test.ts @@ -36,6 +36,9 @@ const SAMPLE_SCHEMA: Record = { "hub-heartbeat-response.json": "hub-heartbeat-response", "hub-licence-payload.json": "hub-licence-payload", "church-export.json": "church-export", + "link-connect.json": "link-connect", + "link-connected.json": "link-connected", + "link-disconnect.json": "link-disconnect", }; describe("JSON Schema (schemas/)", () => { diff --git a/packages/contracts/tests/samples.test.ts b/packages/contracts/tests/samples.test.ts index 196930d..731b229 100644 --- a/packages/contracts/tests/samples.test.ts +++ b/packages/contracts/tests/samples.test.ts @@ -8,6 +8,9 @@ import { eventFeedSchema, eventSchema, hub, + linkConnectSchema, + linkConnectedSchema, + linkDisconnectSchema, identityClaimsSchema, userDeletedReplySchema, userExportReplySchema, @@ -36,6 +39,9 @@ const SCHEMAS: Record = { "hub-heartbeat-response.json": hub.heartbeatResponseSchema, "hub-licence-payload.json": hub.licencePayloadSchema, "church-export.json": churchExportSchema, + "link-connect.json": linkConnectSchema, + "link-connected.json": linkConnectedSchema, + "link-disconnect.json": linkDisconnectSchema, }; describe("samples", () => {