Compare commits

...
Author SHA1 Message Date
joshuaandClaude Opus 5.5 2fd88b1337 Merge branch 'feat/seed-demo-from-hub'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:53:56 +02:00
joshuaandClaude Opus 5.5 3e46d22bc6 docs: VERSIONS.md and HANDOVER for events@2.4.1, contracts@1.7.0, agent@1.2.0, Hub 2.4.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:43:21 +02:00
joshuaandClaude Opus 5.5 6ac17a6a62 Events 2.4.1: the default logo is the Cross Code logo, not Hope Family Church's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:38:35 +02:00
joshuaandClaude Opus 5.5 f2a5df029a Demo data from the Hub: crosscode demo, the seed-demo job, set-demo fixes
- scripts: `crosscode demo <church> --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 <noreply@anthropic.com>
2026-11-19 10:37:16 +02:00
joshuaandClaude Opus 5.5 126beaad70 docs: VERSIONS.md for accounts@1.0.1, contracts@1.6.0, Hub 2.3.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:26:30 +02:00
joshuaandClaude Opus 5.5 9e315f199c Merge branch 'fix/trust-proxy-checks'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:23:49 +02:00
joshuaandClaude Opus 5.5 fd8f6c28b0 Refuse a TRUST_PROXY the apps can't start with; Accounts reads loopback
A server configuration with TRUST_PROXY=TRUE made an Events install build for
minutes, then fail: Express threw "invalid IP address: TRUE" at startup.

- scripts/lib/envtpl.cjs: VALUE_RULES checked before any .env is written
  (exit 4, naming the value and the fix), for every release.
- Contracts 1.6.0: agent.checkEnvValue / agent.invalidValues, the same rules
  for the Hub.
- Accounts 1.0.1: TRUST_PROXY read as Events reads it; loopback used to
  turn proxy trust off.
- Docs: CHANGELOGs, WHATS-NEW, HANDOVER, AGENT-1.0-PLAN, ROLLOUT-1.0, READMEs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:23:49 +02:00
joshuaandClaude Opus 5.5 db2e544ed6 docs: VERSIONS.md, the latest version of everything and what's deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:23:36 +02:00
joshua ccd1cfff46 Merge branch 'fix/install-keeps-backend-logs' 2026-11-19 09:03:50 +02:00
joshuaandClaude Opus 5.5 7fd699a2fd Release the crosscode script fix: failed installs show their PM2 logs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:03:48 +02:00
joshuaandClaude Opus 5.5 6988b5ce7c Scripts: a failed install shows its PM2 apps' last log lines
Before removing what a failed install made, print each PM2 app's last
30 log lines, so the Hub's job log says why the backend didn't start
instead of only "/health didn't report 2.3.1 within 90s".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:44:38 +02:00
joshua 06222fd94a Merge branch 'fix/agent-stats-during-jobs' 2026-11-18 19:03:20 +02:00
joshuaandClaude Opus 5.5 43189c599a Release agent@1.1.1: stats during jobs, its real version
Stats go every minute on their own timer, also while a job runs (before,
a 30-minute install made the Hub alert that the server was down). The
version constant said 1.0.1 in 1.1.0; a test keeps it equal to
package.json now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:03:19 +02:00
43 changed files with 773 additions and 48 deletions
+49
View File
@@ -2,6 +2,55 @@
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 <church> --profile <small|events|ministry|multicampus>
[--admin-email <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
fail: the backend crashed at startup (`invalid IP address: TRUE`) and the install was removed.
- **Scripts: a value the app can't start with stops the install before the build.**
`lib/envtpl.cjs` checks values against `VALUE_RULES` (so far `TRUST_PROXY`: `loopback`, a hop
count, lowercase `true`/`false`, or proxy IPs/CIDRs) and exits 4 naming the value and the fix,
before any `.env` is written. The rules are in the script, so they apply to every release,
including ones from before them. On deploy, values already in a `.env` aren't checked.
- **Contracts 1.6.0:** `agent.checkEnvValue(name, value)` and `agent.invalidValues(values)`, the
same rules for the Hub (Hub 2.3.3 refuses a bad value when the configuration is saved and before
a job).
- **Accounts 1.0.1:** `TRUST_PROXY=loopback` turned proxy trust off; it's now read as Events reads
it. Details in `apps/accounts/CHANGELOG.md`.
## crosscode script - 2026-11-19 (no tag: servers run `main`)
- **Scripts: a failed install says why its apps didn't start.** Before removing what a failed
install made, `crosscode install` / `crosscode add` print each PM2 app's last 30 log lines. The
logs used to go with the apps, so the Hub only showed "/health didn't report 2.3.1 within 90s
(last answer: none)" and the reason was lost.
## agent@1.1.1 - 2026-11-18
- **Stats keep going while a job runs.** The agent sent stats and polled in one loop, so during
a job (an install or update can take 30 minutes) the Hub heard nothing and alerted, by email,
that the server was down. Stats now go every minute on their own timer, job or not (Hub 2.3.1
also treats a server running a job as busy, for agents not updated yet).
- The agent reports its real version: 1.1.0 still said 1.0.1 (a test now keeps it equal to
package.json).
## accounts@1.0.0, contracts@1.5.0, agent@1.1.0 - 2026-11-18
Phase 3 (docs/ACCOUNTS-1.0-PLAN.md). Released before the VM test and a run on real Postgres (both still to do).
+11
View File
@@ -1,5 +1,16 @@
# Changelog — Accounts
## [1.0.1] - 2026-11-19
### Fixed
- **`TRUST_PROXY=loopback` turned proxy trust off.** Accounts read `TRUST_PROXY` as true/false, so
anything but `true`, including the `loopback` the Hub suggests behind frp, meant off: rate
limiting and the audit log saw every visitor as `127.0.0.1`, and oidc-provider ignored
`X-Forwarded-Proto`. It's now read as Events reads it: `loopback`, a hop count, proxy IP
addresses/CIDRs separated by commas, or `true`/`false` in any case (`true` is one hop, as
before). Unset is still one hop in production.
## [1.0.0] - 2026-11-18
The first release (docs/ACCOUNTS-1.0-PLAN.md), with Hub 2.3.0 and agent 1.1.0. Released before the
+5
View File
@@ -3,6 +3,11 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events'
WHATS-NEW.md; a section shows once its version is tagged).
## 1.0.1
- **Fix:** sign-in limits and the activity log now see each visitor's own address on servers
behind the Cross Code proxy, instead of the proxy's.
## 1.0.0
- **One sign-in for all your church's sites and apps.** People sign in once with their own account
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.0.0",
"version": "1.0.1",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
+1 -1
View File
@@ -24,7 +24,7 @@ import { appVersion } from './lib/version.js';
export function createApp(ctx: Ctx, provider: Provider) {
const app = express();
app.disable('x-powered-by');
if (ctx.config.trustProxy) app.set('trust proxy', 1);
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
+24 -2
View File
@@ -9,8 +9,10 @@ export type Config = {
/** Encrypts secrets at rest and signs cookies. Generated on the server, never sent anywhere. */
secret: string;
production: boolean;
/** Behind nginx/frp: trust X-Forwarded-* (as Events' TRUST_PROXY). */
/** Behind nginx/frp: trust X-Forwarded-* (oidc-provider's `proxy`). */
trustProxy: boolean;
/** Express's "trust proxy" (TRUST_PROXY, read as Events reads it), or false when off. */
trustProxySetting: TrustProxy;
hubUrl: string;
hubLicenceKey: string | null;
hubPublicKey: string | null;
@@ -25,17 +27,37 @@ export type Config = {
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
export type TrustProxy = false | number | string | string[];
/**
* TRUST_PROXY as Express's "trust proxy": `loopback` (behind frp, the default the Hub suggests),
* a hop count, IP addresses/CIDRs separated by commas, `true` (one hop: never "trust everyone") or
* `false`. Unset: one hop in production, off otherwise. Before 1.0.1 anything but `true` meant
* off, so `loopback` turned it off.
*/
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
const raw = (v ?? '').trim();
if (raw === '') return production ? 1 : false;
const lower = raw.toLowerCase();
if (lower === 'true') return 1;
if (lower === 'false') return false;
if (/^\d+$/.test(raw)) return Number(raw) || false;
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
}
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
const publicUrl = String(env.ACCOUNTS_URL || env.PUBLIC_URL || 'http://localhost:3200').replace(/\/+$/, '');
const production = env.NODE_ENV === 'production';
const secret = env.ACCOUNTS_SECRET || '';
const trustProxySetting = trustProxyFrom(env.TRUST_PROXY, production);
if (production && secret.length < 32) throw new Error('ACCOUNTS_SECRET must be set (at least 32 characters) in production.');
return {
publicUrl,
port: Number(env.PORT || 5200),
secret: secret || 'development-only-secret-change-me-0123456789',
production,
trustProxy: bool(env.TRUST_PROXY, production),
trustProxy: trustProxySetting !== false,
trustProxySetting,
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
+23
View File
@@ -10,6 +10,29 @@ import { Secrets } from '../src/lib/crypto.js';
import { stateFor, type LicenceClaims } from '../src/hub/licence.js';
import { normalisePhone } from '../src/accounts/service.js';
import { waNumber } from '../src/lib/messages.js';
import { loadConfig, trustProxyFrom } from '../src/lib/config.js';
describe('TRUST_PROXY', () => {
test('read as Events reads it: loopback behind frp is on, not off', () => {
assert.equal(trustProxyFrom('loopback', true), 'loopback');
assert.deepEqual(trustProxyFrom('loopback, 203.0.113.10', true), ['loopback', '203.0.113.10']);
assert.equal(trustProxyFrom('2', true), 2);
assert.equal(trustProxyFrom('TRUE', true), 1);
assert.equal(trustProxyFrom('true', false), 1);
assert.equal(trustProxyFrom('false', true), false);
assert.equal(trustProxyFrom('0', true), false);
assert.equal(trustProxyFrom(undefined, true), 1);
assert.equal(trustProxyFrom('', false), false);
});
test('oidc-provider trusts the proxy whenever Express does', () => {
const on = loadConfig({ NODE_ENV: 'test', TRUST_PROXY: 'loopback' });
assert.equal(on.trustProxy, true);
assert.equal(on.trustProxySetting, 'loopback');
const off = loadConfig({ NODE_ENV: 'test', TRUST_PROXY: 'false' });
assert.equal(off.trustProxy, false);
});
});
describe('passwords', () => {
test('Argon2id hashes verify, wrong passwords don\'t', async () => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.0.0",
"version": "1.0.1",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
+7 -3
View File
@@ -1,10 +1,12 @@
{
"name": "@crosscode/agent",
"version": "1.1.0",
"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"
}
}
+2
View File
@@ -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];
+23 -7
View File
@@ -214,17 +214,33 @@ export class Agent {
}
}
/** Runs until stopped: polls and stats on their own timers, never at the same time as a job. */
/**
* Runs until stopped. Stats go on their own timer, every `statsSeconds`, also while a job runs:
* an install or update can take 30 minutes, and before 1.1.1 the agent went quiet for all of it,
* so the Hub reported it as down (and emailed) though it was busy. Polls wait for the job.
*/
async start(): Promise<void> {
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
let nextStats = 0;
while (!this.stopped) {
if (Date.now() >= nextStats) {
let sending = false;
const statsTick = async () => {
if (sending || this.stopped) return;
sending = true;
try {
await this.statsOnce();
nextStats = Date.now() + this.deps.config.statsSeconds * 1000;
} finally {
sending = false;
}
const delay = await this.pollOnce();
await new Promise((r) => setTimeout(r, Math.max(5, Math.min(delay, this.deps.config.statsSeconds)) * 1000));
};
void statsTick();
const timer = setInterval(() => void statsTick(), this.deps.config.statsSeconds * 1000);
try {
while (!this.stopped) {
const delay = await this.pollOnce();
if (this.stopped) break;
await new Promise((r) => setTimeout(r, Math.max(5, delay) * 1000));
}
} finally {
clearInterval(timer);
}
}
+1 -1
View File
@@ -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.0.1";
export const AGENT_VERSION = "1.2.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+15
View File
@@ -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"]);
@@ -49,3 +55,12 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "update-agent", args: { version: "agent@1.0.1" } }))).toBeNull();
});
});
describe("the agent's version", () => {
it("is the one in package.json (it's what the Hub shows and compares)", () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pkg = require("../package.json") as { version: string };
// eslint-disable-next-line @typescript-eslint/no-require-imports
expect((require("../src/stats") as { AGENT_VERSION: string }).AGENT_VERSION).toBe(pkg.version);
});
});
+26
View File
@@ -42,6 +42,32 @@ function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>>
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
describe("the agent loop", () => {
it("keeps sending stats while a long job runs, so the Hub doesn't think it's down", async () => {
jest.useFakeTimers();
try {
let finish!: () => void;
const longRun = jest.fn<ReturnType<Run>, Parameters<Run>>(() => new Promise<RunResult>((resolve) => { finish = () => resolve(ok()); }));
const h = fakeHub([job()]);
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run: longRun, now: () => NOW, stats: async () => ({}) as agent.AgentStats });
const running = a.start();
await jest.advanceTimersByTimeAsync(10);
expect(longRun).toHaveBeenCalledTimes(1);
// 20 minutes of a job: a stats post every minute all the way through.
await jest.advanceTimersByTimeAsync(20 * 60 * 1000);
const stats = h.posts.filter((p) => p.path === "/api/agent/v1/stats").length;
expect(stats).toBeGreaterThanOrEqual(20);
expect(reports(h.posts)).toHaveLength(0);
finish();
await jest.advanceTimersByTimeAsync(10);
expect(reports(h.posts)).toHaveLength(1);
a.stop();
await jest.advanceTimersByTimeAsync(60 * 1000);
await running;
} finally {
jest.useRealTimers();
}
});
it("runs a valid job once and reports it", async () => {
const j = job();
const { a, run, posts } = make([j, j]);
+14
View File
@@ -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,
+1 -1
View File
@@ -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`
+6
View File
@@ -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
+1 -1
View File
@@ -84,7 +84,7 @@ Create `backend/.env` from `.env.example`. The only variables you must set are:
| `APP_BASE_URL` | — | Public frontend URL — used in email links (fallback if not set via admin panel) |
| `BACKEND_URL` | — | Public backend URL — used to serve ticket PDFs over WhatsApp |
| `PORT` | — | Port to listen on (default `3000`) |
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false`, or comma-separated trusted proxy IP(s)/CIDR(s). |
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false` (lowercase), `loopback` (behind frp), or comma-separated trusted proxy IP(s)/CIDR(s). Anything else (e.g. `TRUE`) stops the backend starting; the Hub and the crosscode script refuse it. |
| `NODE_ENV` | — | `production` or `development` |
| `WAWP_ACCESS_TOKEN` | — | WAWP fallback token (preferred: set via Admin → Site Settings) |
| `WAWP_INSTANCE_ID` | — | WAWP fallback instance ID (preferred: set via Admin → Site Settings) |
+1 -1
View File
@@ -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": {
+26 -6
View File
@@ -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 <site user> npm run demo:ministry\nor, as root: crosscode demo <church> --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;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "2.4.0",
"version": "2.4.1",
"private": true,
"scripts": {
"dev": "next dev",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -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 = () => {
<img src={logoSrc} alt="Logo" className="h-10 w-auto object-contain rounded-sm" />
) : (
<Image
src={churchLogo}
alt="Church logo"
src={defaultLogo}
alt="Logo"
width={50}
height={50}
className="rounded-sm object-contain"
+1 -1
View File
@@ -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",
+5 -1
View File
@@ -101,6 +101,7 @@ build differs from this plan, see [Changes while building](#changes-while-buildi
| `deploy` | `crosscode deploy <church> [products] [--version …] --json` | emergency only |
| `adopt` / `adopt-undo` | `crosscode adopt …` | no |
| `restart` | `crosscode restart <church> [product]` (PM2 reload) | no |
| `seed-demo` | `crosscode demo <church> --profile <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 <church> --json` (§9) | no |
| `uninstall` | `crosscode uninstall <church> --json` | **yes**, and typing the short name |
| `purge` | `crosscode purge <church>` (deletes the 30-day keep, §9) | no (scheduled at uninstall) |
@@ -188,7 +189,10 @@ monorepo, listing every variable with its layer, whether it's required, and a de
**For Joshua to set per server before the first install:** the database settings and
`TRUST_PROXY`. Behind frp the app sees every connection from frpc on `127.0.0.1`, and the
visitor's address arrives in `X-Forwarded-For` from FastPanel's nginx, so the expected value is
`loopback` (the Hub suggests it).
`loopback` (the Hub suggests it). A value the apps can't start with (e.g. `TRUE`, which crashed
the Events backend after a whole install's build) is refused when the configuration is saved (Hub
2.3.3), before a job is made, and again by the crosscode script before it writes a `.env`
(`checkEnvValue` in `@crosscode/contracts` 1.6.0, `VALUE_RULES` in `scripts/lib/envtpl.cjs`).
## 6. frp and the central server
+10 -2
View File
@@ -8,7 +8,9 @@ are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and th
The docs for every product are here in `docs/`: the roadmap, the Hub protocol
([hub-protocol.md](./hub-protocol.md), with a copy in `events-hub`), this handover, the plans
for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)).
for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). The latest
version of everything, and what's deployed, is in [VERSIONS.md](./VERSIONS.md) (update it with
every release).
## Repos
@@ -78,7 +80,13 @@ rollout.
- **The agent pins the Hub's job key** when it joins. Back up `events-hub/backend/keys/` (licence
and job keys); replacing the job key means every server joins again.
- **A new `.env` variable** goes in three env templates: `apps/<product>/env.template.json`,
`scripts/products/<product>.env.template.json` and the Hub's `envTemplates/<product>.json`.
`scripts/products/<product>.env.template.json` and the Hub's `envTemplates/<product>.json`. If
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 <church> --profile …` on the server). By hand, run `npm run demo:*` as the
site's user (`sudo -u cc-<church> …`): 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
+2 -1
View File
@@ -43,7 +43,8 @@ Follow `events-hub/deployment.md` → "Upgrading to 2.1":
- [ ] Hub → Servers → Add server → **Church**; run the command as root. It installs Node tools,
the agent (`/opt/crosscode/agent`) and the crosscode script (`/opt/crosscode/tools`, from
main), and starts `crosscode-agent`. The agent listens on nothing.
- [ ] On the server's page: its configuration. `TRUST_PROXY=loopback` behind frp; the database:
- [ ] On the server's page: its configuration. `TRUST_PROXY=loopback` behind frp (lowercase;
`TRUE` stops the Events backend starting, and the Hub refuses it from 2.3.3); the database:
`DB_HOST`/`DB_PORT`/`DB_ADMIN_URL` for a separate PostgreSQL, or nothing for the local one.
- [ ] `systemctl status crosscode-agent` is active; the server's stats show on the Hub.
- [ ] The first time the agent changes `frpc.ini` it adds the admin lines and **restarts frpc once**
+74
View File
@@ -0,0 +1,74 @@
# Versions — the latest release of everything
Last updated: 2026-11-19. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
separately below; the two often differ.
## Released
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| 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.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) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
on each run, so merging to `main` and pushing releases it. Its changes are listed in
[CHANGELOG.md](../CHANGELOG.md) under "crosscode script".
### Not tagged yet
| What | Where | Version in package.json |
|------|-------|-------------------------|
| `@crosscode/auth-client` | `packages/auth-client` | 1.0.0 (released with Accounts 1.0.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.1.0 |
| Website | `apps/website` | 0.0.0 (not started, phase 4) |
| App | `apps/app` | 0.0.0 (not started, phase 6) |
These shared packages ship inside the apps that use them, from the same checkout, so they don't
need their own tags until something outside this repo depends on them.
## What each latest release was for
- **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.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):** `crosscode demo <church> --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.
## Deployed / rolled out
What actually runs isn't in git, so this table is kept by hand. Fill in a version and date when
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.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 |
| crosscode.co.za | not recorded | | Handover: `v1.3.0` was merged and tagged but not deployed |
+6 -6
View File
@@ -46,7 +46,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.0.0",
"version": "1.0.1",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -82,7 +82,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.0.0",
"version": "1.0.1",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -108,7 +108,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.1.0",
"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.5.0",
"version": "1.7.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+1
View File
@@ -13,6 +13,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
| Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) |
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
## Using it
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.5.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",
+111
View File
@@ -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": {
@@ -24,6 +24,7 @@
"adopt",
"adopt-undo",
"restart",
"seed-demo",
"export",
"uninstall",
"purge",
+54 -2
View File
@@ -54,6 +54,14 @@ export type AgentMode = z.infer<typeof agentModeSchema>;
// Jobs (crosscode.agent-job/1)
// ---------------------------------------------------------------------------------------------
/** Cross Events' demo data sets (`apps/events/backend/scripts/set-demo.js`). */
export const DEMO_PROFILES = ["small", "events", "ministry", "multicampus"] as const;
export const demoProfileSchema = z.enum(DEMO_PROFILES);
export type DemoProfile = z.infer<typeof demoProfileSchema>;
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
export const SEED_DEMO_MIN_AGENT = "1.2.0";
/** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */
export const jobArgsSchemas = {
/** `crosscode install <church> --products … --frp --json` */
@@ -81,6 +89,12 @@ export const jobArgsSchemas = {
"adopt-undo": z.strictObject({ church: shortNameSchema }),
/** `crosscode restart <church> [product] --json` (PM2 reload) */
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
/**
* `crosscode demo <church> --profile <profile> [--admin-email <email>] --json`: replaces Cross
* Events' data with a demo set (a backup is taken first). The Hub only makes it for installs
* marked as demo sites. `adminEmail`: the account kept (default: the release's own choice).
*/
"seed-demo": z.strictObject({ church: shortNameSchema, profile: demoProfileSchema, adminEmail: z.email().max(254).optional() }),
/** `crosscode export <church> --out <zip> --json`; the agent encrypts the ZIP and uploads it under `exportId`. */
export: z.strictObject({ church: shortNameSchema, exportId: z.string().regex(/^exp_[A-Za-z0-9_-]{8,64}$/) }),
/** `crosscode uninstall <church> --json` */
@@ -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<JobType, number> = {
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<T extends JobType>(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<typeof agentJobSchema>;
@@ -318,3 +332,41 @@ export function missingRequired(template: EnvTemplate, layer: "server" | "defaul
}
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;
}
+27
View File
@@ -154,6 +154,19 @@ describe("exports", () => {
});
});
describe("seed-demo jobs", () => {
const args = (a: Record<string, unknown>) => 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({
@@ -171,4 +184,18 @@ describe("env templates", () => {
expect(agent.missingRequired(template, "server", { TRUST_PROXY: "loopback" })).toEqual(["DB_HOST"]);
expect(agent.missingRequired(template, "defaults", {})).toEqual(["HUB_URL"]);
});
it("refuses a TRUST_PROXY the Events backend can't start with", () => {
for (const ok of ["loopback", "1", "true", "false", "loopback, 203.0.113.10", "10.0.0.0/8", "::1", "fd00::/8", "192.168.1.0/255.255.255.0"]) {
expect(agent.checkEnvValue("TRUST_PROXY", ok)).toBeNull();
}
for (const bad of ["TRUE", "True", "yes", "on", "300.1.1.1", "10.0.0.0/8/1", "loopback,"]) {
expect(agent.checkEnvValue("TRUST_PROXY", bad)).toMatch(/^TRUST_PROXY can't be/);
}
expect(agent.checkEnvValue("DB_HOST", "anything")).toBeNull();
expect(agent.invalidValues({ TRUST_PROXY: "TRUE", DB_HOST: "10.0.0.5", DB_PORT: undefined })).toEqual({
TRUST_PROXY: expect.stringContaining("loopback"),
});
expect(agent.invalidValues({ TRUST_PROXY: "loopback" })).toEqual({});
});
});
+3 -1
View File
@@ -96,6 +96,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
crosscode adopt <church> --undo go back to the old folder (within 14 days)
crosscode restart <church> [events] reload the PM2 processes
crosscode demo <church> --profile <profile> replace Events' data with a demo set
crosscode export <church> --out <file.zip> the church's data and uploads
crosscode uninstall <church> --confirm <church> remove it (a final backup is kept 30 days)
crosscode purge <church> --confirm <church> 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\"." ;;
+43 -3
View File
@@ -12,7 +12,9 @@
// appear in arguments or files other than the .env); server / defaults → the config's layers;
// install → the config's install[product], else the variable's `from` filled with --var values.
// Then --fallback, then the template's `default`. A required variable with no value stops
// everything before any file is written (exit 3, the names on stderr).
// everything before any file is written (exit 3, the names on stderr). So does a value the app
// can't start with (VALUE_RULES, exit 4), e.g. TRUST_PROXY=TRUE, which crashes the Events backend
// only after the long build.
// --check: only says what would be added. Prints names only, never values.
'use strict';
@@ -54,6 +56,33 @@ function keysIn(text) {
return keys;
}
// Values the apps check at startup. The rules live here rather than in the templates so they also
// apply to releases whose templates predate them. Keep in step with checkEnvValue in
// packages/contracts/src/agent.ts. Only for values that aren't secret: the message shows the value.
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 => IPV4.test(s) || (s.includes(':') && /^[0-9A-Fa-f:.]+$/.test(s));
function proxyEntry(s) {
if (PROXY_NAME.test(s)) return true;
const [ip, bits, extra] = s.split('/');
if (extra !== undefined || !isIp(ip)) return false;
return bits === undefined || /^\d{1,3}$/.test(bits) || IPV4.test(bits);
}
const VALUE_RULES = {
// 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 the app can't use this value, or undefined when it can (or there's no rule for it). */
function checkValue(name, value) {
const rule = VALUE_RULES[name];
if (!rule || rule.ok(String(value).trim())) return undefined;
return `${name}=${JSON.stringify(String(value))} won't work: ${rule.hint}`;
}
function fill(from, vars) {
let missing = false;
const value = from.replace(/\{([A-Za-z]+)\}/g, (_, k) => {
@@ -94,6 +123,7 @@ function plan(opts) {
const ctx = { config, vars: opts.vars, fallback: opts.fallback, product: opts.product || template.product };
const files = [];
const missing = [];
const invalid = [];
for (const [rel, variables] of Object.entries(template.files)) {
if (rel.includes('..') || path.isAbsolute(rel)) throw new Error(`Bad file name in the template: ${rel}`);
const file = path.join(opts.dir, rel);
@@ -107,11 +137,17 @@ function plan(opts) {
if (v.required) missing.push(`${v.name} (${v.layer}, ${rel})`);
continue;
}
const problem = checkValue(v.name, value);
if (problem) {
const where = v.layer === 'server' ? "server, from the server's configuration on the Hub" : v.layer;
invalid.push(`${problem} (${where}, ${rel})`);
continue;
}
add.push({ name: v.name, value });
}
files.push({ rel, file, exists, add });
}
return { files, missing };
return { files, missing, invalid: [...new Set(invalid)] };
}
function write({ files }, release) {
@@ -151,6 +187,10 @@ function main() {
console.error(`Required settings with no value: ${result.missing.join(', ')}`);
process.exit(3);
}
if (result.invalid.length) {
console.error(`Settings the app can't start with:\n ${result.invalid.join('\n ')}`);
process.exit(4);
}
for (const f of result.files) {
if (!f.add.length) continue;
const names = f.add.map(a => a.name).join(', ');
@@ -161,4 +201,4 @@ function main() {
if (require.main === module) main();
module.exports = { parseArgs, keysIn, fill, line, plan, write };
module.exports = { parseArgs, keysIn, fill, line, plan, write, checkValue };
+15 -1
View File
@@ -58,12 +58,26 @@ random_secret() { openssl rand -base64 64 | tr -d '/+=\n' | head -c "${1:-48}";
INSTALL_UNDO=""
undo_add() { [ -z "$INSTALL_UNDO" ] || printf '%s\n' "$*" >> "$INSTALL_UNDO"; }
# pm2_last_logs <user> <name…>: each PM2 app's last 30 log lines (output and errors), indented.
pm2_last_logs() {
local user="$1" name
shift
for name in "$@"; do
info "PM2: last log lines of $name"
run_as "$user" / pm2 logs "$name" --lines 30 --nostream --raw </dev/null 2>&1 | tail -n 60 | sed 's/^/ /' || true
done
}
install_undo() {
local kind a b
step "Removing what this install made"
tac "$INSTALL_UNDO" | while read -r kind a b; do
case "$kind" in
pm2) # shellcheck disable=SC2086 # b is a space-separated list of PM2 names
pm2)
# Their logs go with them, so show why they didn't start first (the Hub gets the log).
# shellcheck disable=SC2086 # b is a space-separated list of PM2 names
pm2_last_logs "$a" $b
# shellcheck disable=SC2086
run_as "$a" / pm2 delete $b >/dev/null 2>&1 || true
run_as "$a" / pm2 save --force >/dev/null 2>&1 || true
info "PM2: $b removed" ;;
+50
View File
@@ -6,6 +6,10 @@ CROSSCODE_REMOVED="${CROSSCODE_REMOVED:-$CROSSCODE_SITES/.removed}"
manage_usage() {
cat <<'EOF'
crosscode restart <church> [events] reload the products' PM2 processes
crosscode demo <church> --profile <profile> [--admin-email <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 <church> --out <file.zip> the church's data (crosscode.church-export/1) and uploads
crosscode uninstall <church> --confirm <church>
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
+17
View File
@@ -259,3 +259,20 @@ EOF
[ "$(host_from_url "$(env_value "$TMP/.env" FRONTEND_URL)")" = events.hopefamily.co.za ]
[ "$(host_from_url http://localhost:3000/x)" = localhost ]
}
# ── install undo ────────────────────────────────────────────────────────────────────────────
@test "a failed install shows each PM2 app's last log lines before removing it" {
# shellcheck source=../lib/install.sh
source "$BATS_TEST_DIRNAME/../lib/install.sh"
run_as() { shift 2; case "$2" in logs) printf 'Error: %s crashed\n' "$3" ;; esac; echo "$*" >> "$TMP/pm2"; }
INSTALL_UNDO="$TMP/undo"
undo_add pm2 cc-hope "hope-events-backend hope-events-frontend"
run install_undo
[ "$status" -eq 0 ]
[[ "$output" == *"last log lines of hope-events-backend"* ]]
[[ "$output" == *" Error: hope-events-backend crashed"* ]]
[[ "$output" == *" Error: hope-events-frontend crashed"* ]]
# The logs are read before the apps are deleted.
[ "$(grep -n 'logs hope-events-backend' "$TMP/pm2" | cut -d: -f1)" -lt "$(grep -n '^pm2 delete' "$TMP/pm2" | cut -d: -f1)" ]
}
+83
View File
@@ -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" <<EOF
events_app() { printf '%s/apps/events' "\$1"; }
events_backup() { echo "backup \$2" >> "$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 <church> --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" ]
}
+27
View File
@@ -54,6 +54,33 @@ envtpl() { node "$TPL_JS" --template "$TMP/template.json" --dir "$APP" --product
[ ! -e "$APP/frontend/.env.production" ]
}
@test "a value the app can't start with: nothing is written, the value and the fix are named" {
printf '{ "server": { "TRUST_PROXY": "TRUE" } }\n' > "$TMP/bad.json"
run envtpl --config "$TMP/bad.json" --release events@2.4.0
[ "$status" -eq 4 ]
[[ "$output" == *'TRUST_PROXY="TRUE" won'"'"'t work'* ]]
[[ "$output" == *"loopback behind frp"* ]]
[[ "$output" == *"server's configuration on the Hub"* ]]
[ ! -e "$APP/backend/.env" ]
[ ! -e "$APP/frontend/.env.production" ]
}
@test "TRUST_PROXY: the values Events understands are accepted" {
for v in loopback 1 true false 'loopback, 203.0.113.10' 10.0.0.0/8 '::1'; do
rm -rf "$APP/backend/.env" "$APP/frontend/.env.production"
printf '{ "server": { "TRUST_PROXY": "%s" } }\n' "$v" > "$TMP/ok.json"
run envtpl --config "$TMP/ok.json"
[ "$status" -eq 0 ] || { echo "$v: $output"; false; }
done
}
@test "deploy: a bad value already in a .env is left alone (only new variables are checked)" {
printf 'DATABASE_URL=x\nPORT=1\nFRONTEND_URL=y\nTRUST_PROXY=TRUE\n' > "$APP/backend/.env"
printf '{ "server": { "TRUST_PROXY": "TRUE" } }\n' > "$TMP/bad.json"
run envtpl --config "$TMP/bad.json"
[ "$status" -eq 0 ]
}
@test "--fallback fills a value no layer gives" {
run envtpl --fallback TRUST_PROXY=1
[ "$status" -eq 0 ]