Files
crosscode-platform/packages/contracts/tests/hub-signing.test.ts
T

160 lines
7.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createHmac, generateKeyPairSync } from "node:crypto";
import { hub, linkConnectSchema, linkConnectedSchema, oidcClientAddresses } from "../src";
import * as s from "../src/signing";
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" });
});
});
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);
});
});
describe("signing in through Accounts (contracts 1.5.0)", () => {
it("derives the OIDC client secret from the link secret, stably and per link", () => {
const a = s.newLinkSecret();
expect(s.oidcClientSecret(a)).toBe(s.oidcClientSecret(a));
expect(s.oidcClientSecret(a)).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(s.oidcClientSecret(a)).not.toBe(s.oidcClientSecret(s.newLinkSecret()));
expect(s.oidcClientSecret(a)).not.toBe(a);
});
it("gives every product the same fixed addresses", () => {
expect(oidcClientAddresses("https://www.hope.co.za/")).toEqual({
redirectUri: "https://www.hope.co.za/api/auth/callback",
postLogoutRedirectUri: "https://www.hope.co.za/",
backchannelLogoutUri: "https://www.hope.co.za/api/auth/backchannel-logout",
});
});
});