contracts 1.3.0: agent jobs, reports, stats, join/poll, env templates, church export

Jobs of fixed types with strict argument schemas, signed by the Hub with
Ed25519 over canonical JSON. Agent requests signed with the server's
Ed25519 key. Config sealed to the server's X25519 key (X25519 + HKDF +
AES-256-GCM; Node has no XSalsa20). Exports encrypted with a key that
only travels in the download link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:02:24 +02:00
co-authored by Claude Opus 5.5
parent 53e15fdd69
commit 90a98a4306
22 changed files with 3645 additions and 2 deletions
+174
View File
@@ -0,0 +1,174 @@
import { agent, canonicalJson, churchExportSchema, INTERNAL_ID_KEYS } from "../src";
import {
decryptExport,
encryptExport,
generateEd25519,
generateX25519,
openConfig,
publicKeyOf,
sealConfig,
signAgentRequest,
signJob,
verifyAgentRequest,
verifyJob,
} from "../src/signing";
import { sample } from "./helpers";
const hubKeys = generateEd25519();
const serverKeys = { ed: generateEd25519(), x: generateX25519() };
function unsignedJob(over: Record<string, unknown> = {}) {
return {
schema: "crosscode.agent-job/1",
id: "job_abcdefgh12",
serverId: "srv_abcdefgh12",
type: "deploy",
args: { church: "hope", products: ["events"], versions: ["events@2.4.1"] },
config: null,
notBefore: "2026-11-20T12:00:00.000Z",
expiresAt: "2026-11-20T12:15:00.000Z",
...over,
};
}
describe("canonical JSON", () => {
it("sorts keys at every level and drops undefined", () => {
expect(canonicalJson({ b: 1, a: { d: [3, { z: 1, y: 2 }], c: undefined } })).toBe('{"a":{"d":[3,{"y":2,"z":1}]},"b":1}');
});
it("refuses values that don't round-trip", () => {
expect(() => canonicalJson({ a: new Date() })).toThrow();
expect(() => canonicalJson(Number.NaN)).toThrow();
});
});
describe("jobs", () => {
it("a signed job parses and verifies with the pinned Hub key", () => {
const job = signJob(unsignedJob(), hubKeys.privateKeyPem);
expect(agent.agentJobSchema.safeParse(job).success).toBe(true);
expect(verifyJob(job, hubKeys.publicKey)).toBe(true);
});
it("key order doesn't matter, but any change to the content does", () => {
const job = signJob(unsignedJob(), hubKeys.privateKeyPem);
const reordered = Object.fromEntries(Object.entries(job).reverse());
expect(verifyJob(reordered, hubKeys.publicKey)).toBe(true);
expect(verifyJob({ ...job, args: { ...job.args, church: "other" } }, hubKeys.publicKey)).toBe(false);
expect(verifyJob({ ...job, expiresAt: "2026-12-20T12:15:00.000Z" }, hubKeys.publicKey)).toBe(false);
});
it("a job signed by another key is refused", () => {
const forged = signJob(unsignedJob(), generateEd25519().privateKeyPem);
expect(verifyJob(forged, hubKeys.publicKey)).toBe(false);
expect(verifyJob({ ...unsignedJob(), signature: "x".repeat(86) }, hubKeys.publicKey)).toBe(false);
});
it.each([
["shell characters in a name", { args: { church: "hope; rm -rf /", products: ["events"] } }],
["an unknown product", { args: { church: "hope", products: ["shop"] } }],
["a version that isn't a release tag", { args: { church: "hope", products: ["events"], versions: ["main"] } }],
["an unknown argument", { args: { church: "hope", products: ["events"], command: "id" } }],
["an unknown type", { type: "run", args: { command: "id" } }],
])("refuses %s", (_label, over) => {
const job = signJob(unsignedJob(over), hubKeys.privateKeyPem);
expect(agent.agentJobSchema.safeParse(job).success).toBe(false);
});
it("adopt only takes a plain absolute folder", () => {
const ok = signJob(unsignedJob({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/hope-events" } }), hubKeys.privateKeyPem);
expect(agent.agentJobSchema.safeParse(ok).success).toBe(true);
for (const eventsDir of ["/var/www/../etc", "relative/dir", "/var/www/a b", "/var/www/$(id)"]) {
const bad = signJob(unsignedJob({ type: "adopt", args: { church: "hope", eventsDir } }), hubKeys.privateKeyPem);
expect(agent.agentJobSchema.safeParse(bad).success).toBe(false);
}
});
it("install needs different web and api ports", () => {
const args = { church: "hope", products: ["events"], domains: { events: "events.hope.co.za" }, ports: { events: { web: 20010, api: 20010 } } };
expect(agent.jobArgsSchemas.install.safeParse(args).success).toBe(false);
expect(agent.jobArgsSchemas.install.safeParse({ ...args, ports: { events: { web: 20010, api: 20011 } } }).success).toBe(true);
});
});
describe("agent requests", () => {
const body = JSON.stringify({ agentApiVersion: 1, agentVersion: "1.0.0", mode: "church", runningJobId: null });
const now = new Date("2026-11-20T12:00:00Z");
it("verify with the server's key, within five minutes", () => {
const h = signAgentRequest({ serverId: "srv_abcdefgh12", privateKeyPem: serverKeys.ed.privateKeyPem, rawBody: body, now });
const check = (over: Partial<Parameters<typeof verifyAgentRequest>[0]>) =>
verifyAgentRequest({ publicKey: serverKeys.ed.publicKey, timestamp: h[agent.AGENT_HEADERS.timestamp], signature: h[agent.AGENT_HEADERS.signature], rawBody: body, now, ...over });
expect(check({})).toEqual({ ok: true });
expect(check({ rawBody: `${body} ` })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
expect(check({ publicKey: generateEd25519().publicKey })).toEqual({ ok: false, code: "BAD_SIGNATURE" });
expect(check({ now: new Date(now.getTime() + 6 * 60 * 1000) })).toEqual({ ok: false, code: "STALE_REQUEST" });
});
});
describe("sealed config", () => {
const config = { server: { TRUST_PROXY: "loopback", DB_HOST: "10.0.0.5" }, defaults: { HUB_URL: "https://hub.crosscode.co.za" }, install: { events: { FRONTEND_URL: "https://events.hope.co.za" } } };
it("only the server's key opens it", () => {
const sealed = sealConfig(config, serverKeys.x.publicKey);
expect(agent.sealedSchema.safeParse(sealed).success).toBe(true);
expect(JSON.stringify(sealed)).not.toContain("loopback");
expect(openConfig(sealed, serverKeys.x.privateKeyPem)).toEqual(config);
expect(() => openConfig(sealed, generateX25519().privateKeyPem)).toThrow();
});
it("a changed ciphertext is refused", () => {
const sealed = sealConfig(config, serverKeys.x.publicKey);
const bytes = Buffer.from(sealed.ciphertext, "base64url");
bytes[0] = (bytes[0] ?? 0) ^ 1;
expect(() => openConfig({ ...sealed, ciphertext: bytes.toString("base64url") }, serverKeys.x.privateKeyPem)).toThrow();
});
it("the opened config parses", () => {
expect(agent.jobConfigSchema.safeParse(config).success).toBe(true);
});
it("publicKeyOf matches the generated pair", () => {
expect(publicKeyOf(serverKeys.x.privateKeyPem)).toBe(serverKeys.x.publicKey);
expect(publicKeyOf(serverKeys.ed.privateKeyPem)).toBe(serverKeys.ed.publicKey);
});
});
describe("exports", () => {
it("encrypt and decrypt with the link's key", () => {
const zip = Buffer.from("PK\u0003\u0004 pretend zip");
const { key, file } = encryptExport(zip);
expect(file.includes(zip)).toBe(false);
expect(decryptExport(file, key).equals(zip)).toBe(true);
expect(() => decryptExport(file, encryptExport(zip).key)).toThrow();
});
it("the sample has no internal ids", () => {
const data = sample("church-export.json");
expect(churchExportSchema.safeParse(data).success).toBe(true);
const keys: string[] = [];
const walk = (v: unknown): void => {
if (Array.isArray(v)) v.forEach(walk);
else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) { keys.push(k); walk(x); }
};
walk(data);
expect(keys.filter((k) => INTERNAL_ID_KEYS.test(k))).toEqual([]);
});
});
describe("env templates", () => {
it("lists the required server and defaults values that are missing", () => {
const template = agent.envTemplateSchema.parse({
schema: "crosscode.env-template/1",
product: "events",
files: {
"backend/.env": [
{ name: "TRUST_PROXY", layer: "server", required: true },
{ name: "DB_HOST", layer: "server", required: true },
{ name: "BACKUP_ENABLED", layer: "defaults", required: true, default: "true" },
{ name: "HUB_URL", layer: "defaults", required: true },
],
},
});
expect(agent.missingRequired(template, "server", { TRUST_PROXY: "loopback" })).toEqual(["DB_HOST"]);
expect(agent.missingRequired(template, "defaults", {})).toEqual(["HUB_URL"]);
});
});
@@ -35,6 +35,7 @@ const SAMPLE_SCHEMA: Record<string, string> = {
"hub-heartbeat-accounts.json": "hub-heartbeat-request",
"hub-heartbeat-response.json": "hub-heartbeat-response",
"hub-licence-payload.json": "hub-licence-payload",
"church-export.json": "church-export",
};
describe("JSON Schema (schemas/)", () => {
+2
View File
@@ -2,6 +2,7 @@ import { readdirSync } from "node:fs";
import type { z } from "zod";
import {
accountsCallSchema,
churchExportSchema,
churchSchema,
eventChangedSchema,
eventFeedSchema,
@@ -34,6 +35,7 @@ const SCHEMAS: Record<string, z.ZodType> = {
"hub-heartbeat-accounts.json": hub.heartbeatRequestSchema,
"hub-heartbeat-response.json": hub.heartbeatResponseSchema,
"hub-licence-payload.json": hub.licencePayloadSchema,
"church-export.json": churchExportSchema,
};
describe("samples", () => {