Files
crosscode-platform/packages/contracts/tests/agent.test.ts
T
joshuaandClaude Opus 5.5 7032e16894 contracts 1.21.0: demo scenarios, eight churches across every product
agent.DEMO_SCENARIOS (one per Website demo profile, each its own fictional
church), DEMO_SCENARIO_ORDER (Accounts first), DEMO_SCENARIO_MIN_VERSIONS,
scenario in seed-demo, accounts in DEMO_PRODUCTS, a profile per scenario for
Events and the App, SEED_SCENARIO_MIN_AGENT (1.7.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:11:46 +02:00

355 lines
19 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 { 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.each(["church-export.json", "church-export-website.json", "church-export-app.json"])("%s has no internal ids", (file) => {
const data = sample(file);
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("seed-demo jobs", () => {
const args = (a: Record<string, unknown>) => agent.jobArgsSchemas["seed-demo"].safeParse(a).success;
it("take a known profile, and an admin email only when it is one", () => {
expect(args({ church: "hope", profile: "ministry" })).toBe(true);
expect(args({ church: "hope", profile: "events", adminEmail: "jane@hope.test" })).toBe(true);
expect(args({ church: "hope", profile: "everything" })).toBe(false);
expect(args({ church: "hope", profile: "small", adminEmail: "not an email; rm -rf /" })).toBe(false);
expect(args({ church: "hope", profile: "small", extra: 1 })).toBe(false);
expect(agent.JOB_TYPES).toContain("seed-demo");
expect(agent.CENTRAL_JOB_TYPES).not.toContain("seed-demo");
});
it("1.19.0: a Website demo names the product and takes only a Website profile", () => {
expect(args({ church: "hope", product: "website", profile: "bold-plant" })).toBe(true);
expect(args({ church: "hope", product: "events", profile: "small" })).toBe(true);
expect(args({ church: "hope", product: "website", profile: "small" })).toBe(false);
// 1.21.0: Events has a profile per scenario too, so a scenario name with no product is an Events demo.
expect(args({ church: "hope", profile: "bold-plant" })).toBe(true);
expect(args({ church: "hope", product: "website", profile: "clean-campus", adminEmail: "jane@hope.test" })).toBe(false);
expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false);
expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8);
});
it("1.20.0: an App demo names the product and takes only an App profile, without an admin email", () => {
expect(agent.DEMO_PRODUCTS).toContain("app");
expect(args({ church: "demo2", product: "app", profile: "community-family" })).toBe(true);
expect(args({ church: "demo2", product: "app", profile: "small" })).toBe(false);
expect(args({ church: "demo2", product: "app", profile: "acacia-hill" })).toBe(false);
expect(args({ church: "demo2", product: "app", profile: "community-family", adminEmail: "jane@hope.test" })).toBe(false);
});
});
describe("demo scenarios (1.21.0)", () => {
const args = (a: Record<string, unknown>) => agent.jobArgsSchemas["seed-demo"].safeParse(a).success;
it("has eight, one per Website demo profile, with unique churches", () => {
expect(agent.DEMO_SCENARIOS.map((s) => s.key)).toEqual([...agent.WEBSITE_DEMO_PROFILES]);
expect(new Set(agent.DEMO_SCENARIOS.map((s) => s.church)).size).toBe(8);
});
it("names only profiles each product has", () => {
for (const s of agent.DEMO_SCENARIOS) {
for (const product of agent.DEMO_SCENARIO_ORDER) {
expect(agent.DEMO_PROFILES_BY_PRODUCT[product]).toContain(s.profiles[product]);
}
}
});
it("loads Accounts first, every demo product once, each with a minimum release and agent", () => {
expect(agent.DEMO_SCENARIO_ORDER[0]).toBe("accounts");
expect([...agent.DEMO_SCENARIO_ORDER].sort()).toEqual([...agent.DEMO_PRODUCTS].sort());
for (const p of agent.DEMO_PRODUCTS) {
expect(agent.DEMO_SCENARIO_MIN_VERSIONS[p]).toMatch(/^\d+\.\d+\.\d+$/);
expect(agent.SEED_DEMO_MIN_AGENT_BY_PRODUCT[p]).toMatch(/^\d+\.\d+\.\d+$/);
}
});
it("covers the App's bands from 0–100 to 2 001–5 000", () => {
const bands = new Set(agent.DEMO_SCENARIOS.map((s) => s.appActiveMembers));
for (const b of ["0–100", "101–300", "301–750", "751–2 000", "2 001–5 000"] as const) expect(bands).toContain(b);
});
it("takes a scenario only with that scenario's profile for the product", () => {
expect(args({ church: "demo2", product: "accounts", profile: "clean-campus", scenario: "clean-campus" })).toBe(true);
expect(args({ church: "demo2", profile: "bold-youth", scenario: "bold-youth" })).toBe(true);
expect(args({ church: "demo2", product: "website", profile: "bold-plant", scenario: "bold-youth" })).toBe(false);
expect(args({ church: "demo2", profile: "events", scenario: "bold-youth" })).toBe(false);
expect(args({ church: "demo2", product: "app", profile: "bold-youth", scenario: "nowhere" })).toBe(false);
});
it("keeps Events' four single-product demos, and Accounts takes no admin email or Events profile", () => {
expect(args({ church: "hope", profile: "multicampus" })).toBe(true);
expect(args({ church: "hope", profile: "clean-modern" })).toBe(true);
expect(args({ church: "demo2", product: "accounts", profile: "small" })).toBe(false);
expect(args({ church: "demo2", product: "accounts", profile: "clean-modern", adminEmail: "jane@hope.test" })).toBe(false);
});
});
describe("env-read and env-set jobs (1.12.0)", () => {
const set = (a: Record<string, unknown>) => agent.jobArgsSchemas["env-set"].safeParse({ church: "hope", product: "events", file: "backend/.env", set: {}, unset: [], restart: true, ...a });
it("read one product", () => {
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "accounts" }).success).toBe(true);
expect(agent.jobArgsSchemas["env-read"].safeParse({ church: "hope", product: "nope" }).success).toBe(false);
expect(agent.JOB_TYPES).toEqual(expect.arrayContaining(["env-read", "env-set"]));
expect(agent.CENTRAL_JOB_TYPES).not.toContain("env-set");
});
it("set plain values in a product's .env file", () => {
expect(set({ set: { FRONTEND_URL: "https://events.hope.test" } }).success).toBe(true);
expect(set({ file: "frontend/.env.production", set: { NEXT_PUBLIC_API_URL: "https://events.hope.test" }, unset: ["OLD_THING"] }).success).toBe(true);
});
it("refuse secrets, nothing to do, newlines, other files and bad names", () => {
expect(set({}).success).toBe(false);
for (const name of ["JWT_SECRET", "DATABASE_URL", "SMTP_PASS", "HUB_LICENCE_KEY", "SENTRY_DSN", "DB_ADMIN_URL"]) {
expect(set({ set: { [name]: "x" } }).success).toBe(false);
expect(set({ unset: [name] }).success).toBe(false);
}
expect(set({ set: { A_URL: "x\nEVIL=1" } }).success).toBe(false);
expect(set({ file: "../.env", set: { A: "1" } }).success).toBe(false);
expect(set({ set: { "lower": "1" } }).success).toBe(false);
expect(set({ set: { A: "1" }, unset: ["A"] }).success).toBe(false);
expect(set({ set: { A: "1" }, extra: true }).success).toBe(false);
});
it("tell secrets by name", () => {
expect(agent.isSecretEnvName("ACCOUNTS_SECRET")).toBe(true);
expect(agent.isSecretEnvName("FRONTEND_URL")).toBe(false);
expect(agent.isSecretEnvName("JOBS_ENABLED")).toBe(false);
});
it("read results", () => {
const ok = agent.envReadResultSchema.safeParse({
product: "events", readAt: "2026-11-20T10:00:00.000Z",
files: [{ file: "backend/.env", exists: true, variables: [
{ name: "FRONTEND_URL", value: "https://events.hope.test", secret: false, set: true, layer: "install", description: null, editable: true },
{ name: "JWT_SECRET", value: null, secret: true, set: true, layer: "generated", description: "never change it", editable: false },
] }],
});
expect(ok.success).toBe(true);
});
});
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"]);
});
it("refuses a TRUST_PROXY the Events backend can't start with", () => {
for (const ok of ["loopback", "1", "true", "false", "loopback, 203.0.113.10", "10.0.0.0/8", "::1", "fd00::/8", "192.168.1.0/255.255.255.0"]) {
expect(agent.checkEnvValue("TRUST_PROXY", ok)).toBeNull();
}
for (const bad of ["TRUE", "True", "yes", "on", "300.1.1.1", "10.0.0.0/8/1", "loopback,"]) {
expect(agent.checkEnvValue("TRUST_PROXY", bad)).toMatch(/^TRUST_PROXY can't be/);
}
expect(agent.checkEnvValue("DB_HOST", "anything")).toBeNull();
expect(agent.invalidValues({ TRUST_PROXY: "TRUE", DB_HOST: "10.0.0.5", DB_PORT: undefined })).toEqual({
TRUST_PROXY: expect.stringContaining("loopback"),
});
expect(agent.invalidValues({ TRUST_PROXY: "loopback" })).toEqual({});
});
});
describe("frp config and free ports (1.15.0)", () => {
const read = (a: Record<string, unknown>) => agent.jobArgsSchemas["frp-read"].safeParse(a).success;
const write = (a: Record<string, unknown>) => agent.jobArgsSchemas["frp-write"].safeParse({ path: "/etc/frp/frps.toml", content: "bindPort = 7000\n", restart: true, ...a }).success;
it("read the config the agent finds, or one at a path", () => {
expect(read({})).toBe(true);
expect(read({ path: "/etc/frp/frps.toml" })).toBe(true);
expect(read({ path: "/usr/local/frp/frpc.ini" })).toBe(true);
for (const path of ["/etc/shadow", "etc/frp/frps.ini", "/etc/frp/../shadow/frps.ini", "/etc/frp/frps.ini; rm -rf /", "/etc/frp/frps.service", "/etc/frp/server.toml"]) expect(read({ path })).toBe(false);
expect(read({ path: "/etc/frp/frps.ini", extra: 1 })).toBe(false);
});
it("write one, with content and whether to restart", () => {
expect(write({})).toBe(true);
expect(write({ content: "" })).toBe(false);
expect(write({ content: "x".repeat(agent.FRP_CONFIG_MAX + 1) })).toBe(false);
expect(write({ path: "/etc/passwd" })).toBe(false);
expect(write({ restart: "yes" })).toBe(false);
});
it("probe ports", () => {
expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [20000, 20001] }).success).toBe(true);
expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [] }).success).toBe(false);
expect(agent.jobArgsSchemas["probe-ports"].safeParse({ ports: [80] }).success).toBe(false);
});
it("the central agent runs all three", () => {
expect(agent.CENTRAL_JOB_TYPES).toEqual(expect.arrayContaining(["frp-read", "frp-write", "probe-ports"]));
expect(agent.JOB_TIME_LIMIT_MINUTES["frp-write"]).toBeGreaterThan(0);
});
it("results", () => {
expect(agent.frpReadResultSchema.safeParse({
service: "frps", path: "/etc/frp/frps.toml", source: "systemd", found: true, format: "toml", content: `auth.token = "${agent.FRP_HIDDEN}"\n`, hidden: ["auth.token"],
proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999", serviceRunning: true, readAt: "2026-11-21T10:00:00.000Z",
}).success).toBe(true);
expect(agent.probePortsResultSchema.safeParse({ ports: [{ port: 20000, free: false, reason: "in use" }], configPath: null }).success).toBe(true);
});
});
describe("uninstalling one product (contracts 1.16.0)", () => {
const ok = (type: "export" | "uninstall" | "purge", args: unknown) => agent.jobArgsSchemas[type].safeParse(args).success;
it("export, uninstall and purge take the products, or none (the whole church)", () => {
for (const type of ["uninstall", "purge"] as const) {
expect(ok(type, { church: "hope" })).toBe(true);
expect(ok(type, { church: "hope", products: ["events"] })).toBe(true);
expect(ok(type, { church: "hope", products: [] })).toBe(false);
expect(ok(type, { church: "hope", products: ["everything"] })).toBe(false);
}
expect(ok("export", { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] })).toBe(true);
expect(agent.PRODUCT_UNINSTALL_MIN_AGENT).toBe("1.5.0");
});
});