Files
crosscode-platform/packages/contracts/tests/hub-signing.test.ts
T
joshuaandClaude Opus 5.5 4952e2cb0f Contracts 1.4.0: crosscode.link/1 and a public key in the v2 heartbeat
- crosscode.link/1 (link.connect / link.connected / link.disconnect), with
  signLink / verifyLink, PEM conversion, link secrets and nonces.
- The v2 heartbeat can carry the install's publicKey; the reply says
  saved / matches / mismatch (Hub 2.2.0). Never a failed heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:58:26 +02:00

142 lines
6.9 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 } 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);
});
});