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:
@@ -0,0 +1,320 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, productSchema } from "./common";
|
||||
|
||||
/**
|
||||
* The server agent (docs/AGENT-1.0-PLAN.md, ROADMAP-v3 phase 1d): what the Hub and the agent on
|
||||
* each server send each other. The agent only polls (it listens on nothing), runs only the
|
||||
* `crosscode` script, and only for jobs of the fixed types below, signed by the Hub.
|
||||
*
|
||||
* Signing and encryption (Node only) are in `@crosscode/contracts/signing`:
|
||||
* - jobs: Ed25519 by the Hub over `canonicalJson(job without "signature")`;
|
||||
* - agent → Hub requests: Ed25519 by the agent over `timestamp + "." + rawBody` ({@link AGENT_HEADERS});
|
||||
* - the job's `config`: sealed to the server's X25519 key (X25519 + HKDF-SHA256 + AES-256-GCM).
|
||||
*/
|
||||
|
||||
export const AGENT_API_VERSION = 1;
|
||||
|
||||
/** Headers on every agent → Hub request (after joining). */
|
||||
export const AGENT_HEADERS = {
|
||||
server: "x-crosscode-server",
|
||||
timestamp: "x-crosscode-timestamp",
|
||||
signature: "x-crosscode-signature",
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Building blocks
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** A church's short name: folders, PM2 names, database names, tunnel names (`hope`, `cross-roads`). */
|
||||
export const shortNameSchema = z.string().regex(/^[a-z][a-z0-9-]{1,30}$/, "Expected a short name: a-z, 0-9 and -, starting with a letter");
|
||||
|
||||
/** A release tag, `<product>@x.y.z` (no prereleases: jobs only install releases). */
|
||||
export const releaseTagSchema = z.string().regex(/^(accounts|events|website|app)@\d+\.\d+\.\d+$/, "Expected <product>@x.y.z");
|
||||
|
||||
/** An agent release tag, `agent@x.y.z`. */
|
||||
export const agentTagSchema = z.string().regex(/^agent@\d+\.\d+\.\d+$/, "Expected agent@x.y.z");
|
||||
|
||||
/** A host name (no scheme, no path): `events.hope.co.za`. */
|
||||
export const domainSchema = z.string().max(253).regex(/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/, "Expected a domain like events.hope.co.za");
|
||||
|
||||
/** A TCP port the Hub hands out (frp tunnels use the same number on both ends). */
|
||||
export const portSchema = z.int().min(1024).max(65535);
|
||||
|
||||
/** An absolute path on the server without `..`, spaces or shell characters. */
|
||||
export const serverPathSchema = z.string().max(255).regex(/^\/(?!.*\/\.\.?(\/|$))[A-Za-z0-9._/-]+$/, "Expected an absolute path");
|
||||
|
||||
export const productPortsSchema = z.object({ web: portSchema, api: portSchema }).refine((p) => p.web !== p.api, "web and api must differ");
|
||||
export type ProductPorts = z.infer<typeof productPortsSchema>;
|
||||
|
||||
export const AGENT_MODES = ["church", "central"] as const;
|
||||
export const agentModeSchema = z.enum(AGENT_MODES);
|
||||
export type AgentMode = z.infer<typeof agentModeSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Jobs (crosscode.agent-job/1)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */
|
||||
export const jobArgsSchemas = {
|
||||
/** `crosscode install <church> --products … --frp --json` */
|
||||
install: z.strictObject({
|
||||
church: shortNameSchema,
|
||||
products: z.array(productSchema).min(1).max(4),
|
||||
/** Per product: the release (default: the latest). */
|
||||
versions: z.partialRecord(productSchema, releaseTagSchema).optional(),
|
||||
/** Per product: where it's served. */
|
||||
domains: z.partialRecord(productSchema, domainSchema),
|
||||
/** Per product: the ports from the Hub's port list. */
|
||||
ports: z.partialRecord(productSchema, productPortsSchema),
|
||||
}),
|
||||
/** `crosscode add <church> <product>` (from phase 3). */
|
||||
"add-product": z.strictObject({ church: shortNameSchema, product: productSchema, version: releaseTagSchema.optional(), domain: domainSchema, ports: productPortsSchema }),
|
||||
/** `crosscode deploy <church> [products] [--version …] --json` */
|
||||
deploy: z.strictObject({
|
||||
church: shortNameSchema,
|
||||
products: z.array(productSchema).min(1).max(4),
|
||||
versions: z.array(releaseTagSchema).max(4).optional(),
|
||||
check: z.boolean().optional(),
|
||||
}),
|
||||
/** `crosscode adopt <church> --events-dir <dir> [--version …] [--address …] --json` */
|
||||
adopt: z.strictObject({ church: shortNameSchema, eventsDir: serverPathSchema, version: releaseTagSchema.optional(), address: domainSchema.optional() }),
|
||||
"adopt-undo": z.strictObject({ church: shortNameSchema }),
|
||||
/** `crosscode restart <church> [product] --json` (PM2 reload) */
|
||||
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
|
||||
/** `crosscode export <church> --out <zip> --json`; the agent encrypts the ZIP and uploads it under `exportId`. */
|
||||
export: z.strictObject({ church: shortNameSchema, exportId: z.string().regex(/^exp_[A-Za-z0-9_-]{8,64}$/) }),
|
||||
/** `crosscode uninstall <church> --json` */
|
||||
uninstall: z.strictObject({ church: shortNameSchema }),
|
||||
/** `crosscode purge <church> --json` (deletes what uninstall kept for 30 days) */
|
||||
purge: z.strictObject({ church: shortNameSchema }),
|
||||
/** The agent updates itself to that tag. */
|
||||
"update-agent": z.strictObject({ version: agentTagSchema }),
|
||||
/** Central server only: are these ports allowed, open and bound to 127.0.0.1? */
|
||||
"check-ports": z.strictObject({ ports: z.array(portSchema).min(1).max(50) }),
|
||||
/** `crosscode status [<church>] --json` */
|
||||
status: z.strictObject({ church: shortNameSchema.optional() }),
|
||||
} as const;
|
||||
|
||||
export type JobType = keyof typeof jobArgsSchemas;
|
||||
export const JOB_TYPES = Object.keys(jobArgsSchemas) as JobType[];
|
||||
export const jobTypeSchema = z.enum(JOB_TYPES as [JobType, ...JobType[]]);
|
||||
export type JobArgs<T extends JobType> = z.infer<(typeof jobArgsSchemas)[T]>;
|
||||
|
||||
/** The only jobs a central agent runs (§3). */
|
||||
export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "update-agent"];
|
||||
|
||||
/** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */
|
||||
export const JOB_TIME_LIMIT_MINUTES: Record<JobType, number> = {
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, export: 20,
|
||||
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
|
||||
};
|
||||
|
||||
/** Config sealed to the server's X25519 key (`sealConfig` in `@crosscode/contracts/signing`). */
|
||||
export const sealedSchema = z.strictObject({
|
||||
alg: z.literal("x25519-hkdf-sha256-aes-256-gcm"),
|
||||
/** The sender's one-time X25519 public key, base64url (raw 32 bytes). */
|
||||
epk: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
|
||||
/** 12-byte nonce, base64url. */
|
||||
iv: z.string().regex(/^[A-Za-z0-9_-]{16}$/),
|
||||
/** Ciphertext with the 16-byte GCM tag appended, base64url. */
|
||||
ciphertext: z.string().regex(/^[A-Za-z0-9_-]+$/).max(200_000),
|
||||
});
|
||||
export type Sealed = z.infer<typeof sealedSchema>;
|
||||
|
||||
/**
|
||||
* What a job's sealed `config` holds once opened (§5): `.env` values by layer, each keyed by the
|
||||
* variable name. `generated` values are never sent: the server makes them.
|
||||
*/
|
||||
export const jobConfigSchema = z.strictObject({
|
||||
server: z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000)).default({}),
|
||||
defaults: z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000)).default({}),
|
||||
/** Per product: the install's own values (URLs, timezone, licence key, PORT). */
|
||||
install: z.partialRecord(productSchema, z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000))).default({}),
|
||||
});
|
||||
export type JobConfig = z.infer<typeof jobConfigSchema>;
|
||||
|
||||
const jobBase = {
|
||||
schema: z.literal("crosscode.agent-job/1"),
|
||||
id: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
config: sealedSchema.nullable().optional(),
|
||||
notBefore: dateTimeSchema,
|
||||
expiresAt: dateTimeSchema,
|
||||
/** Ed25519 over `canonicalJson(job without "signature")`, base64url. */
|
||||
signature: z.string().regex(/^[A-Za-z0-9_-]{86}$/),
|
||||
};
|
||||
|
||||
function jobOf<T extends JobType>(type: T) {
|
||||
return z.strictObject({ ...jobBase, type: z.literal(type), args: jobArgsSchemas[type] });
|
||||
}
|
||||
|
||||
export const agentJobSchema = z.discriminatedUnion("type", [
|
||||
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"),
|
||||
jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
||||
]);
|
||||
export type AgentJob = z.infer<typeof agentJobSchema>;
|
||||
export type UnsignedAgentJob = Omit<AgentJob, "signature">;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reports (crosscode.agent-report/1)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
export const JOB_STATUSES = ["succeeded", "failed", "rolled-back", "refused", "expired"] as const;
|
||||
export const jobStatusSchema = z.enum(JOB_STATUSES);
|
||||
export type JobStatus = z.infer<typeof jobStatusSchema>;
|
||||
|
||||
export const reportStepSchema = z.object({
|
||||
name: z.string().max(200),
|
||||
startedAt: dateTimeSchema,
|
||||
finishedAt: dateTimeSchema.nullable(),
|
||||
outcome: z.enum(["ok", "failed", "skipped", "rolled-back"]),
|
||||
detail: z.string().max(2000).optional(),
|
||||
});
|
||||
export type ReportStep = z.infer<typeof reportStepSchema>;
|
||||
|
||||
/**
|
||||
* A job's result. The `crosscode … --json` output is the report without `jobId`, `serverId` and
|
||||
* `log`; the agent adds those (the log's last 200 lines, filtered for secrets) and signs the request.
|
||||
*/
|
||||
export const agentReportSchema = z.object({
|
||||
schema: z.literal("crosscode.agent-report/1"),
|
||||
jobId: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
type: jobTypeSchema,
|
||||
status: jobStatusSchema,
|
||||
startedAt: dateTimeSchema,
|
||||
finishedAt: dateTimeSchema,
|
||||
steps: z.array(reportStepSchema).max(200),
|
||||
/** What the command found or did, by type (versions, ports, the export's size …). */
|
||||
result: z.record(z.string(), z.unknown()).default({}),
|
||||
/** Why a job was refused or failed, in a sentence. */
|
||||
message: z.string().max(2000).optional(),
|
||||
log: z.array(z.string().max(1000)).max(200),
|
||||
});
|
||||
export type AgentReport = z.infer<typeof agentReportSchema>;
|
||||
|
||||
/** What `crosscode … --json` prints: the report's own part. */
|
||||
export const scriptReportSchema = agentReportSchema.omit({ schema: true, jobId: true, serverId: true, type: true, log: true }).extend({
|
||||
schema: z.literal("crosscode.script-report/1"),
|
||||
command: z.string().max(40),
|
||||
});
|
||||
export type ScriptReport = z.infer<typeof scriptReportSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Stats (crosscode.agent-stats/1), every 60 s
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const bytes = z.number().nonnegative();
|
||||
|
||||
export const processStatSchema = z.object({
|
||||
name: z.string().max(100),
|
||||
church: shortNameSchema.nullable(),
|
||||
product: productSchema.nullable(),
|
||||
status: z.string().max(40),
|
||||
memoryBytes: bytes,
|
||||
cpuPercent: z.number().nonnegative(),
|
||||
restarts: z.int().nonnegative(),
|
||||
uptimeSeconds: z.number().nonnegative(),
|
||||
});
|
||||
|
||||
export const centralStatSchema = z.object({
|
||||
/** `proxy_bind_addr` in frps.ini, null when it isn't set (tunnels then open on every address). */
|
||||
proxyBindAddr: z.string().max(100).nullable(),
|
||||
/** `allow_ports` in frps.ini as written, e.g. `20000-29999`. */
|
||||
allowPorts: z.string().max(2000).nullable(),
|
||||
frpsRunning: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
export const agentStatsSchema = z.object({
|
||||
schema: z.literal("crosscode.agent-stats/1"),
|
||||
at: dateTimeSchema,
|
||||
ram: z.object({ totalBytes: bytes, usedBytes: bytes, availableBytes: bytes, swapTotalBytes: bytes, swapUsedBytes: bytes }),
|
||||
cpu: z.object({ percent: z.number().min(0).max(100), load1: z.number().nonnegative(), load5: z.number().nonnegative(), load15: z.number().nonnegative(), cores: z.int().positive() }),
|
||||
disks: z.array(z.object({ mount: z.string().max(255), totalBytes: bytes, usedBytes: bytes, freeBytes: bytes })).max(30),
|
||||
uptimeSeconds: z.number().nonnegative(),
|
||||
versions: z.object({ os: z.string().max(200), node: z.string().max(40), postgres: z.string().max(40).nullable(), frpc: z.string().max(40).nullable(), agent: z.string().max(40) }),
|
||||
frpcRunning: z.boolean().nullable(),
|
||||
processes: z.array(processStatSchema).max(200),
|
||||
central: centralStatSchema.nullable().optional(),
|
||||
});
|
||||
export type AgentStats = z.infer<typeof agentStatsSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Agent API (/api/agent/v1/*)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const base64urlKey = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "Expected a raw 32-byte key, base64url");
|
||||
|
||||
/** POST /api/agent/v1/join (unsigned: the one-time token is the proof). */
|
||||
export const joinRequestSchema = z.object({
|
||||
agentApiVersion: z.literal(AGENT_API_VERSION),
|
||||
token: z.string().regex(/^[A-Za-z0-9_-]{32,128}$/),
|
||||
mode: agentModeSchema,
|
||||
hostname: z.string().max(253),
|
||||
agentVersion: z.string().max(40),
|
||||
/** The agent's Ed25519 key (signs its requests) and X25519 key (receives config). */
|
||||
publicKeys: z.object({ ed25519: base64urlKey, x25519: base64urlKey }),
|
||||
});
|
||||
export const joinResponseSchema = z.object({
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
/** The Hub's job-signing Ed25519 key, pinned by the agent. */
|
||||
hubJobKey: base64urlKey,
|
||||
pollSeconds: z.int().min(5).max(600),
|
||||
statsSeconds: z.int().min(15).max(3600),
|
||||
});
|
||||
|
||||
/** POST /api/agent/v1/poll (signed). */
|
||||
export const pollRequestSchema = z.object({
|
||||
agentApiVersion: z.literal(AGENT_API_VERSION),
|
||||
agentVersion: z.string().max(40),
|
||||
mode: agentModeSchema,
|
||||
/** The job being run now, if any (the Hub won't hand out another). */
|
||||
runningJobId: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/).nullable(),
|
||||
});
|
||||
export const pollResponseSchema = z.object({
|
||||
jobs: z.array(z.unknown()).max(10), // each checked with agentJobSchema and the signature by the agent
|
||||
pollSeconds: z.int().min(5).max(600),
|
||||
});
|
||||
|
||||
/** POST /api/agent/v1/stats (signed): an {@link agentStatsSchema} body. → 204 */
|
||||
/** POST /api/agent/v1/report (signed): an {@link agentReportSchema} body. → 204 */
|
||||
/** PUT /api/agent/v1/exports/:exportId (signed): the encrypted ZIP, `application/octet-stream`. → 204 */
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Env template (crosscode.env-template/1): apps/<product>/env.template.json
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
export const ENV_LAYERS = ["server", "defaults", "install", "generated"] as const;
|
||||
export const envLayerSchema = z.enum(ENV_LAYERS);
|
||||
|
||||
export const envVariableSchema = z.object({
|
||||
name: z.string().regex(/^[A-Z][A-Z0-9_]*$/),
|
||||
layer: envLayerSchema,
|
||||
required: z.boolean().default(false),
|
||||
/** Used when no layer gives a value. */
|
||||
default: z.string().max(4000).optional(),
|
||||
/** Built from the install's values: `https://{domain}`, `{apiPort}`. */
|
||||
from: z.string().max(400).optional(),
|
||||
description: z.string().max(400).optional(),
|
||||
});
|
||||
export type EnvVariable = z.infer<typeof envVariableSchema>;
|
||||
|
||||
export const envTemplateSchema = z.object({
|
||||
schema: z.literal("crosscode.env-template/1"),
|
||||
product: productSchema,
|
||||
/** Relative to the product's folder (`apps/<product>`): `backend/.env`, `frontend/.env.production`. */
|
||||
files: z.record(z.string().regex(/^[a-z0-9._/-]+$/), z.array(envVariableSchema).min(1)),
|
||||
});
|
||||
export type EnvTemplate = z.infer<typeof envTemplateSchema>;
|
||||
|
||||
/** The variables a layer must provide for a template, that it doesn't (the Hub's check before a job). */
|
||||
export function missingRequired(template: EnvTemplate, layer: "server" | "defaults", values: Record<string, string | undefined>): string[] {
|
||||
const missing: string[] = [];
|
||||
for (const vars of Object.values(template.files)) {
|
||||
for (const v of vars) {
|
||||
if (v.layer !== layer || !v.required || v.default !== undefined) continue;
|
||||
if (!values[v.name] || !String(values[v.name]).trim()) missing.push(v.name);
|
||||
}
|
||||
}
|
||||
return [...new Set(missing)];
|
||||
}
|
||||
Reference in New Issue
Block a user