Contracts: event, event feed, church, identity, sign-in return, Hub protocol v2
- crosscode.event/1 and crosscode.event-feed/1 (feed, event.changed webhook), with session and registration rules; parseEventFeed skips and reports bad events instead of failing the whole feed. - crosscode.church/1: branding, campuses, service times, contact, links. - crosscode.identity/1: sign-in claims and the user.updated / user.deleted / user.export back-channel calls and replies. - Sign-in return helpers (isSafeReturnPath, encodeState/decodeState, isRegisteredRedirectUri) so every product returns people to the page they came from in the same safe way. - Hub protocol v2: product on register/heartbeat, stats per product, install public key, linked products, customerId/product in licences. - @crosscode/contracts/signing (Node only): the Hub's HMAC scheme. - Samples for every contract in samples/, checked by the tests (120). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { accountsCallSchema, churchSchema, identityClaimsSchema, userDeletedReplySchema } from "../src";
|
||||
import type { Church } from "../src";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
describe("crosscode.church/1", () => {
|
||||
const church = () => sample<Church>("church.json");
|
||||
|
||||
it("refuses a service time for a campus that doesn't exist", () => {
|
||||
const c = church();
|
||||
c.serviceTimes[0]!.campus = "vereeniging";
|
||||
const r = churchSchema.safeParse(c);
|
||||
expect(r.success).toBe(false);
|
||||
expect(r.error?.issues[0]?.message).toBe('Unknown campus "vereeniging"');
|
||||
});
|
||||
|
||||
it("refuses duplicate campus slugs", () => {
|
||||
const c = church();
|
||||
c.campuses.push({ ...c.campuses[0]! });
|
||||
expect(churchSchema.safeParse(c).success).toBe(false);
|
||||
});
|
||||
|
||||
it("checks colours, times and phone numbers", () => {
|
||||
const c = church();
|
||||
expect(churchSchema.safeParse({ ...c, branding: { ...c.branding, colours: { primary: "blue", accent: null } } }).success).toBe(false);
|
||||
expect(churchSchema.safeParse({ ...c, serviceTimes: [{ ...c.serviceTimes[0]!, time: "9am" }] }).success).toBe(false);
|
||||
expect(churchSchema.safeParse({ ...c, contact: { ...c.contact, phone: "016 123 4567" } }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("crosscode.identity/1", () => {
|
||||
it("has no roles in the claims (roles stay in each product)", () => {
|
||||
const parsed = identityClaimsSchema.parse({ ...sample("identity-claims.json"), role: "admin" });
|
||||
expect(parsed).not.toHaveProperty("role");
|
||||
});
|
||||
|
||||
it("knows the authenticator app as a 2FA method", () => {
|
||||
expect(identityClaimsSchema.safeParse({ ...sample("identity-claims.json"), two_factor: "sms" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("tells the back-channel calls apart by type", () => {
|
||||
expect(accountsCallSchema.parse(sample("user-deleted.json")).type).toBe("user.deleted");
|
||||
expect(accountsCallSchema.safeParse({ ...sample("user-deleted.json"), type: "user.renamed" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("a deferred delete needs a reason and a retry time", () => {
|
||||
expect(userDeletedReplySchema.safeParse({ schema: "crosscode.identity/1", status: "deferred" }).success).toBe(false);
|
||||
expect(userDeletedReplySchema.safeParse({ schema: "crosscode.identity/1", status: "deleted" }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { eventKey, eventSchema, parseEventFeed } from "../src";
|
||||
import type { CrosscodeEvent } from "../src";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
const base = () => sample<CrosscodeEvent>("event.json");
|
||||
const simple = () => sample<CrosscodeEvent>("event-simple.json");
|
||||
const messages = (input: unknown) => {
|
||||
const r = eventSchema.safeParse(input);
|
||||
return r.success ? [] : r.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`);
|
||||
};
|
||||
|
||||
describe("crosscode.event/1", () => {
|
||||
it("ignores fields it doesn't know (a newer producer never breaks an older consumer)", () => {
|
||||
const parsed = eventSchema.parse({ ...base(), someFutureField: { a: 1 } });
|
||||
expect(parsed).not.toHaveProperty("someFutureField");
|
||||
});
|
||||
|
||||
it("refuses another schema or version", () => {
|
||||
expect(messages({ ...base(), schema: "crosscode.event/2" })).not.toEqual([]);
|
||||
expect(messages({ ...base(), schema: "crosscode.church/1" })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses an unknown origin product", () => {
|
||||
const e = base();
|
||||
expect(messages({ ...e, origin: { ...e.origin, product: "accounts" } })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("checks startsAt / endsAt against the sessions", () => {
|
||||
expect(messages({ ...base(), startsAt: "2027-03-14T07:00:00.000Z" })).toContain("startsAt: startsAt must be the first session's start");
|
||||
expect(messages({ ...base(), endsAt: "2027-03-16T13:00:00.000Z" })).toContain("endsAt: endsAt must be the last session's end");
|
||||
});
|
||||
|
||||
it("leaves cancelled sessions out of the first-start / last-end check", () => {
|
||||
const e = base();
|
||||
e.sessions[2]!.cancelled = true;
|
||||
expect(messages(e)).toContain("endsAt: endsAt must be the last session's end");
|
||||
e.endsAt = e.sessions[1]!.endsAt;
|
||||
expect(messages(e)).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses an event or session that ends before it starts", () => {
|
||||
const e = simple();
|
||||
expect(messages({ ...e, endsAt: "2026-12-20T15:00:00.000Z" })).toContain("endsAt: endsAt is before startsAt");
|
||||
const b = base();
|
||||
b.sessions[0]!.endsAt = "2027-03-14T05:00:00.000Z";
|
||||
expect(messages(b)).toContain("sessions.0.endsAt: Session ends before it starts");
|
||||
});
|
||||
|
||||
it("only lets Cross Events take registrations", () => {
|
||||
const e = simple();
|
||||
expect(messages({ ...e, registration: { ...e.registration, mode: "origin", url: e.origin.url } })).toContain(
|
||||
'registration.mode: Only Cross Events takes registrations (mode "origin")',
|
||||
);
|
||||
expect(messages({ ...e, registration: { ...e.registration, status: "full" } })).toContain(
|
||||
'registration.status: Only Cross Events sends a registration status other than "open"',
|
||||
);
|
||||
});
|
||||
|
||||
it("needs a url for origin / external registration and none otherwise", () => {
|
||||
const e = base();
|
||||
expect(messages({ ...e, registration: { ...e.registration, url: null } })).toContain('registration.url: A "origin" registration needs a url');
|
||||
const s = simple();
|
||||
expect(messages({ ...s, registration: { ...s.registration, url: "https://example.com" } })).toContain('registration.url: A "contact" registration has no url');
|
||||
expect(messages({ ...s, registration: { ...s.registration, mode: "external", url: "https://forms.example.com/carols" } })).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a negative or fractional price, and a currency that isn't ISO 4217", () => {
|
||||
const e = base();
|
||||
for (const priceFrom of [{ amountCents: -1, currency: "ZAR" }, { amountCents: 1.5, currency: "ZAR" }, { amountCents: 100, currency: "rand" }]) {
|
||||
expect(messages({ ...e, registration: { ...e.registration, priceFrom } })).not.toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses non-UTC-ISO times and non-http URLs", () => {
|
||||
expect(messages({ ...base(), updatedAt: "3 November 2026" })).not.toEqual([]);
|
||||
expect(messages({ ...simple(), imageUrl: "javascript:alert(1)" })).not.toEqual([]);
|
||||
expect(messages({ ...simple(), imageUrl: "ftp://example.com/a.jpg" })).not.toEqual([]);
|
||||
});
|
||||
|
||||
it("identifies an event by origin product and id", () => {
|
||||
expect(eventKey(base())).toBe("events:8f1c2a4e-5b6d-4c7e-9f80-a1b2c3d4e5f6");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEventFeed", () => {
|
||||
it("skips a bad event and reports it, keeping the rest", () => {
|
||||
const feed = sample<{ events: unknown[] }>("event-feed.json");
|
||||
feed.events.push({ ...simple(), title: "" }, "not an event", simple());
|
||||
const result = parseEventFeed(feed);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.feed.events).toHaveLength(2);
|
||||
expect(result.rejected.map((r) => [r.index, r.id])).toEqual([
|
||||
[1, simple().id],
|
||||
[2, null],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the envelope itself is wrong", () => {
|
||||
expect(parseEventFeed({ schema: "crosscode.event-feed/1", events: [] }).ok).toBe(false);
|
||||
expect(parseEventFeed(null).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const SAMPLES = join(__dirname, "..", "samples");
|
||||
|
||||
/** A fresh copy of a sample payload from samples/. */
|
||||
export function sample<T extends object = Record<string, unknown>>(file: string): T {
|
||||
return JSON.parse(readFileSync(join(SAMPLES, file), "utf8")) as T;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import { hub } from "../src";
|
||||
import { HUB_HEADERS, LINK_HEADERS, sign, signedHeaders, verify } from "../src/signing";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
describe("Hub protocol v2", () => {
|
||||
it("picks the stats by product", () => {
|
||||
const events = sample<Record<string, unknown>>("hub-heartbeat-events.json");
|
||||
const website = sample<Record<string, unknown>>("hub-heartbeat-website.json");
|
||||
expect(hub.heartbeatRequestSchema.safeParse({ ...events, stats: website.stats }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses protocol v1 bodies (the Hub routes those to its v1 handler)", () => {
|
||||
expect(hub.heartbeatRequestSchema.safeParse({ ...sample("hub-heartbeat-events.json"), protocolVersion: 1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a licence token payload from a Hub before 2.0 (no customerId or product)", () => {
|
||||
const payload = sample<Record<string, unknown>>("hub-licence-payload.json");
|
||||
delete payload.customerId;
|
||||
delete payload.product;
|
||||
expect(hub.licencePayloadSchema.safeParse(payload).success).toBe(true);
|
||||
});
|
||||
|
||||
it("only sends income as a band", () => {
|
||||
const hb = sample<{ stats: { income: Record<string, unknown> } }>("hub-heartbeat-events.json");
|
||||
hb.stats.income.last30d = 12345;
|
||||
expect(hub.heartbeatRequestSchema.safeParse(hb).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, "0–100"],
|
||||
[100, "0–100"],
|
||||
[101, "101–300"],
|
||||
[750, "301–750"],
|
||||
[751, "751–2 000"],
|
||||
[5000, "2 001–5 000"],
|
||||
[5001, "over 5 000"],
|
||||
] as const)("puts %d active members in the %s band", (n, band) => {
|
||||
expect(hub.activeMemberBand(n)).toBe(band);
|
||||
});
|
||||
});
|
||||
|
||||
describe("signing", () => {
|
||||
const secret = "s3cret-for-tests";
|
||||
const body = JSON.stringify({ hello: "world" });
|
||||
const now = new Date("2026-11-03T10:00:00.000Z");
|
||||
|
||||
it("signs exactly like the Hub protocol v1 heartbeat", () => {
|
||||
const timestamp = now.toISOString();
|
||||
const expected = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
||||
expect(sign(secret, timestamp, body)).toBe(expected);
|
||||
expect(sign(secret, timestamp, new TextEncoder().encode(body))).toBe(expected);
|
||||
});
|
||||
|
||||
it("builds the headers and verifies them", () => {
|
||||
const h = signedHeaders(LINK_HEADERS, { senderId: "inst-1", secret, rawBody: body, now });
|
||||
expect(h[LINK_HEADERS.sender]).toBe("inst-1");
|
||||
expect(verify({ secret, timestamp: h[LINK_HEADERS.timestamp], signature: h[LINK_HEADERS.signature], rawBody: body, now })).toEqual({ ok: true });
|
||||
expect(Object.keys(signedHeaders(HUB_HEADERS, { senderId: "i", secret, rawBody: body, now }))).toEqual(["x-hub-install", "x-hub-timestamp", "x-hub-signature"]);
|
||||
});
|
||||
|
||||
it("refuses a changed body, a wrong secret or a bad signature", () => {
|
||||
const timestamp = now.toISOString();
|
||||
const signature = sign(secret, timestamp, body);
|
||||
expect(verify({ secret, timestamp, signature, rawBody: body + " ", now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret: "other", timestamp, signature, rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret, timestamp, signature: "zz", rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
expect(verify({ secret, timestamp, signature: undefined, rawBody: body, now })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
|
||||
});
|
||||
|
||||
it("refuses requests more than five minutes off the clock", () => {
|
||||
const old = new Date(now.getTime() - 5 * 60 * 1000 - 1).toISOString();
|
||||
expect(verify({ secret, timestamp: old, signature: sign(secret, old, body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" });
|
||||
const edge = new Date(now.getTime() - 5 * 60 * 1000).toISOString();
|
||||
expect(verify({ secret, timestamp: edge, signature: sign(secret, edge, body), rawBody: body, now })).toEqual({ ok: true });
|
||||
expect(verify({ secret, timestamp: "yesterday", signature: sign(secret, "yesterday", body), rawBody: body, now })).toEqual({ ok: false, code: "STALE_REQUEST" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { decodeState, encodeState, isRegisteredRedirectUri, isSafeReturnPath, safeReturnPath } from "../src";
|
||||
|
||||
describe("isSafeReturnPath", () => {
|
||||
it.each([
|
||||
"/",
|
||||
"/dashboard",
|
||||
"/events/youth-camp/register?ticket=adult",
|
||||
"/events/youth-camp#details",
|
||||
"/search?q=youth%20camp",
|
||||
"/a/b/../c",
|
||||
"/caf%C3%A9",
|
||||
])("accepts %p", (path) => {
|
||||
expect(isSafeReturnPath(path)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["absolute URL", "https://evil.com/"],
|
||||
["protocol-relative", "//evil.com"],
|
||||
["backslash host", "/\\evil.com"],
|
||||
["backslash anywhere", "/events\\x"],
|
||||
["encoded slashes", "/%2F%2Fevil.com"],
|
||||
["encoded backslash", "/%5Cevil.com"],
|
||||
["double-encoded slashes", "/%252F%252Fevil.com"],
|
||||
["javascript:", "javascript:alert(1)"],
|
||||
["no leading slash", "dashboard"],
|
||||
["empty", ""],
|
||||
["tab", "/\t/evil.com"],
|
||||
["newline", "/events\n"],
|
||||
["encoded CR/LF", "/events%0D%0ALocation:%20https://evil.com"],
|
||||
["encoded tab before slashes", "/%09/evil.com"],
|
||||
["space", "/events/youth camp"],
|
||||
["bad percent-encoding", "/%E0%A4%A"],
|
||||
["too long", "/" + "a".repeat(2048)],
|
||||
])("refuses %s", (_label, path) => {
|
||||
expect(isSafeReturnPath(path)).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses non-strings", () => {
|
||||
for (const v of [undefined, null, 1, {}, ["/"]]) expect(isSafeReturnPath(v)).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the product's home page", () => {
|
||||
expect(safeReturnPath("//evil.com")).toBe("/");
|
||||
expect(safeReturnPath(undefined, "/dashboard")).toBe("/dashboard");
|
||||
expect(safeReturnPath("/events")).toBe("/events");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sign-in state", () => {
|
||||
const nonce = "n0nce-AbCdEfGhIjKl_123";
|
||||
|
||||
it("round-trips the nonce and the return path, query included", () => {
|
||||
const state = encodeState({ nonce, returnTo: "/events/youth-camp/register?ticket=adult&qty=2" });
|
||||
expect(state).toMatch(/^[A-Za-z0-9_-]+$/);
|
||||
expect(decodeState(state)).toEqual({ nonce, returnTo: "/events/youth-camp/register?ticket=adult&qty=2" });
|
||||
});
|
||||
|
||||
it("never carries an unsafe return path", () => {
|
||||
expect(decodeState(encodeState({ nonce, returnTo: "https://evil.com" }))).toEqual({ nonce, returnTo: "/" });
|
||||
const forged = Buffer.from(JSON.stringify({ n: nonce, r: "//evil.com" })).toString("base64url");
|
||||
expect(decodeState(forged, "/home")).toEqual({ nonce, returnTo: "/home" });
|
||||
});
|
||||
|
||||
it("refuses a short or missing nonce", () => {
|
||||
expect(() => encodeState({ nonce: "short", returnTo: "/" })).toThrow();
|
||||
expect(decodeState(Buffer.from(JSON.stringify({ r: "/" })).toString("base64url"))).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for anything that isn't a state", () => {
|
||||
for (const v of [undefined, "", "not base64!", Buffer.from("not json").toString("base64url"), Buffer.from("[1]").toString("base64url")]) {
|
||||
expect(decodeState(v)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("handles non-ASCII paths", () => {
|
||||
expect(decodeState(encodeState({ nonce, returnTo: "/caf%C3%A9" }))?.returnTo).toBe("/caf%C3%A9");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRegisteredRedirectUri", () => {
|
||||
const registered = ["https://events.hopefamily.co.za/auth/callback"];
|
||||
|
||||
it("only matches exactly", () => {
|
||||
expect(isRegisteredRedirectUri("https://events.hopefamily.co.za/auth/callback", registered)).toBe(true);
|
||||
for (const uri of [
|
||||
"https://events.hopefamily.co.za/auth/callback/",
|
||||
"https://events.hopefamily.co.za/auth/callback?x=1",
|
||||
"https://EVENTS.hopefamily.co.za/auth/callback",
|
||||
"https://events.hopefamily.co.za.evil.com/auth/callback",
|
||||
"http://events.hopefamily.co.za/auth/callback",
|
||||
]) {
|
||||
expect(isRegisteredRedirectUri(uri, registered)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readdirSync } from "node:fs";
|
||||
import type { z } from "zod";
|
||||
import {
|
||||
accountsCallSchema,
|
||||
churchSchema,
|
||||
eventChangedSchema,
|
||||
eventFeedSchema,
|
||||
eventSchema,
|
||||
hub,
|
||||
identityClaimsSchema,
|
||||
userDeletedReplySchema,
|
||||
userExportReplySchema,
|
||||
} from "../src";
|
||||
import { SAMPLES, sample } from "./helpers";
|
||||
|
||||
/** Every sample file and the schema it must pass. A new sample without an entry fails the test. */
|
||||
const SCHEMAS: Record<string, z.ZodType> = {
|
||||
"event.json": eventSchema,
|
||||
"event-simple.json": eventSchema,
|
||||
"event-feed.json": eventFeedSchema,
|
||||
"event-changed.json": eventChangedSchema,
|
||||
"church.json": churchSchema,
|
||||
"identity-claims.json": identityClaimsSchema,
|
||||
"user-updated.json": accountsCallSchema,
|
||||
"user-deleted.json": accountsCallSchema,
|
||||
"user-deleted-reply.json": userDeletedReplySchema,
|
||||
"user-export.json": accountsCallSchema,
|
||||
"user-export-reply.json": userExportReplySchema,
|
||||
"hub-register-request.json": hub.registerRequestSchema,
|
||||
"hub-register-response.json": hub.registerResponseSchema,
|
||||
"hub-heartbeat-events.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-website.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-app.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-accounts.json": hub.heartbeatRequestSchema,
|
||||
"hub-heartbeat-response.json": hub.heartbeatResponseSchema,
|
||||
"hub-licence-payload.json": hub.licencePayloadSchema,
|
||||
};
|
||||
|
||||
describe("samples", () => {
|
||||
const files = readdirSync(SAMPLES).filter((f) => f.endsWith(".json"));
|
||||
|
||||
it("every sample has a schema", () => {
|
||||
expect(files.filter((f) => !(f in SCHEMAS))).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(Object.entries(SCHEMAS))("%s is valid", (file, schema) => {
|
||||
const result = schema.safeParse(sample(file));
|
||||
expect(result.success ? [] : result.error.issues).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(Object.entries(SCHEMAS))("%s keeps every field it sends (no field is silently dropped)", (file, schema) => {
|
||||
const input = sample(file);
|
||||
expect(schema.parse(input)).toEqual(input);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user