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>
700 lines
37 KiB
TypeScript
700 lines
37 KiB
TypeScript
import { z } from "zod";
|
||
import { dateTimeSchema, productSchema } from "./common";
|
||
import type { ACTIVE_MEMBER_BANDS } from "./hub";
|
||
|
||
/**
|
||
* 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 Church Website's demo data sets (1.19.0, `apps/website/backend/src/demo/seeds.ts`): two per
|
||
* template, each its own kind of church, the second on the template's other recommended variants.
|
||
*/
|
||
export const WEBSITE_DEMO_PROFILES = [
|
||
"heritage-parish", "heritage-city",
|
||
"bold-youth", "bold-plant",
|
||
"community-family", "community-town",
|
||
"clean-modern", "clean-campus",
|
||
] as const;
|
||
export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES);
|
||
export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>;
|
||
|
||
// ─── Demo scenarios (1.21.0, APP-1.0-PLAN §12 "Demo scenarios") ──────────────
|
||
|
||
/**
|
||
* A demo scenario loads every product of a demo client with the same church: Accounts' church
|
||
* profile (its own name, logo, icon, colours and details) and people, then Events, the Website and
|
||
* the App, each with that church's data. One per Website demo profile, keyed by it.
|
||
*/
|
||
export const DEMO_SCENARIO_KEYS = WEBSITE_DEMO_PROFILES;
|
||
export const demoScenarioSchema = z.enum(DEMO_SCENARIO_KEYS);
|
||
export type DemoScenarioKey = z.infer<typeof demoScenarioSchema>;
|
||
|
||
/**
|
||
* Cross Events' demo data sets: the four single-product ones (`set-demo.js`) and, from Events
|
||
* 3.8.0, one per scenario, named after it.
|
||
*/
|
||
export const EVENTS_DEMO_PROFILES = [...DEMO_PROFILES, ...DEMO_SCENARIO_KEYS] as const;
|
||
export const eventsDemoProfileSchema = z.enum(EVENTS_DEMO_PROFILES);
|
||
|
||
/**
|
||
* The Church App's demo data sets: one per scenario (1.21.0; 1.20.0's `acacia-hill` is the
|
||
* `community-family` scenario, and no App had shipped with it).
|
||
*/
|
||
export const APP_DEMO_PROFILES = DEMO_SCENARIO_KEYS;
|
||
export const appDemoProfileSchema = z.enum(APP_DEMO_PROFILES);
|
||
export type AppDemoProfile = z.infer<typeof appDemoProfileSchema>;
|
||
|
||
/** Accounts' demo data sets (1.21.0): a scenario's church profile and people. One per scenario. */
|
||
export const ACCOUNTS_DEMO_PROFILES = DEMO_SCENARIO_KEYS;
|
||
|
||
/** The products with demo data (`seed-demo` jobs). 1.20.0 adds `app`, 1.21.0 `accounts`. */
|
||
export const DEMO_PRODUCTS = ["events", "website", "app", "accounts"] as const;
|
||
export const demoProductSchema = z.enum(DEMO_PRODUCTS);
|
||
export type DemoProduct = z.infer<typeof demoProductSchema>;
|
||
|
||
/** Each demo product's profiles. */
|
||
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = {
|
||
events: EVENTS_DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES, app: APP_DEMO_PROFILES, accounts: ACCOUNTS_DEMO_PROFILES,
|
||
};
|
||
|
||
const DEMO_PRODUCT_NAMES: Record<DemoProduct, string> = { events: "Cross Events", website: "Website", app: "App", accounts: "Accounts" };
|
||
|
||
/** The order a scenario loads in: Accounts first (the profile and people the others read). */
|
||
export const DEMO_SCENARIO_ORDER = ["accounts", "events", "website", "app"] as const satisfies readonly DemoProduct[];
|
||
|
||
/** The first release of each product that loads a scenario (`--scenario`). The Hub refuses a scenario for an older install. */
|
||
export const DEMO_SCENARIO_MIN_VERSIONS: Record<DemoProduct, string> = { accounts: "1.9.0", events: "3.8.0", website: "1.8.0", app: "1.0.0" };
|
||
|
||
export interface DemoScenario {
|
||
key: DemoScenarioKey;
|
||
/** The church's name in the demo. */
|
||
church: string;
|
||
/** For the Hub's list. */
|
||
label: string;
|
||
description: string;
|
||
/** The profile each product loads. */
|
||
profiles: { accounts: string; events: string; website: string; app: string };
|
||
/** Campuses in the church profile. */
|
||
campuses: number;
|
||
/** The demo's main language (Afrikaans content and devotionals for `af`). */
|
||
language: "en" | "af";
|
||
/** The App's active-member band its people give it, so the scenarios show the Hub's tiers. */
|
||
appActiveMembers: (typeof ACTIVE_MEMBER_BANDS)[number];
|
||
}
|
||
|
||
const scenario = (key: DemoScenarioKey, s: Omit<DemoScenario, "key" | "profiles">): DemoScenario =>
|
||
({ key, ...s, profiles: { accounts: key, events: key, website: key, app: key } });
|
||
|
||
/** The eight scenarios (Joshua, 2026-11-30). Every church and person in them is fictional. */
|
||
export const DEMO_SCENARIOS: readonly DemoScenario[] = [
|
||
scenario("heritage-parish", {
|
||
church: "St Columba's", label: "Heritage: St Columba's, a parish church",
|
||
description: "A 120-year-old parish church, small and older, one Sunday service. Carols, a harvest festival, a quiet prayer wall and a Lent campaign.",
|
||
campuses: 1, language: "en", appActiveMembers: "0–100",
|
||
}),
|
||
scenario("heritage-city", {
|
||
church: "Grace Cathedral", label: "Heritage: Grace Cathedral, a city-centre church",
|
||
description: "Three Sunday services and lunchtime prayer. A concert series, ticketed Easter services, a prayer wall full in office hours with gaps at night.",
|
||
campuses: 1, language: "en", appActiveMembers: "301–750",
|
||
}),
|
||
scenario("bold-youth", {
|
||
church: "Ignite Church", label: "Bold: Ignite Church, young and music-led",
|
||
description: "A youth conference with paid registration and a worship night, a 21-day prayer campaign before it, testimonies and WhatsApp reminders.",
|
||
campuses: 1, language: "en", appActiveMembers: "751–2 000",
|
||
}),
|
||
scenario("bold-plant", {
|
||
church: "Harbour City", label: "Bold: Harbour City, a new church plant",
|
||
description: "Two years old, meeting in a school hall. Launch Sunday, a newcomers' lunch, a prayer wall still filling up and the admin's setup half done.",
|
||
campuses: 1, language: "en", appActiveMembers: "0–100",
|
||
}),
|
||
scenario("community-family", {
|
||
church: "Acacia Hill", label: "Community: Acacia Hill, a family church",
|
||
description: "The mockup's church (cross-demo2). Kids' club, Alpha, family camp and volunteer rosters, a 21-day campaign, prayer requests waiting for approval.",
|
||
campuses: 1, language: "en", appActiveMembers: "101–300",
|
||
}),
|
||
scenario("community-town", {
|
||
church: "Karoo Gemeenskapskerk", label: "Community: Karoo Gemeenskapskerk, a country-town church",
|
||
description: "Mostly Afrikaans. A bazaar and a prayer breakfast, its own AFR83 devotionals, 30-minute prayer slots.",
|
||
campuses: 1, language: "af", appActiveMembers: "101–300",
|
||
}),
|
||
scenario("clean-modern", {
|
||
church: "Northpoint", label: "Clean: Northpoint, a contemporary church",
|
||
description: "About 600 people. Courses, a groups launch and serve teams, every prayer hour covered twice, announcements by WhatsApp.",
|
||
campuses: 1, language: "en", appActiveMembers: "301–750",
|
||
}),
|
||
scenario("clean-campus", {
|
||
church: "Riverside", label: "Clean: Riverside, three campuses near the university",
|
||
description: "Student welcome week at one campus and a combined worship night, one prayer wall for all three, announcements per campus.",
|
||
campuses: 3, language: "en", appActiveMembers: "2 001–5 000",
|
||
}),
|
||
];
|
||
|
||
export function demoScenario(key: DemoScenarioKey): DemoScenario {
|
||
return DEMO_SCENARIOS.find((s) => s.key === key)!;
|
||
}
|
||
|
||
/** 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 `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */
|
||
export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0";
|
||
|
||
/**
|
||
* The first agent that runs `seed-demo` jobs for the App (`product: "app"`; an older one passes no
|
||
* product to the script, so the Hub mustn't send it one). Agent 1.7.0 ships with App 1.0.0.
|
||
*/
|
||
export const SEED_APP_DEMO_MIN_AGENT = "1.7.0";
|
||
|
||
/** 1.21.0: the first agent that runs `seed-demo` for Accounts and with a `scenario` (passed on as `--scenario`). */
|
||
export const SEED_SCENARIO_MIN_AGENT = "1.7.0";
|
||
|
||
/** The first agent that runs a product's `seed-demo` jobs. */
|
||
export const SEED_DEMO_MIN_AGENT_BY_PRODUCT: Record<DemoProduct, string> = {
|
||
events: SEED_DEMO_MIN_AGENT, website: SEED_WEBSITE_DEMO_MIN_AGENT, app: SEED_APP_DEMO_MIN_AGENT, accounts: SEED_SCENARIO_MIN_AGENT,
|
||
};
|
||
|
||
/** 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> [website|app|accounts] --profile <profile> [--scenario <s>] [--admin-email <email>] --json`: replaces
|
||
* Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo
|
||
* set (a backup is taken first); 1.20.0 adds `product: "app"` (the App's prayer wall, campaign,
|
||
* testimonies, devotionals, announcements and events). The Hub only makes it for installs marked as demo sites.
|
||
* `adminEmail` (Events only): the account kept (default: the release's own choice). No `product`
|
||
* is Events, so older Hubs' jobs mean what they did. 1.21.0: `product: "accounts"` (the
|
||
* scenario's church profile, with its logo and icon, and its people) and `scenario`: one job per
|
||
* product in `DEMO_SCENARIO_ORDER`, each with the scenario's profile for that product.
|
||
*/
|
||
"seed-demo": z.strictObject({
|
||
church: shortNameSchema,
|
||
product: demoProductSchema.optional(),
|
||
profile: z.union([eventsDemoProfileSchema, websiteDemoProfileSchema, appDemoProfileSchema]),
|
||
adminEmail: z.email().max(254).optional(),
|
||
/** 1.21.0: part of loading this scenario (the profile must be the scenario's for the product). */
|
||
scenario: demoScenarioSchema.optional(),
|
||
}).superRefine((a, ctx) => {
|
||
const product = a.product ?? "events";
|
||
if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` });
|
||
if (product !== "events" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: `the ${DEMO_PRODUCT_NAMES[product]}'s demo keeps every admin` });
|
||
if (a.scenario && demoScenario(a.scenario).profiles[product] !== a.profile) {
|
||
ctx.addIssue({ code: "custom", path: ["profile"], message: `the ${a.scenario} scenario loads ${demoScenario(a.scenario).profiles[product]} in ${DEMO_PRODUCT_NAMES[product]}` });
|
||
}
|
||
}),
|
||
/**
|
||
* `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;
|
||
}
|