Files
crosscode-platform/packages/contracts/tests/agent.test.ts
T
joshuaandClaude Opus 5.5 8899c97a9c Agent 1.5.0 + contracts 1.16.0: uninstall, export and purge one product of a church
crosscode uninstall/export/purge <church> [product ...]: with products named only those
go and the church keeps the others; naming every product it still has removes the church
(folder and app user), so the last product to go takes the church with it. The report
gives products and remaining. Uninstalling cross-events-demo's Events removed its Accounts
too, which the Hub still showed as live.

Contracts 1.16.0: optional products on export/uninstall/purge, PRODUCT_UNINSTALL_MIN_AGENT.
Agent 1.5.0 passes them to crosscode. The Website plan moves to contracts 1.17.0 / Hub 2.13.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:32 +02:00

292 lines
15 KiB
TypeScript

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("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");
});
});
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");
});
});