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>
535 lines
28 KiB
TypeScript
535 lines
28 KiB
TypeScript
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)
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
/** Cross Events' demo data sets (`apps/events/backend/scripts/set-demo.js`). */
|
|
export const DEMO_PROFILES = ["small", "events", "ministry", "multicampus"] as const;
|
|
export const demoProfileSchema = z.enum(DEMO_PROFILES);
|
|
export type DemoProfile = z.infer<typeof demoProfileSchema>;
|
|
|
|
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
|
|
export const SEED_DEMO_MIN_AGENT = "1.2.0";
|
|
|
|
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
|
|
export const ENV_JOBS_MIN_AGENT = "1.3.0";
|
|
|
|
/** A .env variable's name. */
|
|
export const envNameSchema = z.string().max(100).regex(/^[A-Z][A-Z0-9_]*$/, "Expected an env variable name (A-Z, 0-9, _)");
|
|
|
|
/** A product's .env file, relative to `apps/<product>`: `backend/.env`, `frontend/.env.production`. */
|
|
export const envFileSchema = z.string().max(100).regex(/^(backend|frontend)\/\.env(\.production)?$/, "Expected backend/.env or frontend/.env.production");
|
|
|
|
/**
|
|
* Names whose values are secrets: never shown on the Hub (only whether they're set) and never
|
|
* changed from it. Keep in step with SECRET_NAME in scripts/lib/envedit.cjs.
|
|
*/
|
|
export const SECRET_ENV_NAME = /(SECRET|PASS|TOKEN|PRIVATE|CREDENTIAL|_KEY$|_DSN$|DATABASE_URL|ADMIN_URL)/;
|
|
export const isSecretEnvName = (name: string): boolean => SECRET_ENV_NAME.test(name);
|
|
|
|
/** At most this many changes in one `env-set` job. */
|
|
export const ENV_SET_MAX = 50;
|
|
|
|
/** The first agent that runs `frp-read`, `frp-write` and `probe-ports` jobs (an older one refuses the unknown types). */
|
|
export const FRP_JOBS_MIN_AGENT = "1.4.0";
|
|
|
|
/**
|
|
* The first agent that takes `products` on `export`, `uninstall` and `purge` (only those products
|
|
* go; the church keeps its others). An older one refuses the key, and uninstalls the whole church
|
|
* without it.
|
|
*/
|
|
export const PRODUCT_UNINSTALL_MIN_AGENT = "1.5.0";
|
|
|
|
/**
|
|
* Where frps (central server) or frpc (church server) keeps its config: an absolute path to a file
|
|
* whose name starts with `frp` and ends in `.ini` or `.toml` (`/etc/frp/frps.toml`).
|
|
*/
|
|
export const frpConfigPathSchema = serverPathSchema.regex(/\/frp[A-Za-z0-9._-]*\.(ini|toml)$/, "Expected the path of frps's or frpc's config: a file named frp….ini or frp….toml");
|
|
|
|
/** The longest frp config the Hub reads or writes. */
|
|
export const FRP_CONFIG_MAX = 64_000;
|
|
|
|
/**
|
|
* Secret values in an frp config (token, passwords) never leave the server: `frp-read` shows them
|
|
* as this, and `frp-write` puts the server's own value back where it finds it. A secret can't be
|
|
* changed from the Hub.
|
|
*/
|
|
export const FRP_HIDDEN = "***hidden***";
|
|
|
|
/** 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 demo <church> --profile <profile> [--admin-email <email>] --json`: replaces Cross
|
|
* Events' data with a demo set (a backup is taken first). The Hub only makes it for installs
|
|
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
|
|
*/
|
|
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
|
|
/**
|
|
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
|
|
* whether they're set). The report's `result` is an {@link envReadResultSchema}.
|
|
*/
|
|
"env-read": z.strictObject({ church: shortNameSchema, product: productSchema }),
|
|
/**
|
|
* `crosscode env <church> <product> --file <file> --set NAME=value … --unset NAME … [--restart]
|
|
* --json`: changes values in one .env file (a copy is kept first), rebuilds the frontend when its
|
|
* file changed (Next.js builds the values in), then reloads; on a failure the file is put back.
|
|
* Never secrets, never what the server generates (DATABASE_URL, JWT_SECRET …): the script
|
|
* refuses those too.
|
|
*/
|
|
"env-set": z.strictObject({
|
|
church: shortNameSchema,
|
|
product: productSchema,
|
|
file: envFileSchema,
|
|
set: z.record(envNameSchema, z.string().max(4000).regex(/^[^\r\n]*$/, "Values can't contain newlines")),
|
|
unset: z.array(envNameSchema).max(ENV_SET_MAX),
|
|
restart: z.boolean(),
|
|
}).check((ctx) => {
|
|
const a = ctx.value;
|
|
const names = [...Object.keys(a.set), ...a.unset];
|
|
const issue = (message: string) => ctx.issues.push({ code: "custom", message, input: a });
|
|
if (names.length === 0) issue("Nothing to change");
|
|
if (names.length > ENV_SET_MAX) issue(`At most ${ENV_SET_MAX} changes at a time`);
|
|
const secret = names.find(isSecretEnvName);
|
|
if (secret) issue(`${secret} is a secret: it can't be changed from the Hub`);
|
|
if (a.unset.some((n) => Object.prototype.hasOwnProperty.call(a.set, n))) issue("A name can't be both set and removed");
|
|
}),
|
|
/** `crosscode export <church> [products] --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}$/), products: z.array(productSchema).min(1).max(4).optional() }),
|
|
/**
|
|
* `crosscode uninstall <church> [products] --json`. With `products` (agent 1.5.0, {@link
|
|
* PRODUCT_UNINSTALL_MIN_AGENT}) only those go and the church keeps its others; without it, or
|
|
* naming every product, the whole church goes.
|
|
*/
|
|
uninstall: z.strictObject({ church: shortNameSchema, products: z.array(productSchema).min(1).max(4).optional() }),
|
|
/** `crosscode purge <church> [products] --json` (deletes what uninstall kept for 30 days: with `products`, only what was kept of those) */
|
|
purge: z.strictObject({ church: shortNameSchema, products: z.array(productSchema).min(1).max(4).optional() }),
|
|
/** The agent updates itself to that tag. */
|
|
"update-agent": z.strictObject({ version: agentTagSchema }),
|
|
/**
|
|
* frps's config (central server) or frpc's (church server), secrets hidden: an {@link frpReadResultSchema}.
|
|
* With `path`, the agent uses (and remembers) that file instead of the one it finds itself.
|
|
*/
|
|
"frp-read": z.strictObject({ path: frpConfigPathSchema.optional() }),
|
|
/**
|
|
* Replaces frps's or frpc's config: secrets put back from the file on the server, checked with
|
|
* `frps verify` / `frpc verify`, a backup kept, then (with `restart`) the service restarted. When
|
|
* it doesn't come back, the old file is put back (`rolled-back`). `path` must be the file the
|
|
* agent uses now (what the last `frp-read` showed).
|
|
*/
|
|
"frp-write": z.strictObject({ path: frpConfigPathSchema, content: z.string().min(1).max(FRP_CONFIG_MAX), restart: z.boolean() }),
|
|
/**
|
|
* Before an install: which of these ports are free here? On the central server: nothing listens
|
|
* on it and frps's allow_ports has it. On a church server: nothing listens on it and frpc's config
|
|
* doesn't use it. The result is a {@link probePortsResultSchema}.
|
|
*/
|
|
"probe-ports": z.strictObject({ ports: z.array(portSchema).min(1).max(50) }),
|
|
/** 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", "frp-read", "frp-write", "probe-ports"];
|
|
|
|
/** 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, "seed-demo": 15, "env-read": 2, "env-set": 20, export: 20,
|
|
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
|
|
"frp-read": 2, "frp-write": 5, "probe-ports": 2,
|
|
};
|
|
|
|
/** 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("seed-demo"),
|
|
jobOf("env-read"), jobOf("env-set"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
|
jobOf("frp-read"), jobOf("frp-write"), jobOf("probe-ports"),
|
|
]);
|
|
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` (frps.ini) or `proxyBindAddr` (frps.toml), null when it isn't set (tunnels then open on every address). */
|
|
proxyBindAddr: z.string().max(100).nullable(),
|
|
/** `allow_ports` as written (`20000-29999`); frps.toml's `allowPorts` is written the same way. */
|
|
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(),
|
|
/** Agent 1.4.0+: the frps (central) or frpc (church) config the agent uses, null when it found none. */
|
|
frpConfigPath: z.string().max(255).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>;
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// Reading an install's .env (the env-read job, contracts 1.12.0)
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
/** One variable in an `env-read` result. `value` is null for a secret (`set` says whether it has one). */
|
|
export const envReadVariableSchema = z.object({
|
|
name: envNameSchema,
|
|
value: z.string().max(4000).nullable(),
|
|
secret: z.boolean(),
|
|
set: z.boolean(),
|
|
/** From the release's env template (null when the template doesn't list it). */
|
|
layer: envLayerSchema.nullable(),
|
|
description: z.string().max(400).nullable(),
|
|
/** Whether the Hub may change it: not secret, not generated on the server. */
|
|
editable: z.boolean(),
|
|
});
|
|
export type EnvReadVariable = z.infer<typeof envReadVariableSchema>;
|
|
|
|
/** The `result` of an `env-read` report: each of the product's .env files, variables in file order. */
|
|
export const envReadResultSchema = z.object({
|
|
product: productSchema,
|
|
files: z.array(z.object({ file: envFileSchema, exists: z.boolean(), variables: z.array(envReadVariableSchema).max(300) })).max(10),
|
|
readAt: dateTimeSchema,
|
|
});
|
|
export type EnvReadResult = z.infer<typeof envReadResultSchema>;
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// frp config and free ports (contracts 1.15.0, agent 1.4.0)
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
/** How the agent found the frp config: set from the Hub, the systemd unit's `-c`, or a usual place. */
|
|
export const FRP_CONFIG_SOURCES = ["hub", "systemd", "usual-place"] as const;
|
|
|
|
/** The `result` of an `frp-read` report (and of an `frp-write` that went through). */
|
|
export const frpReadResultSchema = z.object({
|
|
/** `frps` on the central server, `frpc` on a church server. */
|
|
service: z.enum(["frps", "frpc"]),
|
|
path: z.string().max(255).nullable(),
|
|
source: z.enum(FRP_CONFIG_SOURCES).nullable(),
|
|
found: z.boolean(),
|
|
format: z.enum(["ini", "toml"]).nullable(),
|
|
/** The file with each secret value replaced by {@link FRP_HIDDEN}. */
|
|
content: z.string().max(FRP_CONFIG_MAX).nullable(),
|
|
/** The names of the hidden values (`token`, `auth.token`, `webServer.password` …). */
|
|
hidden: z.array(z.string().max(100)).max(50),
|
|
/** frps only (null on a church server): what the Hub checks. */
|
|
proxyBindAddr: z.string().max(100).nullable(),
|
|
allowPorts: z.string().max(2000).nullable(),
|
|
serviceRunning: z.boolean().nullable(),
|
|
/** Where the agent looked, when it found nothing. */
|
|
looked: z.array(z.string().max(255)).max(20).optional(),
|
|
readAt: dateTimeSchema,
|
|
});
|
|
export type FrpReadResult = z.infer<typeof frpReadResultSchema>;
|
|
|
|
/** The `result` of a `probe-ports` report. */
|
|
export const probePortsResultSchema = z.object({
|
|
ports: z.array(z.object({ port: portSchema, free: z.boolean(), reason: z.string().max(200).nullable() })).max(50),
|
|
configPath: z.string().max(255).nullable(),
|
|
});
|
|
export type ProbePortsResult = z.infer<typeof probePortsResultSchema>;
|
|
|
|
/** 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)];
|
|
}
|
|
|
|
// Values the apps check at startup, so a bad one is refused when it's entered instead of
|
|
// crashing the app after an install's build. Keep in step with VALUE_RULES in
|
|
// scripts/lib/envtpl.cjs (which checks again on the server, for any release).
|
|
const PROXY_NAME = /^(loopback|linklocal|uniquelocal)$/;
|
|
const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
|
|
const isIp = (s: string) => IPV4.test(s) || (s.includes(":") && /^[0-9A-Fa-f:.]+$/.test(s));
|
|
function proxyEntry(s: string): boolean {
|
|
if (PROXY_NAME.test(s)) return true;
|
|
const [ip, bits, extra] = s.split("/");
|
|
if (extra !== undefined || ip === undefined || !isIp(ip)) return false;
|
|
return bits === undefined || /^\d{1,3}$/.test(bits) || IPV4.test(bits);
|
|
}
|
|
const ENV_VALUE_RULES: Record<string, { ok: (v: string) => boolean; hint: string }> = {
|
|
// Events hands this to Express's "trust proxy" (apps/events/backend/src/app.js).
|
|
TRUST_PROXY: {
|
|
ok: (v) => v === "true" || v === "false" || /^\d+$/.test(v) || v.split(",").every((s) => proxyEntry(s.trim())),
|
|
hint: "Use loopback behind frp, a hop count such as 1, true or false (lowercase), or proxy IP addresses/CIDRs separated by commas.",
|
|
},
|
|
};
|
|
|
|
/** Why an app can't start with this value (a sentence for the person who entered it), or null when it can. */
|
|
export function checkEnvValue(name: string, value: string): string | null {
|
|
const rule = ENV_VALUE_RULES[name];
|
|
if (!rule || rule.ok(String(value).trim())) return null;
|
|
return `${name} can't be "${value}". ${rule.hint}`;
|
|
}
|
|
|
|
/** The problems with a layer's values ({ NAME: message }), empty when there are none (the Hub's check on save and before a job). */
|
|
export function invalidValues(values: Record<string, string | undefined>): Record<string, string> {
|
|
const out: Record<string, string> = {};
|
|
for (const [name, value] of Object.entries(values)) {
|
|
if (value === undefined || value === null || String(value) === "") continue;
|
|
const problem = checkEnvValue(name, String(value));
|
|
if (problem) out[name] = problem;
|
|
}
|
|
return out;
|
|
}
|