Files
crosscode-platform/packages/contracts/tests/agent.test.ts
T
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:02 +02:00

243 lines
12 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({});
});
});