From f2a5df029a0f80b5ca37e7c3c07a65de572340b3 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Thu, 19 Nov 2026 10:37:16 +0200 Subject: [PATCH] Demo data from the Hub: crosscode demo, the seed-demo job, set-demo fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts: `crosscode demo --profile … [--admin-email …]`: backup, set-demo.js as the site's user, reload, wait for /health. - Contracts 1.7.0: the seed-demo job, DEMO_PROFILES, SEED_DEMO_MIN_AGENT. - Agent 1.2.0: seed-demo → crosscode demo. - Events 2.4.1: set-demo.js stops with a clear message when it can't read .env (was "client password must be a string", then a hang); keeps the oldest admin when the default one isn't on the site; --admin-email=. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 +++ apps/agent/package.json | 10 +- apps/agent/src/command.ts | 2 + apps/agent/src/stats.ts | 2 +- apps/agent/tests/command.test.ts | 6 + apps/events/CHANGELOG.md | 12 ++ apps/events/WHATS-NEW.md | 4 + apps/events/backend/package.json | 2 +- apps/events/backend/scripts/set-demo.js | 32 +++++- apps/events/frontend/package.json | 2 +- apps/events/package.json | 2 +- docs/AGENT-1.0-PLAN.md | 1 + package-lock.json | 8 +- packages/contracts/package.json | 2 +- packages/contracts/schemas/agent-job.json | 111 +++++++++++++++++++ packages/contracts/schemas/agent-report.json | 1 + packages/contracts/src/agent.ts | 18 ++- packages/contracts/tests/agent.test.ts | 13 +++ scripts/crosscode | 4 +- scripts/lib/manage.sh | 50 +++++++++ scripts/tests/demo.bats | 83 ++++++++++++++ 21 files changed, 360 insertions(+), 21 deletions(-) create mode 100644 scripts/tests/demo.bats diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b7b7ab..9bfdc85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## events@2.4.1, contracts@1.7.0, agent@1.2.0, crosscode script - 2026-11-19 + +Demo data from the Hub, for installs marked as demo sites (Hub 2.4.0). + +- **Scripts: `crosscode demo --profile + [--admin-email ]`.** Takes a backup, loads the demo set as the site's user (who alone + can read its `.env`), then reloads Events and waits for `/health`. Stops before the data if the + backup fails, and doesn't reload after a failed seed. +- **Contracts 1.7.0:** the `seed-demo` job (`church`, `profile`, optional `adminEmail`; 15 + minutes), `DEMO_PROFILES`, `SEED_DEMO_MIN_AGENT`. +- **Agent 1.2.0:** runs `seed-demo` jobs as `crosscode demo`. Older agents refuse them, so the + Hub checks the agent's version first. +- **Events 2.4.1:** `set-demo.js` says to run as the site's user instead of failing with "client + password must be a string" and hanging; keeps the site's oldest admin when the default isn't + there. Details in `apps/events/CHANGELOG.md`. + ## accounts@1.0.1, contracts@1.6.0, crosscode script - 2026-11-19 A server configuration with `TRUST_PROXY=TRUE` made an Events install build for minutes, then diff --git a/apps/agent/package.json b/apps/agent/package.json index 3bdaaf3..5d33b6a 100644 --- a/apps/agent/package.json +++ b/apps/agent/package.json @@ -1,10 +1,12 @@ { "name": "@crosscode/agent", - "version": "1.1.1", + "version": "1.2.0", "private": true, "description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)", "license": "UNLICENSED", - "bin": { "crosscode-agent": "./dist/cli.js" }, + "bin": { + "crosscode-agent": "./dist/cli.js" + }, "scripts": { "build": "tsup", "typecheck": "tsc -p tsconfig.json --noEmit", @@ -14,5 +16,7 @@ "@crosscode/contracts": "*", "zod": "^4.6.7" }, - "engines": { "node": ">=24" } + "engines": { + "node": ">=24" + } } diff --git a/apps/agent/src/command.ts b/apps/agent/src/command.ts index f8ca2d6..1bf9ab0 100644 --- a/apps/agent/src/command.ts +++ b/apps/agent/src/command.ts @@ -48,6 +48,8 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string } return ["adopt", job.args.church, "--undo"]; case "restart": return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])]; + case "seed-demo": + return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])]; case "export": if (!opts.exportFile) throw new Error("export needs a file to write"); return ["export", job.args.church, "--out", opts.exportFile]; diff --git a/apps/agent/src/stats.ts b/apps/agent/src/stats.ts index 36b8d53..62c138c 100644 --- a/apps/agent/src/stats.ts +++ b/apps/agent/src/stats.ts @@ -12,7 +12,7 @@ import { paths } from "./paths"; * the tools that are there; anything missing is null rather than an error. */ -export const AGENT_VERSION = "1.1.1"; +export const AGENT_VERSION = "1.2.0"; function run(cmd: string, args: string[], timeoutMs = 10_000): Promise { return new Promise((resolve) => { diff --git a/apps/agent/tests/command.test.ts b/apps/agent/tests/command.test.ts index 40f6779..bf7904b 100644 --- a/apps/agent/tests/command.test.ts +++ b/apps/agent/tests/command.test.ts @@ -39,6 +39,12 @@ describe("crosscode arguments for each job", () => { expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]); }); + it("seed-demo: crosscode demo with the profile, and the admin kept when the Hub names one", () => { + expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]); + expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } }))) + .toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]); + }); + it("export writes to the file the agent gives", () => { const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } }); expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]); diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 09c7ab4..97a7526 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project follows [Semantic Versioning](https://semver.org/). +## [2.4.1] - 2026-11-19 + +### Fixed + +- **Demo data on a server** (`scripts/set-demo.js`): run as anyone but the site's user, `.env` + (mode 600) couldn't be read, so `DATABASE_URL` was missing and pg failed with "client password + must be a string", then hung. It now stops at once and says to run it as the site's user (or + `crosscode demo`, which the Hub uses). +- The admin account kept can be named with `--admin-email=` (or `DEMO_ADMIN_EMAIL`, as before). + When none is named and joshua@crosscode.co.za isn't on the site, the oldest admin is kept, so a + site installed from the Hub (with the church's own admin) can be seeded. + ## [2.4.0] - 2026-11-18 Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2, diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index 6230187..6b444e9 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,10 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 2.4.1 + +- Nothing changes for your church: this fixes setting up demonstration sites for Cross Code. + ## 2.4.0 - **Ready for the Church Website and App.** When your church has them, your events can show on diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index 10b890a..939801d 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-backend", - "version": "2.4.0", + "version": "2.4.1", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { diff --git a/apps/events/backend/scripts/set-demo.js b/apps/events/backend/scripts/set-demo.js index 600d6b6..beb1957 100644 --- a/apps/events/backend/scripts/set-demo.js +++ b/apps/events/backend/scripts/set-demo.js @@ -16,8 +16,9 @@ * campus-limited staff, a series across campuses, kids check-in and rosters at two * campuses. * - * Everything is removed first EXCEPT the site settings (AppSetting) and the admin - * account (DEMO_ADMIN_EMAIL, default joshua@crosscode.co.za). Dates are relative to + * Everything is removed first EXCEPT the site settings (AppSetting) and one admin + * account (--admin-email= or DEMO_ADMIN_EMAIL; else joshua@crosscode.co.za, else the oldest admin). + * Dates are relative to * today, so the upcoming events are always in the future whenever this is run. * * No emails or WhatsApp messages are sent. Demo people use @example.com addresses and @@ -40,7 +41,18 @@ const fs = require('fs'); const crypto = require('crypto'); const readline = require('readline'); -require('dotenv').config({ path: path.resolve(__dirname, '../.env') }); +const ENV_FILE = path.resolve(__dirname, '../.env'); +const loaded = require('dotenv').config({ path: ENV_FILE, quiet: true }); + +// Without DATABASE_URL the pg driver fails with "client password must be a string" and hangs. The +// usual reason on a server: .env is readable only by the site's own user (mode 600). +if (!process.env.DATABASE_URL && !process.argv.includes('--list')) { + const denied = loaded.error && loaded.error.code === 'EACCES'; + console.error(denied + ? `Can't read ${ENV_FILE}: it belongs to the site's user. Run this as that user, e.g.\n sudo -u npm run demo:ministry\nor, as root: crosscode demo --profile ministry` + : `DATABASE_URL isn't set (${loaded.error ? `${ENV_FILE}: ${loaded.error.code || loaded.error.message}` : `not in ${ENV_FILE}`}). Nothing was changed.`); + process.exit(1); +} const { hashPassword } = require('../src/config/auth'); const { v4: uuidv4 } = require('uuid'); @@ -49,7 +61,11 @@ const { applyBundles } = require('../src/utils/bundles'); const prisma = createPrismaClient(); -const ADMIN_EMAIL = (process.env.DEMO_ADMIN_EMAIL || 'joshua@crosscode.co.za').trim().toLowerCase(); +// The account kept: --admin-email= or DEMO_ADMIN_EMAIL (must exist), else joshua@crosscode.co.za +// if it's there, else the oldest admin (a site installed from the Hub has its own admin). +const ADMIN_ARG = (process.argv.find(a => a.startsWith('--admin-email=')) || '').slice('--admin-email='.length); +const ADMIN_NAMED = (ADMIN_ARG || process.env.DEMO_ADMIN_EMAIL || '').trim().toLowerCase(); +const ADMIN_EMAIL = ADMIN_NAMED || 'joshua@crosscode.co.za'; const DEMO_PASSWORD = 'Demo@1234'; const SKIP_PROMPT = process.argv.includes('--yes') || process.argv.includes('-y'); const PROFILE_NAME = (process.argv.find(a => a.startsWith('--profile=')) || '--profile=events').split('=')[1].trim().toLowerCase(); @@ -1846,9 +1862,13 @@ async function main() { return; } admin = await prisma.user.findFirst({ where: { email: { equals: ADMIN_EMAIL, mode: 'insensitive' } } }); + if (!admin && !ADMIN_NAMED) { + admin = await prisma.user.findFirst({ where: { role: 'admin' }, orderBy: { createdAt: 'asc' } }); + if (admin) console.log(`Keeping the site's first admin, ${admin.email} (${ADMIN_EMAIL} isn't here).`); + } if (!admin) { - console.error(`Admin account ${ADMIN_EMAIL} was not found — nothing was changed.`); - console.error('Set DEMO_ADMIN_EMAIL to the account you want to keep.'); + console.error(`Admin account ${ADMIN_NAMED || 'to keep'} was not found — nothing was changed.`); + console.error('Name the account to keep with --admin-email= or DEMO_ADMIN_EMAIL (or finish /setup first).'); process.exitCode = 1; return; } diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 009c95c..53d0084 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events-frontend", - "version": "2.4.0", + "version": "2.4.1", "private": true, "scripts": { "dev": "next dev", diff --git a/apps/events/package.json b/apps/events/package.json index 406563c..e9e7254 100644 --- a/apps/events/package.json +++ b/apps/events/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/events", - "version": "2.4.0", + "version": "2.4.1", "main": "index.js", "scripts": { "dev:backend": "cd backend && npm run dev", diff --git a/docs/AGENT-1.0-PLAN.md b/docs/AGENT-1.0-PLAN.md index 9aa758a..830d9a7 100644 --- a/docs/AGENT-1.0-PLAN.md +++ b/docs/AGENT-1.0-PLAN.md @@ -101,6 +101,7 @@ build differs from this plan, see [Changes while building](#changes-while-buildi | `deploy` | `crosscode deploy [products] [--version …] --json` | emergency only | | `adopt` / `adopt-undo` | `crosscode adopt …` | no | | `restart` | `crosscode restart [product]` (PM2 reload) | no | +| `seed-demo` | `crosscode demo --profile [--admin-email …]` (backup, demo data, reload; agent 1.2.0+) | no, but only for installs marked as demo sites in the Hub, and typing the short name | | `export` | `crosscode export --json` (§9) | no | | `uninstall` | `crosscode uninstall --json` | **yes**, and typing the short name | | `purge` | `crosscode purge ` (deletes the 30-day keep, §9) | no (scheduled at uninstall) | diff --git a/package-lock.json b/package-lock.json index 2f469c1..eb19213 100644 --- a/package-lock.json +++ b/package-lock.json @@ -108,7 +108,7 @@ }, "apps/agent": { "name": "@crosscode/agent", - "version": "1.1.1", + "version": "1.2.0", "license": "UNLICENSED", "dependencies": { "@crosscode/contracts": "*", @@ -127,7 +127,7 @@ }, "apps/events/backend": { "name": "@crosscode/events-backend", - "version": "2.4.0", + "version": "2.4.1", "hasInstallScript": true, "dependencies": { "@cj-tech-master/excelts": "^10.2.0", @@ -176,7 +176,7 @@ }, "apps/events/frontend": { "name": "@crosscode/events-frontend", - "version": "2.4.0", + "version": "2.4.1", "dependencies": { "@crosscode/contracts": "*", "@crosscode/seo": "*", @@ -21274,7 +21274,7 @@ }, "packages/contracts": { "name": "@crosscode/contracts", - "version": "1.6.0", + "version": "1.7.0", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 688a039..69f728f 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/contracts", - "version": "1.6.0", + "version": "1.7.0", "description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads", "license": "UNLICENSED", "type": "commonjs", diff --git a/packages/contracts/schemas/agent-job.json b/packages/contracts/schemas/agent-job.json index 24a3d2d..ead9d38 100644 --- a/packages/contracts/schemas/agent-job.json +++ b/packages/contracts/schemas/agent-job.json @@ -743,6 +743,117 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "schema": { + "type": "string", + "const": "crosscode.agent-job/1" + }, + "id": { + "type": "string", + "pattern": "^job_[A-Za-z0-9_-]{8,64}$" + }, + "serverId": { + "type": "string", + "pattern": "^srv_[A-Za-z0-9_-]{8,64}$" + }, + "config": { + "anyOf": [ + { + "type": "object", + "properties": { + "alg": { + "type": "string", + "const": "x25519-hkdf-sha256-aes-256-gcm" + }, + "epk": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{43}$" + }, + "iv": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{16}$" + }, + "ciphertext": { + "type": "string", + "maxLength": 200000, + "pattern": "^[A-Za-z0-9_-]+$" + } + }, + "required": [ + "alg", + "epk", + "iv", + "ciphertext" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "notBefore": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + }, + "signature": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{86}$" + }, + "type": { + "type": "string", + "const": "seed-demo" + }, + "args": { + "type": "object", + "properties": { + "church": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{1,30}$" + }, + "profile": { + "type": "string", + "enum": [ + "small", + "events", + "ministry", + "multicampus" + ] + }, + "adminEmail": { + "type": "string", + "maxLength": 254, + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + } + }, + "required": [ + "church", + "profile" + ], + "additionalProperties": false + } + }, + "required": [ + "schema", + "id", + "serverId", + "notBefore", + "expiresAt", + "signature", + "type", + "args" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/contracts/schemas/agent-report.json b/packages/contracts/schemas/agent-report.json index d4d320d..656e5d8 100644 --- a/packages/contracts/schemas/agent-report.json +++ b/packages/contracts/schemas/agent-report.json @@ -24,6 +24,7 @@ "adopt", "adopt-undo", "restart", + "seed-demo", "export", "uninstall", "purge", diff --git a/packages/contracts/src/agent.ts b/packages/contracts/src/agent.ts index 4fcae97..033781b 100644 --- a/packages/contracts/src/agent.ts +++ b/packages/contracts/src/agent.ts @@ -54,6 +54,14 @@ export type AgentMode = z.infer; // 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; + +/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */ +export const SEED_DEMO_MIN_AGENT = "1.2.0"; + /** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */ export const jobArgsSchemas = { /** `crosscode install --products … --frp --json` */ @@ -81,6 +89,12 @@ export const jobArgsSchemas = { "adopt-undo": z.strictObject({ church: shortNameSchema }), /** `crosscode restart [product] --json` (PM2 reload) */ restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }), + /** + * `crosscode demo --profile [--admin-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 export --out --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 --json` */ @@ -105,7 +119,7 @@ export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", " /** 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 = { - install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, export: 20, + install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, "seed-demo": 15, export: 20, uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3, }; @@ -149,7 +163,7 @@ function jobOf(type: T) { } export const agentJobSchema = z.discriminatedUnion("type", [ - jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), + jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"), jobOf("seed-demo"), jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"), ]); export type AgentJob = z.infer; diff --git a/packages/contracts/tests/agent.test.ts b/packages/contracts/tests/agent.test.ts index b7fb4e2..c64fa41 100644 --- a/packages/contracts/tests/agent.test.ts +++ b/packages/contracts/tests/agent.test.ts @@ -154,6 +154,19 @@ describe("exports", () => { }); }); +describe("seed-demo jobs", () => { + const args = (a: Record) => 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 templates", () => { it("lists the required server and defaults values that are missing", () => { const template = agent.envTemplateSchema.parse({ diff --git a/scripts/crosscode b/scripts/crosscode index 27fb239..858ee85 100755 --- a/scripts/crosscode +++ b/scripts/crosscode @@ -96,6 +96,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r crosscode adopt --events-dir move an existing Cross Events install here crosscode adopt --undo go back to the old folder (within 14 days) crosscode restart [events] reload the PM2 processes + crosscode demo --profile replace Events' data with a demo set crosscode export --out the church's data and uploads crosscode uninstall --confirm remove it (a final backup is kept 30 days) crosscode purge --confirm delete what uninstall kept @@ -112,6 +113,7 @@ case "$command" in install) cmd_install "$@" ;; adopt) cmd_adopt "$@" ;; restart) cmd_restart "$@" ;; + demo) cmd_demo "$@" ;; export) cmd_export "$@" ;; uninstall) cmd_uninstall "$@" ;; purge) cmd_purge "$@" ;; @@ -123,7 +125,7 @@ case "$command" in install) install_usage ;; add) add_usage ;; adopt) adopt_usage ;; - restart|export|uninstall|purge) manage_usage ;; + restart|demo|export|uninstall|purge) manage_usage ;; *) usage ;; esac ;; *) usage; die "Unknown command \"$command\"." ;; diff --git a/scripts/lib/manage.sh b/scripts/lib/manage.sh index 479ccb9..1e5906c 100644 --- a/scripts/lib/manage.sh +++ b/scripts/lib/manage.sh @@ -6,6 +6,10 @@ CROSSCODE_REMOVED="${CROSSCODE_REMOVED:-$CROSSCODE_SITES/.removed}" manage_usage() { cat <<'EOF' crosscode restart [events] reload the products' PM2 processes +crosscode demo --profile [--admin-email ] + replace Cross Events' data with a demo set + (small, events, ministry, multicampus); a backup + is taken first, one admin account is kept crosscode export --out the church's data (crosscode.church-export/1) and uploads crosscode uninstall --confirm final backup and uploads kept in @@ -52,6 +56,52 @@ cmd_restart() { done } +DEMO_PROFILES="small events ministry multicampus" + +# Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's +# user (its .env is readable only by that user). The Hub sends it only for installs marked as demo +# sites. Afterwards Events is reloaded: the demo switches campuses on or off. +cmd_demo() { + local church="" profile="" email="" dir user app + while [ $# -gt 0 ]; do + case "$1" in + --profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;; + --admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;; + -h|--help) manage_usage; return 0 ;; + -*) die "Unknown option $1 (crosscode help demo)." ;; + *) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;; + esac + done + [ -n "$church" ] || die "Name the church." + [[ " $DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $DEMO_PROFILES." + [ -z "$email" ] || [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || die "--admin-email: not an email address." + require_root + load_church "$church" + church_has_product events || die "$church has no Cross Events." + # shellcheck source=/dev/null + source "$CROSSCODE_HOME/products/events.sh" + dir="$(pvar events DIR)" + user="$(pvar events USER)" + app="$(events_app "$dir")" + [ -f "$app/backend/scripts/set-demo.js" ] || die "This release of Events ($(checkout_ref "$dir" events)) has no demo data." + + step "Events: backup first" + events_backup "$dir" "$user" || die "The backup failed, so the demo data wasn't loaded." + + step "Events: demo data ($profile)" + local -a env_args=() + # DEMO_ADMIN_EMAIL rather than --admin-email=: releases before 2.4.1 only read the variable. + [ -z "$email" ] || env_args=("DEMO_ADMIN_EMAIL=$email") + run_as "$user" "$app/backend" env "${env_args[@]+"${env_args[@]}"}" node scripts/set-demo.js "--profile=$profile" --yes || + die "The demo data wasn't loaded (see above). If it got as far as changing anything, the backup from just now has the data from before." + + step "Events: reloading PM2" + events_reload "$dir" "$user" + step "Events: waiting for it to answer" + wait_for_version "$(events_health_url)" "$(events_expected_version "$dir")" 60 || + die "Events didn't answer after the reload (sudo -u $user pm2 logs)." +} + cmd_export() { local church="" out="" p tmp dir user bytes while [ $# -gt 0 ]; do diff --git a/scripts/tests/demo.bats b/scripts/tests/demo.bats new file mode 100644 index 0000000..2430ac0 --- /dev/null +++ b/scripts/tests/demo.bats @@ -0,0 +1,83 @@ +#!/usr/bin/env bats +# crosscode demo (lib/manage.sh): argument checks, then backup → demo data as the site's user → +# reload, in that order, and nothing after a step that fails. + +setup() { + export CROSSCODE_NO_UPDATE=1 + CC="$BATS_TEST_DIRNAME/../crosscode" + TMP="$BATS_TEST_TMPDIR" + CALLS="$TMP/calls" + : > "$CALLS" + # shellcheck source=../lib/common.sh + source "$BATS_TEST_DIRNAME/../lib/common.sh" + # shellcheck source=../lib/manage.sh + source "$BATS_TEST_DIRNAME/../lib/manage.sh" + + # A church with Events, and Events' hooks recording what they'd do. + export CROSSCODE_HOME="$TMP/home" + mkdir -p "$CROSSCODE_HOME/products" "$TMP/sites/hope/events/apps/events/backend/scripts" + touch "$TMP/sites/hope/events/apps/events/backend/scripts/set-demo.js" + cat > "$CROSSCODE_HOME/products/events.sh" <> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; } +events_reload() { echo "reload \$2" >> "$CALLS"; } +events_health_url() { echo http://127.0.0.1:20001/health; } +events_expected_version() { echo 2.4.1; } +EOF + require_root() { :; } + load_church() { [ "$1" = hope ] || die "There's no church $1 here."; } + church_has_product() { [ "$1" = events ]; } + pvar() { case "$2" in DIR) echo "$TMP/sites/hope/events" ;; USER) echo cc-hope ;; esac; } + checkout_ref() { echo events@2.4.1; } + wait_for_version() { echo "wait $2" >> "$CALLS"; } + run_as() { local user="$1" dir="$2"; shift 2; echo "run $user ${dir#"$TMP"/} $*" >> "$CALLS"; [ -z "${FAIL_SEED:-}" ]; } +} + +@test "the profile and admin email are checked before anything else" { + CROSSCODE_HOME= run bash "$CC" demo hope + [ "$status" -eq 1 ] + [[ "$output" == *"--profile: one of small events ministry multicampus"* ]] + CROSSCODE_HOME= run bash "$CC" demo hope --profile everything + [ "$status" -eq 1 ] + CROSSCODE_HOME= run bash "$CC" demo hope --profile small --admin-email 'x; rm -rf /' + [ "$status" -eq 1 ] + [[ "$output" == *"not an email address"* ]] + CROSSCODE_HOME= run bash "$CC" help demo + [[ "$output" == *"crosscode demo --profile"* ]] +} + +@test "backup, then the demo as the site's user (no prompt), then a reload" { + run cmd_demo hope --profile ministry + [ "$status" -eq 0 ] + [ "$(cat "$CALLS")" = "backup cc-hope +run cc-hope sites/hope/events/apps/events/backend env node scripts/set-demo.js --profile=ministry --yes +reload cc-hope +wait 2.4.1" ] +} + +@test "the admin to keep goes in DEMO_ADMIN_EMAIL (older releases only read that)" { + run cmd_demo hope --profile small --admin-email jane@hope.test + [ "$status" -eq 0 ] + grep -qx 'run cc-hope sites/hope/events/apps/events/backend env DEMO_ADMIN_EMAIL=jane@hope.test node scripts/set-demo.js --profile=small --yes' "$CALLS" +} + +@test "a failed backup stops it before the data is touched" { + FAIL_BACKUP=1 run cmd_demo hope --profile small + [ "$status" -eq 1 ] + [[ "$output" == *"The backup failed"* ]] + [ "$(cat "$CALLS")" = "backup cc-hope" ] +} + +@test "a failed demo isn't followed by a reload" { + FAIL_SEED=1 run cmd_demo hope --profile small + [ "$status" -eq 1 ] + ! grep -q reload "$CALLS" +} + +@test "a release without the demo script is refused" { + rm "$TMP/sites/hope/events/apps/events/backend/scripts/set-demo.js" + run cmd_demo hope --profile small + [ "$status" -eq 1 ] + [[ "$output" == *"has no demo data"* ]] + [ ! -s "$CALLS" ] +}