diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b7b7ab..14c339a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ 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. The default logo (before a church uploads one) is the Cross Code logo, not Hope Family + Church's. 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..dd5aae2 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -5,6 +5,20 @@ 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 default logo** (before a church uploads its own) was still Hope Family Church's artwork; it's + now the Cross Code logo (`frontend/src/app/default_logo.png`). +- 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/SETTINGS.md b/apps/events/SETTINGS.md index a1b33cd..0ffde81 100644 --- a/apps/events/SETTINGS.md +++ b/apps/events/SETTINGS.md @@ -26,7 +26,7 @@ in-process settings cache TTL) without a server restart. | `primary_color` | Legacy `accent_color` value if present, else `#4F46E5` (indigo) on the website / `#1e3a5f` (navy) in emails | See [Two different fallbacks](#two-different-fallbacks-for-primary_color) below — this is the one setting with a genuine inconsistency worth knowing about. Drives buttons, links, nav highlights, and the email header/CTA. The Branding tab warns when it is under 4.5:1 against white (too light for white text and links) and offers a darker shade (1.50.0). | | `secondary_color` | `210 40% 96.1%` background / near-black text (light gray "wash", shadcn's stock theme) | The Branding tab's color picker *pre-fills* `#8B5CF6` as a suggested starting point, but that's only a UI default — if you never hit Save, the actual site uses the light-gray fallback, not violet. | | `accent_color` | `210 40% 96.1%` background / near-black text (same light gray as Secondary) | Same story as Secondary — the picker pre-fills `#EC4899` (pink) as a suggestion only. | -| `logo_url` | Bundled logo (`frontend/src/app/church_logo.jpg`) | Shown in the navbar. This is still the original Hope Family Church artwork checked into the repo — swap the file (or upload a real logo via the Branding tab) before deploying for a different organisation. | +| `logo_url` | Bundled Cross Code logo (`frontend/src/app/default_logo.png`) | Shown in the navbar until the church uploads its own (Site settings → Branding, or `/setup`). | | `favicon_url` | `frontend/public/favicon.ico` (the site's original generic favicon) | Shown in the browser tab. | ### Two different fallbacks for `primary_color` diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index 6230187..67b6ba1 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,12 @@ 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 + +- Until you upload your own logo (Site settings → Branding), the site now shows the Cross Code + logo. +- A fix for setting up demonstration sites. + ## 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/frontend/src/app/church_logo.jpg b/apps/events/frontend/src/app/church_logo.jpg deleted file mode 100644 index 5bfb94d..0000000 Binary files a/apps/events/frontend/src/app/church_logo.jpg and /dev/null differ diff --git a/apps/events/frontend/src/app/default_logo.png b/apps/events/frontend/src/app/default_logo.png new file mode 100644 index 0000000..ef4b1da Binary files /dev/null and b/apps/events/frontend/src/app/default_logo.png differ diff --git a/apps/events/frontend/src/components/layout/Navbar.tsx b/apps/events/frontend/src/components/layout/Navbar.tsx index c924a91..d544fee 100644 --- a/apps/events/frontend/src/components/layout/Navbar.tsx +++ b/apps/events/frontend/src/components/layout/Navbar.tsx @@ -6,7 +6,7 @@ import { usePathname } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { useSiteSettings } from "@/contexts/SiteSettingsContext"; import { BottomNav } from "./BottomNav"; -import churchLogo from "@/app/church_logo.jpg"; +import defaultLogo from "@/app/default_logo.png"; import { appName } from "@/lib/siteConfig"; import { resolveToApiOrigin } from "@/lib/api"; import { hardNavigate } from "@/lib/navigation"; @@ -67,8 +67,8 @@ export const Navbar = () => { Logo ) : ( Church logo [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/docs/HANDOVER.md b/docs/HANDOVER.md index a8fdacc..214a8fa 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -84,6 +84,9 @@ rollout. the app refuses some values at startup (as Events does a `TRUST_PROXY` it can't parse), add a rule to both `checkEnvValue` in `packages/contracts/src/agent.ts` (the Hub) and `VALUE_RULES` in `scripts/lib/envtpl.cjs` (the server), so a bad value stops before an install's build. +- **Demo data:** Hub → the install's page → Mark as a demo site → Load demo data (Hub 2.4.0, agent + 1.2.0; `crosscode demo --profile …` on the server). By hand, run `npm run demo:*` as the + site's user (`sudo -u cc- …`): only that user can read the `.env`. - **A new Events install never takes over an existing database**: moving an existing site is `adopt`, not a New install pointed at the old database. - **Prisma in the monorepo:** each app other than Events sets its own generator `output`, so diff --git a/docs/VERSIONS.md b/docs/VERSIONS.md index 3e623e3..85157b6 100644 --- a/docs/VERSIONS.md +++ b/docs/VERSIONS.md @@ -10,11 +10,11 @@ separately below; the two often differ. | What | Repo | Latest | Tag | Released | |------|------|--------|-----|----------| -| Cross Events | `crosscode-platform` (`apps/events`) | **2.4.0** | `events@2.4.0` | 2026-11-18 | +| Cross Events | `crosscode-platform` (`apps/events`) | **2.4.1** | `events@2.4.1` | 2026-11-19 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.0.1** | `accounts@1.0.1` | 2026-11-19 | -| Server agent | `crosscode-platform` (`apps/agent`) | **1.1.1** | `agent@1.1.1` | 2026-11-18 | -| Contracts | `crosscode-platform` (`packages/contracts`) | **1.6.0** | `contracts@1.6.0` | 2026-11-19 | -| Cross Code Hub | `events-hub` | **2.3.3** | `v2.3.3` | 2026-11-19 | +| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 | +| Contracts | `crosscode-platform` (`packages/contracts`) | **1.7.0** | `contracts@1.7.0` | 2026-11-19 | +| Cross Code Hub | `events-hub` | **2.4.0** | `v2.4.0` | 2026-11-19 | | crosscode.co.za | `crosscode-site` | **1.5.0** | `v1.5.0` | 2026-11-18 | | `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) | @@ -37,21 +37,26 @@ need their own tags until something outside this repo depends on them. ## What each latest release was for -- **Events 2.4.0:** protocol v2, Linked products, the event feed, `packages/seo` - ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). 2.3.1 is the version for churches until 2.4.0's +- **Events 2.4.1:** the default logo is the Cross Code logo; the demo script says to run as the + site's user (instead of "client password must be a string") and keeps the site's oldest admin. + 2.4.0: protocol v2, Linked products, the event feed, `packages/seo` + ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). 2.3.1 is the version for churches until 2.4.x's e2e run on Postgres and VM test are done. - **Accounts 1.0.1:** `TRUST_PROXY=loopback` (the value behind frp) now turns proxy trust on; it used to turn it off. 1.0.0 was the church's sign-in (OpenID Connect provider) ([ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). Needs the VM test and a run on real Postgres before a church gets it. -- **Agent 1.1.1:** stats keep going while a job runs; reports its real version. -- **Contracts 1.6.0:** `agent.checkEnvValue` / `invalidValues`, settings the apps can't start with - (1.5.0: the Accounts contracts). -- **Hub 2.3.3:** refuses a server setting the apps can't start with (`TRUST_PROXY=TRUE`) when it's +- **Agent 1.2.0:** runs `seed-demo` jobs (`crosscode demo`). 1.1.1: stats keep going while a job + runs. +- **Contracts 1.7.0:** the `seed-demo` job. 1.6.0: `agent.checkEnvValue` / `invalidValues`, + settings the apps can't start with. +- **Hub 2.4.0:** demo sites: mark an Events install as a demo site and load demo data from its + page (needs agent 1.2.0 on that server). 2.3.3: refuses a server setting the apps can't start with (`TRUST_PROXY=TRUE`) when it's saved and before a job. 2.3.2: installs no longer get stuck "Uninstalling" when the export fails; a failed install's record can be removed (and uninstall is refused for it). - **crosscode.co.za 1.5.0:** lists Accounts. -- **`crosscode` script (2026-11-19):** a value the app can't start with stops an install before the +- **`crosscode` script (2026-11-19):** `crosscode demo --profile …` (backup, demo data, + restart); a value the app can't start with stops an install before the build (`VALUE_RULES` in `lib/envtpl.cjs`); a failed install prints each PM2 app's last log lines before removing it, so the Hub's job log shows why the backend didn't start. @@ -62,7 +67,7 @@ you deploy one. | What | Running | Since | Notes | |------|---------|-------|-------| -| Hub | 2.x (exact version not recorded) | | It runs agent jobs (installs on church-server1, 2026-11-18), so it's past 2.1. **2.3.3 not deployed yet** | +| Hub | 2.x (exact version not recorded) | | It runs agent jobs (installs on church-server1, 2026-11-18), so it's past 2.1. **2.4.0 not deployed yet** (it has a migration) | | Agent on church-server1 | not recorded | | | | Agent on the central server | not recorded | | | | Cross Events (churches) | not recorded | | `hope-events` and `cross-events-demo` heartbeat as 2.1.1 and 2.3.1 | 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" ] +}