Compare commits

...
Author SHA1 Message Date
joshua 2eaedb8cec Merge branch 'feat/contracts-1.17' 2026-11-24 17:02:17 +02:00
joshuaandClaude Opus 5.5 45a2edd4cc Accounts 1.7.0 + @crosscode/ui 0.2.0: brand style, the church's fonts and footer, church.update
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:02:16 +02:00
joshuaandClaude Opus 5.5 0e3534f29f contracts 1.17.0: brand style, church.update, the Website's export, licence storage limit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:25:20 +02:00
joshua 9954e66c33 Merge branch 'docs/website-fonts-and-handover' 2026-11-24 15:59:05 +02:00
joshuaandClaude Opus 5.5 9523976044 docs: font pairings confirmed (Website plan decision 15)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:59:03 +02:00
joshuaandClaude Opus 5.5 06eedd0499 docs: HANDOVER up to the 2026-11-23 releases; Website plan targets Hub 2.21.0; font pairings proposed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:55:47 +02:00
joshua 75aeae1ff2 Merge branch 'docs/hub-2.20.0-deployed' 2026-11-23 13:49:36 +02:00
joshuaandClaude Opus 5.5 d0df78abe3 docs: Hub 2.20.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:49:36 +02:00
joshua 029d3f4e89 Merge branch 'docs/hub-2.20.0' 2026-11-23 13:45:48 +02:00
joshuaandClaude Opus 5.5 0b500934cb docs: Hub 2.20.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:45:48 +02:00
joshua 86ddc2e6d9 Merge branch 'docs/hub-2.19.0-deployed' 2026-11-23 13:28:29 +02:00
joshuaandClaude Opus 5.5 5fbfd28014 docs: Hub 2.18.0 and 2.19.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:28:29 +02:00
joshua 703fa7804f Merge branch 'docs/hub-2.19.0' 2026-11-23 13:19:07 +02:00
joshuaandClaude Opus 5.5 9eb4d345c6 docs: Hub 2.19.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:19:07 +02:00
joshua e4730120ab Merge branch 'docs/agent-whats-new' 2026-11-23 13:11:40 +02:00
joshuaandClaude Opus 5.5 ac6800d9de docs: Hub 2.18.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:11:40 +02:00
joshuaandClaude Opus 5.5 fc1e97eba8 Agent: WHATS-NEW.md for every release (1.0.0-1.5.0)
Notes for whoever updates servers, read by the Hub's agent release source (Hub 2.19.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:11:39 +02:00
joshua cd84838e78 Merge branch 'docs/hub-2.17.0-deployed' 2026-11-23 12:43:58 +02:00
joshuaandClaude Opus 5.5 6c03a10a24 docs: Hub 2.16.0 and 2.17.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:43:57 +02:00
joshua fe54d9ab7b Merge branch 'docs/hub-2.17.0' 2026-11-23 12:43:07 +02:00
joshuaandClaude Opus 5.5 0d48f81c02 docs: Hub 2.17.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:43:06 +02:00
joshua c1383d62aa Merge branch 'docs/hub-2.16.0' 2026-11-23 12:35:59 +02:00
joshuaandClaude Opus 5.5 9dc42e7481 docs: Hub 2.16.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:35:57 +02:00
joshua a01465a4bb Merge branch 'docs/hub-2.15.0-deployed' 2026-11-23 11:50:23 +02:00
joshuaandClaude Opus 5.5 e59e7488a3 docs: Hub 2.15.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:50:22 +02:00
joshua 1fe94bf70e Merge branch 'docs/hub-2.15.0' 2026-11-23 11:47:57 +02:00
joshuaandClaude Opus 5.5 970a60d55f docs: Hub 2.15.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:47:56 +02:00
joshua da0a7b5f15 Merge branch 'docs/hub-2.14.0-deployed' 2026-11-23 11:16:35 +02:00
joshuaandClaude Opus 5.5 e5bb98c81f docs: Hub 2.14.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:16:34 +02:00
joshua 9dd599cd80 Merge branch 'docs/hub-2.14.0' 2026-11-23 11:14:39 +02:00
joshuaandClaude Opus 5.5 8dc2c8ad68 docs: Hub 2.14.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:14:38 +02:00
joshua 1bb64b1902 Merge branch 'docs/deployed-site-1.6.1' 2026-11-23 10:46:43 +02:00
joshuaandClaude Opus 5.5 3d28ec6edb docs: crosscode.co.za 1.6.1 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:46:41 +02:00
joshua d7f30d348a Merge branch 'docs/site-1.6.1' 2026-11-23 10:40:43 +02:00
joshuaandClaude Opus 5.5 87069c85dd docs: crosscode.co.za 1.6.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:40:39 +02:00
joshua 1f9f2f4640 Merge branch 'docs/deployed-hub-2.13.0' 2026-11-23 10:22:55 +02:00
joshuaandClaude Opus 5.5 544cd30656 docs: Hub 2.13.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:22:54 +02:00
joshua 55a924afb6 Merge branch 'docs/deployed-uninstall-release' 2026-11-23 10:00:52 +02:00
joshuaandClaude Opus 5.5 e9f1e46781 docs: agent 1.5.0 and Hub 2.12.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:00:51 +02:00
joshua 3e85921a35 Merge branch 'fix/uninstall-one-product' 2026-11-23 09:42:10 +02:00
joshuaandClaude Opus 5.5 8899c97a9c Agent 1.5.0 + contracts 1.16.0: uninstall, export and purge one product of a church
crosscode uninstall/export/purge <church> [product ...]: with products named only those
go and the church keeps the others; naming every product it still has removes the church
(folder and app user), so the last product to go takes the church with it. The report
gives products and remaining. Uninstalling cross-events-demo's Events removed its Accounts
too, which the Hub still showed as live.

Contracts 1.16.0: optional products on export/uninstall/purge, PRODUCT_UNINSTALL_MIN_AGENT.
Agent 1.5.0 passes them to crosscode. The Website plan moves to contracts 1.17.0 / Hub 2.13.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:32 +02:00
joshua e04bfac208 Merge branch 'docs/deployed-frp-release' 2026-11-21 11:13:40 +02:00
joshuaandClaude Opus 5.5 7677f54056 docs: agent 1.4.0 and Hub 2.11.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:13:39 +02:00
joshua ce1c978f21 Merge branch 'feat/frp-config-and-port-probe' 2026-11-21 11:08:15 +02:00
joshuaandClaude Opus 5.5 8542d19be0 Agent 1.4.0 + contracts 1.15.0: frp config anywhere, edited from the Hub; ports probed before installs
- The agent finds frps/frpc's config (Hub path, systemd -c, usual places) and reads INI and TOML.
- New jobs frp-read, frp-write (secrets kept on the server, verify, backup, restart, roll back)
  and probe-ports (which ports are free here), on central and church servers.
- Stats report frpConfigPath; crosscode gets FRPC_INI on church servers.
- Website plan versions move up to contracts 1.16.0 and Hub 2.12.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:07:50 +02:00
joshua 4cc30c1445 Merge branch 'docs/website-plan-confirmed' 2026-11-21 00:16:01 +02:00
joshuaandClaude Opus 5.5 d91d956e78 docs: Website 1.0 plan decisions confirmed; full storage stops uploads
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:16:00 +02:00
joshua 9f07ecf0dd Merge branch 'docs/website-1.0-plan' 2026-11-21 00:13:10 +02:00
joshuaandClaude Opus 5.5 74df4aa7b5 docs: plan the Church Website 1.0.0 (phase 5)
WEBSITE-1.0-PLAN.md: templates with section variants, style settings and custom
pages; one Publish after a clickable preview; Coming soon; contact details only;
messages from YouTube or by link; brand style and footer shared with Events 3.7;
no address moves in 1.0. ROADMAP decisions 40-47, §6, §9, §10, §11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:13:10 +02:00
joshua 72a6283024 Merge branch 'docs/deployed-and-phase-5' 2026-11-21 00:00:56 +02:00
joshuaandClaude Opus 5.5 86711699cf docs: everything up to the 2026-11-20 releases deployed; phase 5 (Website) next
HANDOVER phase table and Next up, VERSIONS deployed table, and the Website/ui
placeholders now say phase 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:00:55 +02:00
joshua d28029e96e Merge branch 'fix/accounts-backups-local-changes' 2026-11-20 15:55:08 +02:00
joshuaandClaude Opus 5.5 e65e26202a crosscode script: Accounts' pre-deploy dumps don't stop a deploy
The dump made before each Accounts deploy (apps/accounts/backend/backups/)
counted as a file added by hand on Accounts below 1.3.0, which has no
.gitignore for it, so the next deploy stopped. Untracked files in that
folder no longer count (CROSSCODE_OWN_DIRS in lib/common.sh).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:55:07 +02:00
joshua ca55142f6f Merge branch 'docs/hub-2.10.0' 2026-11-20 14:44:52 +02:00
joshuaandClaude Opus 5.5 1b94814f67 docs: Hub 2.10.0 (emails, FastPanel ^~ /api/) in HANDOVER, VERSIONS and AGENT-1.0-PLAN §11
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:44:52 +02:00
joshua 0b70a87669 Merge branch 'fix/branding-upload-routing' 2026-11-20 14:28:16 +02:00
joshuaandClaude Opus 5.5 ead07ef932 docs: Events 3.6.1 in CHANGELOG, VERSIONS and HANDOVER (FastPanel sites)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:28:15 +02:00
joshuaandClaude Opus 5.5 d8312f4b33 Events 3.6.1: branding uploads work behind a proxy with extension rules
The logo/favicon upload succeeded, but the check that the site can show it
got a 404: on events-demo every /api/... path ending in a file extension
(.png, .ico, .pdf, .json) went to Next.js instead of the backend.

- next.config.ts: /api/* and /uploads/* that reach the site are passed to
  the backend (beforeFiles rewrites) via the new BACKEND_INTERNAL_URL
  (http://127.0.0.1:<apiPort>, from env.template.json on deploy). The e2e
  E2E_API_PROXY uses the same rewrites.
- nginx written by both installers and shown in DEPLOYMENT.md: /api/ and
  /uploads/ use location ^~ so no regex location can take them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:08:11 +02:00
joshua a9239d429a Merge branch 'feat/signin-notices' 2026-11-20 13:54:04 +02:00
joshuaandClaude Opus 5.5 405b5f1b92 Accounts 1.6.0: a "New sign-in" email (and WhatsApp) after every sign-in
As Cross Events' own sign-in sends: when, the site, rough location and device, with what to do if
it wasn't them. WhatsApp too for a verified number. Admins can turn it off (signin_notices).
Fire-and-forget: never holds up or fails a sign-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:54:03 +02:00
joshuaandClaude Opus 5.5 c8c5db46bc docs: HANDOVER.md Next up for the latest releases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:29:23 +02:00
joshua 031fb11e02 Merge branch 'docs/handover-2026-11-20' 2026-11-20 13:28:31 +02:00
joshuaandClaude Opus 5.5 16d3ffe6ba docs: HANDOVER.md for the 2026-11-20 releases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:28:31 +02:00
joshua eac6564e11 Merge branch 'feat/people-check' 2026-11-20 13:26:51 +02:00
joshuaandClaude Opus 5.5 8f78fcc75c Events 3.6.0, Accounts 1.5.0, contracts 1.14.0: the nightly people check
- Contracts 1.14.0: people.check in crosscode.identity-request/1 (500 subs) and its reply
  (active / deactivated / deleted / unknown, profile for the first two).
- Accounts 1.5.0: answers people.check with profiles only for people the product knows; the reply
  isn't stored.
- Events 3.6.0: accounts-people-check job (04:30): fixes out-of-date copies, handles deleted
  accounts as user.deleted, counts unknown people and stops (changing nothing) when most of a page
  is unknown; skipped with an Accounts older than 1.5.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:26:50 +02:00
joshua cacbb16895 Merge branch 'fix/accounts-link' 2026-11-20 12:56:39 +02:00
joshuaandClaude Opus 5.5 08b58ae310 Events 3.5.0, contracts 1.13.0, agent 1.3.1: demo data keeps the Accounts link; sign-in health for the Hub
- Events: loading demo data emptied ProductLink but kept auth_mode, so a site in Accounts mode had
  no link and nobody could sign in (ACCOUNTS_UNAVAILABLE on events-demo). set-demo.js keeps
  ProductLink and LinkNonce; a site in Accounts mode without a link reconnects at its next
  heartbeat; sign-in failures are kept and sent in the heartbeat (stats.signIn).
- Contracts 1.13.0: stats.signIn in the Cross Events heartbeat.
- Agent 1.3.1: 1.3.0 reported itself as 1.2.0 (AGENT_VERSION not bumped).
- What's New notes for Events 3.4.0 / 3.5.0 and Accounts 1.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:56:37 +02:00
joshua e32a3b6144 Merge branch 'feat/env-and-jobs' 2026-11-20 12:14:04 +02:00
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:02 +02:00
164 changed files with 8912 additions and 407 deletions
+133
View File
@@ -2,6 +2,139 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
additive and optional: products on 1.16.0 keep working. Accounts 1.7.0 ships with them because it
answers the new `church.update` request. Details of Accounts in `apps/accounts/CHANGELOG.md`.
- **Brand style** (`./style`): the 8 font pairings confirmed on 2026-11-24 (`FONT_PAIRINGS`:
`classic`, `scholarly`, `editorial`, `impact`, `contemporary`, `friendly`, `warm`, `modern`, each
with its heading and body font), the corner styles (`CORNERS`, `DEFAULT_CORNERS` = `soft`), the
Website's templates (`WEBSITE_TEMPLATES`) and the three pairings each recommends
(`TEMPLATE_FONT_PAIRINGS`, default first). The ids are stored in profiles and never change.
- **`crosscode.church/1`:** optional `branding.style` (`fontPairing`, `corners`, each nullable). An
id a product doesn't know yet reads as null, so a newer Accounts never breaks an older product.
- **`crosscode.church-export/1`:** an optional `website` part (template, first publish, style
settings, pages with their sections, messages, simple events, the publish history's notes and
the media library's alt text). New sample `church-export-website.json`.
- **`church.update`** (identity request, product → Accounts, signed with the link's secret): the
Website's admin changes shared profile facts (plan decision 10). The product checks the person's
role and sends them as `actor`; only the fields given change (`branding` field by field); live at
once, then `church.changed`. Optional `ifUpdatedAt` refuses with the new error code
`PROFILE_CHANGED` when someone saved in between. Reply: the profile (`churchUpdateReplySchema`).
Accounts 1.7.0 takes it from the Website only.
- **Licence:** optional `limits.storageBytes`, the Website's storage limit including add-ons (plan
decision 12). New sample `hub-licence-payload-website.json`.
- **Accounts 1.7.0:** the brand style in Admin → Church profile, the church's fonts, corners and
shared footer on its pages, and `church.update` from the Website. Update Accounts before (or with)
anything that sends `church.update`; nothing does until the Website.
- **`@crosscode/ui` 0.2.0:** `fonts.css` (the 8 pairings' fonts, Latin and Latin Extended, from the
pinned `@fontsource-variable` packages, with Capsize size-matched fallbacks on Arial or Georgia;
generated by `scripts/fonts.mjs`, checked by `npm test`, at most 160 KB per pairing for an
English page), `brandAttributes`, `ChurchFooter`, `productLinks`; the components' corners follow
`--cc-radius` and headings the pairing's heading font. Apps without a pairing look as before.
- `package-lock.json` catches up with the agent's and contracts' versions.
## agent@1.5.0 + contracts@1.16.0 + crosscode script - 2026-11-23
- **Fix: uninstalling one product removed the whole church.** `crosscode uninstall <church>` only
knew whole churches, while the Hub uninstalls per product: uninstalling cross-events-demo's
Events also removed its Accounts, which the Hub still showed as live, and its own uninstall
failed later ("No church cross-events-demo on this server").
- **`crosscode uninstall|export|purge <church> [product …]`.** With products named, only those
are backed up, kept (`.removed/<church>-<date>/<product>`) and removed; the church keeps the
others in church.env. Naming every product it still has removes the church (folder and app
user), so the last product to go always takes the church with it. The report gives `products`
and `remaining`. `purge` with products deletes only what was kept of those, also while the
church still has others. Without products, as before.
- **Agent 1.5.0** passes `products` through. **Contracts 1.16.0:** optional `products` on the
`export`, `uninstall` and `purge` job arguments, and `PRODUCT_UNINSTALL_MIN_AGENT` (an older
agent refuses the key). Hub 2.12.0 uses them.
- The Church Website plan's versions move up one again: contracts 1.17.0, Hub 2.13.0.
## agent@1.4.0 + contracts@1.15.0 - 2026-11-21
- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes
`/etc/frp/frps.ini`: it uses the path set on the Hub, else the `-c` in the frps/frpc systemd
unit, else the usual places (`/etc/frp`, `/usr/local/frp`, `/opt/frp` …), and reads TOML
(`proxyBindAddr`, `allowPorts = [{ start, end }]`) as well as INI. The central server's check
after an install failed with "No frps.ini at /etc/frp/frps.ini" on a server that keeps it
elsewhere. Stats say which file it uses (`frpConfigPath`). `crosscode` gets `FRPC_INI` for it
on church servers.
- **New jobs** (both modes): `frp-read` (the config, secrets hidden), `frp-write` (secrets put
back, `frp* verify`, backup, restart, the old file back if frp doesn't start) and
`probe-ports` (which of these ports are free here). Contracts 1.15.0: the job arguments,
`frpReadResultSchema`, `probePortsResultSchema`, `FRP_JOBS_MIN_AGENT`, `FRP_HIDDEN`,
`agentStats.frpConfigPath`. The Hub needs agent 1.4.0 on a server for these (Hub 2.11.0).
- The Church Website plan's versions move up one: contracts 1.16.0, Hub 2.12.0.
## crosscode script - 2026-11-20 (no tag: servers run `main`)
- **Fix:** the database dump made before each Accounts deploy (`apps/accounts/backend/backups/`)
counted as a file added by hand on Accounts below 1.3.0 (no `.gitignore` for it yet), so the
next deploy stopped with "changed or added by hand". Untracked files in that folder no longer
count (`CROSSCODE_OWN_DIRS` in `lib/common.sh`).
## events@3.6.1 - 2026-11-20
- **Events 3.6.1 (fix):** uploading a logo or favicon failed with "uploaded, but the site can't
show it yet" behind a proxy with a file-extension rule (FastPanel's static-file handling sent
`/api/uploads/…png` to the frontend). The site now passes `/api/*` and `/uploads/*` that reach
it on to the backend (new `BACKEND_INTERNAL_URL`, added on deploy).
- **crosscode script:** the nginx site it writes uses `location ^~ /api/` and `^~ /uploads/`.
## accounts@1.6.0 - 2026-11-20
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp for a verified number) after every
sign-in, as Cross Events' own sign-in did; Sign-in settings → `signin_notices` turns it off.
## events@3.6.0, accounts@1.5.0, contracts@1.14.0 - 2026-11-20
A nightly check that each site's copies of people match their church accounts, for changes that
never arrived.
- **Contracts 1.14.0:** `people.check` in `crosscode.identity-request/1` (`PEOPLE_CHECK_MAX` 500)
and `peopleCheckReplySchema` (each sub `active` / `deactivated` / `deleted` / `unknown`, with the
profile for the first two). Samples and JSON Schema `people-check-reply`.
- **Accounts 1.5.0:** answers it, only with profiles of people the product knows.
- **Events 3.6.0:** the `accounts-people-check` job (04:30): fixes out-of-date copies, handles
deleted accounts as `user.deleted`, and stops if most people are unknown (wrong Accounts?).
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
wasn't bumped with `package.json`), so the Hub refused `.env` jobs on it. Use 1.3.1.
Loading demo data left a site that signs in through Accounts with no Accounts link, so nobody could
sign in (`ACCOUNTS_UNAVAILABLE`, found on events-demo). The Hub (2.9.0) now sees it.
- **Contracts 1.13.0:** `stats.signIn` in the Cross Events heartbeat (mode, the linked Accounts,
the last sign-in failure; optional).
- **Events 3.5.0:** `set-demo.js` keeps `ProductLink` and `LinkNonce`; a site in Accounts mode
without a link reconnects at its next heartbeat even after an earlier auto-connect; sign-in
failures (start, finish, Accounts unreachable) are kept and sent to the Hub; What's New notes for
3.4.0 (and Accounts 1.4.0) that were missing.
## events@3.4.0, accounts@1.4.0, contracts@1.12.0, agent@1.3.0, crosscode script - 2026-11-20
Background jobs are switched on and off (and rescheduled) from each site's admin, over the .env;
Accounts' emails look like Cross Events'; the Hub shows and changes an install's .env (Hub 2.8.0).
- **Contracts 1.12.0:** `env-read` and `env-set` agent jobs, `envReadResultSchema`,
`isSecretEnvName` / `SECRET_ENV_NAME`, `ENV_JOBS_MIN_AGENT` (1.3.0). `env-set` refuses secrets,
newlines, files other than `backend/.env` / `frontend/.env.production`, and empty changes.
- **crosscode script:** `crosscode env <church> <product>` prints the product's .env values
(secrets only as set or not); with `--set NAME=value`, `--unset NAME` and `--restart` it changes
one file (a copy is kept, the last 5), rebuilds the frontend when its file changed, reloads, and
waits for `/health`; if that fails the file is put back (and rebuilt). Secrets and generated
values are refused (`lib/envedit.cjs`). Tests: `scripts/tests/envedit.bats`.
- **Agent 1.3.0:** runs `env-read` and `env-set` as `crosscode env`.
- **Events 3.4.0:** Settings → Background jobs switches each job on or off and changes its
schedule; the choice is kept in the database, wins over the .env and applies straight away.
- **Accounts 1.4.0:** Admin → Background jobs (the same as Events'); every email is styled as
Cross Events' (church colour and logo, a button, contact details), with the same plain text.
## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20
Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads.
+73
View File
@@ -1,5 +1,78 @@
# Changelog — Accounts
## [1.7.0] - 2026-11-24
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
### Added
- **Brand style** in the church profile (`branding.style`: font pairing and corners, contracts
1.17.0). Admin → Church profile → **Brand style** shows each of the 8 pairings in its own fonts,
and the three corner styles. Served in `GET /api/church/v1` and `/api/v2/branding`.
- **The church's fonts and corners on Accounts' pages**: `@crosscode/ui/fonts.css` (self-hosted, no
font requests to anyone else) and `brandAttributes` on `<html>`. Without a pairing the pages
keep the device fonts, so nothing changes until an admin picks one.
- **The shared footer** (`ChurchFooter` from `@crosscode/ui`) on the public pages (sign in, forgot
and reset password, signed out, confirm email): service times, address, contact, social links,
links to the church's other sites and the privacy notice, from the church profile.
- **`church.update`** (contracts 1.17.0): the church's Website changes shared profile facts for its
admins (WEBSITE-1.0-PLAN decision 10). Only from a product linked as `website`
(`WRONG_PRODUCT`), only for an `actor` who signs in through it (`NOT_ALLOWED`), and refused
with `PROFILE_CHANGED` (409) when `ifUpdatedAt` is out of date. Live at once; linked products get
`church.changed`; audited as `church_profile_changed_by_product` with the fields changed.
### Changed
- Saving the profile merges `branding` field by field (`mergeProfile`), so a form or product that
sends only part of it (the colours without the style, or only the style) never drops the rest.
## [1.6.0] - 2026-11-20
### Added
- **"New sign-in" notices**, as Cross Events' own sign-in sends (`src/accounts/signInNotice.ts`):
after each completed sign-in (the interaction reaching done, so not the silent ones a second
product gets from an existing session), an email with when, the site, rough location and device
(`newSignInEmail` in `src/lib/emails.ts`), and a WhatsApp message when the person has a verified
number and WhatsApp is set up. Location from ip-api.com in production only, never for private
addresses. Fire-and-forget: never holds up or fails a sign-in. Admins can turn it off:
`signin_notices` (Sign-in settings, on by default). In Accounts mode Cross Events no longer sends
its own, so before this nobody was told.
## [1.5.0] - 2026-11-20
Needs contracts 1.14.0.
### Added
- `people.check` (contracts 1.14.0): for up to 500 subs, the current profile of each person the
product knows (`active` / `deactivated`), `deleted` for a deleted account, `unknown` for anyone
else (no profile). Audited once per request (`people_checked_by_product`, counts only); the reply
isn't stored for retries, since it holds profiles. Cross Events 3.6.0 asks nightly.
## [1.4.0] - 2026-11-20
Works with every Cross Events 3.x and contracts 1.11.0 or later.
### Added
- **Admin → Background jobs**, as Cross Events': each job's schedule, next run and last runs,
"Run now", and a switch and schedule per job. The choice is saved in the database
(`job_overrides`), wins over the .env and applies straight away (other processes within 30 s).
New optional .env flags per job, as Events: `EXPORTS_JOB_ENABLED`, `DELETIONS_JOB_ENABLED`,
`BACKUP_ENABLED`, `HUB_HEARTBEAT_ENABLED`, and `JOB_SCHEDULE_<NAME>`. API: `GET /api/v2/admin/jobs`,
`PUT /api/v2/admin/jobs/:name` `{ enabled, cron }`, `POST /api/v2/admin/jobs/:name/run`.
On timers (when the queue can't start) jobs now follow their cron schedule too.
### Changed
- **Every email is styled as Cross Events'** (`src/lib/emails.ts`): a header in the church's
colour with its logo or name, a button for the link (written out underneath), callouts for
warnings, and the church's contact details in the footer. Sign-in codes, password reset, "your
account at …", confirm a new email address, "your email address changed", "your data is ready"
and the test emails. The plain text is sent too and hasn't changed. Everything put in the HTML is
escaped, and only http(s) links are used.
## [1.3.0] - 2026-11-20
Needs contracts 1.11.0 (`people.removeDemo`). Works with every Cross Events 3.x.
+33
View File
@@ -3,6 +3,39 @@
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.7.0
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
pairings, each shown in its own fonts, and sharp, soft or round corners. Your sign-in pages use
them now, and your new Church Website and Cross Events' public pages will too, so all your sites
look like one church. Until you pick, nothing changes.
- **A footer with your church's details** under the sign-in pages: service times, address, contact
details and links to your church's other sites, from the church profile.
- Getting ready for the **Church Website**: its admins will be able to change your service times,
logo and contact details from the website, and they'll change everywhere at once.
## 1.6.0
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
where, on what device and to which site, with what to do if it wasn't them, as Cross Events
does for its own sign-in. People with a confirmed WhatsApp number get it on WhatsApp too.
Admins can turn this off under Sign-in settings.
## 1.5.0
- Your church's sites can now check every night that the details they keep for each person match
their church account (Cross Events 3.6.0 does), so a change that didn't reach a site is fixed the
next morning.
## 1.4.0
- **Better-looking emails.** Sign-in codes, password links, "your account is ready" and the other
emails from your church account now look like Cross Events' emails: your church's colour and logo
at the top, a clear button, and your church's contact details at the bottom.
- Admins: **Admin → Background jobs** shows what Accounts does on a schedule (backups, privacy
requests, tidying up), when it last ran, and lets you run a job now, switch it off or change when
it runs.
## 1.3.0
- Your account and the admin pages have a new look, like Cross Events: a menu down the side, and
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.3.0",
"version": "1.7.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
@@ -22,6 +22,7 @@
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
@@ -12,6 +12,7 @@ import { loginEvent } from '../lib/audit.js';
import { queueCall } from '../links/deliveries.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { SendError } from '../lib/messages.js';
import { codeEmail } from '../lib/emails.js';
export const MAX_FAILED_SIGN_INS = 10;
export const LOCK_MINUTES = 15;
@@ -122,7 +123,7 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
}
}
try {
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
await ctx.messenger.email({ to: a.email, ...(await codeEmail(ctx, { name: a.name, code, text, purpose, minutes: CODE_MINUTES })) });
} catch (e) {
console.error('[codes] could not send a code:', (e as Error).message);
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
@@ -0,0 +1,58 @@
/**
* "New sign-in" notices (1.6.0), as Cross Events sends for its own sign-in: after each completed
* sign-in, an email to the person, and a WhatsApp message too when they have a verified number and
* WhatsApp is set up. Admins can turn them off (Sign-in settings, `signin_notices`). Never holds up
* or fails the sign-in.
*
* The rough location comes from the IP (ip-api.com, as Cross Events), in production only, and never
* for private addresses.
*/
import type { Ctx } from '../context.js';
import { newSignInEmail } from '../lib/emails.js';
import { productName } from '../oidc/clients.js';
const PRIVATE_IP = /^(::1$|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fc|fd|fe80|::ffff:(127|10|192\.168)\.)/i;
/** "Chrome on Windows" from a user agent; the raw string when it can't tell. */
export function describeDevice(ua: string | null | undefined): string {
const s = String(ua || '');
if (!s) return 'Unknown device';
const browser = /Edg\//.test(s) ? 'Edge' : /OPR\/|Opera/.test(s) ? 'Opera' : /Firefox\//.test(s) ? 'Firefox'
: /SamsungBrowser\//.test(s) ? 'Samsung Internet' : /Chrome\//.test(s) ? 'Chrome' : /Safari\//.test(s) ? 'Safari' : null;
const os = /iPhone|iPad|iPod/.test(s) ? 'iPhone or iPad' : /Android/.test(s) ? 'Android' : /Windows/.test(s) ? 'Windows'
: /Mac OS X|Macintosh/.test(s) ? 'a Mac' : /CrOS/.test(s) ? 'a Chromebook' : /Linux/.test(s) ? 'Linux' : null;
if (browser && os) return `${browser} on ${os}`;
return browser || os || s.slice(0, 120);
}
async function roughLocation(ctx: Ctx, ip: string | null): Promise<string> {
if (!ip || PRIVATE_IP.test(ip) || !ctx.config.production) return 'Unknown';
try {
const res = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip.replace(/^::ffff:/, ''))}?fields=status,city,regionName,country`, { signal: AbortSignal.timeout(3000) });
const geo = (await res.json()) as { status?: string; city?: string; regionName?: string; country?: string };
const parts = geo.status === 'success' ? [geo.city, geo.regionName, geo.country].filter(Boolean) : [];
return parts.length ? parts.join(', ') : 'Unknown';
} catch {
return 'Unknown';
}
}
export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: string | null; userAgent: string | null; clientId: string | null }): Promise<'sent' | 'off' | 'failed'> {
try {
if (!(await ctx.settings.bool('signin_notices', true))) return 'off';
const a = await ctx.db.account.findUnique({ where: { id: o.accountId } });
if (!a || a.status !== 'active') return 'off';
const link = o.clientId ? await ctx.db.productLink.findUnique({ where: { installId: o.clientId } }) : null;
const site = link ? productName(link.product) : o.clientId === 'accounts-self' ? 'Your account page' : null;
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
}
return 'sent';
} catch (e) {
console.warn('[sign-in notice] not sent:', (e as Error).message);
return 'failed';
}
}
+33 -1
View File
@@ -22,6 +22,8 @@ import { builtInNotice, currentNotice, publish } from '../privacy/notice.js';
import { licenceStatus } from '../hub/licence.js';
import { connect as connectHub } from '../hub/client.js';
import { productName } from '../oidc/clients.js';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
import { testEmail } from '../lib/emails.js';
const PAGE = 50;
@@ -200,7 +202,7 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
try {
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
await ctx.messenger.email({ to: a.email, ...(await testEmail(ctx)) });
} catch (e) {
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
}
@@ -299,6 +301,36 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
}
});
// ─── Background jobs (1.4.0, as Cross Events) ───────────────────────────────
const jobError = (e: unknown): never => {
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
throw e;
};
r.get('/jobs', handle(async (req, res) => {
await admin(req, res);
return jobStatus(ctx);
}));
// Switch a job on or off, or change its schedule: wins over the .env; null goes back to it.
r.put('/jobs/:name', handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const change = { enabled: req.body?.enabled, cron: req.body?.cron };
const override = await setOverride(ctx, name, change).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: change, ip: clientIp(req) });
return { name, override };
}));
r.post('/jobs/:name/run', limit(20, 60), handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_run_manual', targetType: 'job', targetId: name, metadata: { queued: out.queued }, ip: clientIp(req) });
return out;
}));
// ─── Licence, audit ────────────────────────────────────────────────────────
r.get('/licence', handle(async (req, res) => {
+31 -3
View File
@@ -69,10 +69,37 @@ export class ProfileError extends Error {
}
}
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
/** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */
export class ProfileChangedError extends Error {
constructor(public updatedAt: string) {
super('The church profile was changed by someone else since you opened it.');
}
}
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
/**
* The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form
* that doesn't know `branding.style` (or sends only the style) never drops the rest.
*/
export function mergeProfile(base: Record<string, unknown>, input: unknown): Record<string, unknown> {
if (!isObject(input)) return { ...base };
const next: Record<string, unknown> = { ...base, ...input };
if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding };
return next;
}
/**
* Saves changes (merged onto what's there) from an admin here or a product (`church.update`),
* and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since.
*/
export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise<Church> {
const current = await storedProfile(ctx);
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
if (opts.ifUpdatedAt) {
const now = current.updatedAt ?? new Date(0).toISOString();
if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now);
}
const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input);
const check = profileInputSchema.safeParse(next);
if (!check.success) {
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
@@ -92,6 +119,7 @@ export async function branding(ctx: Ctx) {
shortName: c.shortName,
logoUrl: c.branding.logoUrl,
colours: c.branding.colours,
style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null },
signupEnabled: await ctx.settings.bool('signup_enabled', true),
};
}
@@ -8,7 +8,9 @@ import type Provider from 'oidc-provider';
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { clientIp, loginEvent } from '../lib/audit.js';
import { sendSignInNotice } from '../accounts/signInNotice.js';
import { resetPasswordEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { normaliseEmail } from '../accounts/service.js';
@@ -43,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const clientId = String(details.params.client_id ?? '') || null;
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
await signedInThrough(ctx, clientId, pending.accountId);
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
return { stage: 'done', redirectTo, ...extra };
}
@@ -97,11 +101,7 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const token = randomToken();
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
await ctx.messenger.email({
to: a.email,
subject: 'Reset your password',
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
});
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
}
return { sent: true };
}));
+268 -24
View File
@@ -1,7 +1,13 @@
/**
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
*
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
* one now, and switches one on or off or changes its schedule. That choice is kept in the
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
*/
import { CronExpressionParser } from 'cron-parser';
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { runBackupJob } from './backups/backups.js';
@@ -12,17 +18,17 @@ import { deleteExpired } from './oidc/adapter.js';
import { runDeletionJob } from './privacy/deletion.js';
import { runExportsJob } from './privacy/export.js';
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
{ name: 'backup', cron: '0 2 * * *', everyMs: 24 * 3600e3, run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
{
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
run: async (ctx) => {
const now = ctx.now();
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
@@ -37,23 +43,261 @@ export const JOBS: Job[] = [
},
];
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) return async () => {};
const tz = ctx.config.timezone;
const SCHEMA = 'pgboss_accounts';
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30_000;
export type Override = { enabled?: boolean; cron?: string };
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
type State = {
mode: 'queue' | 'timers' | 'off';
boss: PgBoss | null;
timers: Map<string, NodeJS.Timeout>;
history: Map<string, Run[]>;
overrides: Record<string, Override>;
overridesAt: number;
env: NodeJS.ProcessEnv;
};
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
/** Tests: a different environment for the env flags and schedules. */
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
state.env = env;
}
const flag = (name: string | null) => {
if (!name) return true;
const v = state.env[name];
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
};
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
await boss.schedule(job.name, job.cron, undefined, { tz });
await boss.work(job.name, async () => job.run(ctx));
}
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
return async () => { await boss.stop({ graceful: true }); };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
return async () => { timers.forEach(clearInterval); };
CronExpressionParser.parse(cron, { tz });
return true;
} catch {
return false;
}
}
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
try {
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
state.overridesAt = Date.now();
} catch (e) {
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
}
return state.overrides;
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
export const envEnabled = (job: Job) => flag(job.env);
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
export function isEnabled(ctx: Ctx, job: Job): boolean {
if (!ctx.config.jobsEnabled) return false;
const o = state.overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
export function envCronFor(ctx: Ctx, job: Job): string {
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (v && isCron(v, ctx.config.timezone)) return v;
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
return job.cron;
}
export function cronFor(ctx: Ctx, job: Job): string {
const o = state.overrides[job.name];
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
return envCronFor(ctx, job);
}
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
function remember(name: string, run: Run) {
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
}
async function runJob(ctx: Ctx, job: Job) {
return (await job.run(ctx)) ?? null;
}
function startTimer(ctx: Ctx, job: Job) {
const tz = ctx.config.timezone;
const scheduleNext = () => {
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
state.timers.set(job.name, setTimeout(async () => {
await loadOverrides(ctx);
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
async function applyJob(ctx: Ctx, job: Job) {
if (state.mode === 'queue' && state.boss) {
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
else await state.boss.unschedule(job.name).catch(() => {});
} else if (state.mode === 'timers') {
clearTimeout(state.timers.get(job.name));
state.timers.delete(job.name);
startTimer(ctx, job);
}
}
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) {
state.mode = 'off';
return async () => {};
}
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
try {
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
state.boss = boss;
state.mode = 'queue';
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
await loadOverrides(ctx);
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
return runJob(ctx, job);
});
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
else await boss.unschedule(job.name).catch(() => {});
}
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
state.boss = null;
state.mode = 'timers';
for (const job of JOBS) startTimer(ctx, job);
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
}
}
export class JobError extends Error {
constructor(public status: number, message: string) { super(message); }
}
/**
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
* .env, null goes back to it, undefined leaves it.
*/
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
const { enabled, cron } = change;
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const all = { ...(await loadOverrides(ctx, true)) };
const entry: Override = { ...(all[name] ?? {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
ctx.settings.forget();
state.overrides = all;
state.overridesAt = Date.now();
await applyJob(ctx, job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
if (state.mode === 'queue' && state.boss) {
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true };
}
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
return { queued: false, output: entry.output };
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
throw new JobError(502, `The job failed: ${(e as Error).message}`);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
}
}
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
export async function jobStatus(ctx: Ctx) {
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
const recent = new Map<string, Run[]>();
if (state.mode === 'queue') {
try {
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
FROM (
SELECT name, state::text, created_on, started_on, completed_on, output,
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
} catch (e) {
console.warn('[jobs] Could not read the run history:', (e as Error).message);
}
} else {
for (const [name, list] of state.history) recent.set(name, list);
}
return {
mode: state.mode,
timezone: tz,
jobsEnabledEnv: ctx.config.jobsEnabled,
jobs: JOBS.map((job) => {
const cron = cronFor(ctx, job);
const enabled = isEnabled(ctx, job);
const o = state.overrides[job.name] ?? {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
recent: recent.get(job.name) ?? [],
};
}),
};
}
+225
View File
@@ -0,0 +1,225 @@
/**
* The emails Accounts sends (1.4.0), styled as Cross Events' (apps/events/backend/src/utils/email.js):
* a header in the church's colour with its logo or name, a white card, a button for the one thing
* to do with the link written out under it, and a footer with the church's contact details.
*
* Every email also has the plain text it always had (some mail apps show only that, and the tests
* read codes and links from it). Everything put into the HTML is escaped; colours and links are
* checked first.
*/
import type { Ctx } from '../context.js';
import { church } from '../church/profile.js';
export type Built = { subject: string; text: string; html: string };
type Brand = { name: string; colour: string; accent: string; logoUrl: string | null; email: string | null; phone: string | null; url: string };
const FONT = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`;
const MONO = `'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace`;
const HEX = /^#[0-9a-fA-F]{6}$/;
export const esc = (s: unknown) => String(s ?? '')
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
/** Only http(s) links go in an href. */
const safeUrl = (u: string) => (/^https?:\/\//i.test(u) ? u : '#');
/** A darker shade of a #rrggbb colour, for the header's gradient. */
function darker(hex: string, by = 0.25): string {
const n = parseInt(hex.slice(1), 16);
const ch = (shift: number) => Math.max(0, Math.round(((n >> shift) & 255) * (1 - by)));
return `#${[ch(16), ch(8), ch(0)].map((c) => c.toString(16).padStart(2, '0')).join('')}`;
}
async function brand(ctx: Ctx): Promise<Brand> {
const base = ctx.config.publicUrl.replace(/\/+$/, '');
try {
const c = await church(ctx);
const logo = c.branding.logoUrl;
return {
name: c.name || 'Your church',
colour: HEX.test(c.branding.colours.primary) ? c.branding.colours.primary : '#1f4e79',
accent: c.branding.colours.accent && HEX.test(c.branding.colours.accent) ? c.branding.colours.accent : '#f2a900',
logoUrl: logo ? (logo.startsWith('/') ? `${base}${logo}` : /^https:\/\//i.test(logo) ? logo : null) : null,
email: c.contact.email ?? null,
phone: c.contact.phone ?? null,
url: base,
};
} catch {
return { name: 'Your church', colour: '#1f4e79', accent: '#f2a900', logoUrl: null, email: null, phone: null, url: base };
}
}
/** The page around an email's body (Cross Events' layout). */
function layout(b: Brand, body: string, preheader: string): string {
const header = b.logoUrl
? `<img src="${esc(b.logoUrl)}" alt="${esc(b.name)}" height="56" style="display:block;margin:0 auto;max-height:56px;max-width:240px;border:0">`
: `<h1 style="color:#ffffff;font-size:26px;font-weight:800;margin:0;letter-spacing:-0.5px;font-family:${FONT};text-shadow:0 1px 3px rgba(0,0,0,0.3)">${esc(b.name)}</h1>`;
const contact = [
esc(b.name),
b.email ? `<a href="mailto:${esc(b.email)}" style="color:#94a3b8;text-decoration:underline">${esc(b.email)}</a>` : '',
b.phone ? esc(b.phone) : '',
].filter(Boolean).join(' &bull; ');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>${esc(b.name)}</title>
</head>
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%">
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all">${esc(preheader)}&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
<tr><td align="center" style="padding:40px 16px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
<tr><td style="background:${b.colour};background:linear-gradient(135deg,${b.colour} 0%,${darker(b.colour)} 100%);border-radius:12px 12px 0 0;padding:36px 48px;text-align:center">
${header}
<p style="color:#ffffff;font-size:13px;font-weight:500;margin:10px 0 0 0;font-family:${FONT};letter-spacing:0.3px;opacity:0.9">Your ${esc(b.name)} account</p>
</td></tr>
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:44px 48px 36px 48px">
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.75">
${body}
</div>
</td></tr>
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:24px 48px;text-align:center">
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">${contact}</p>
<p style="color:#cbd5e1;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">You're getting this because you have an account with ${esc(b.name)}, used to sign in to its sites.</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
const title = (t: string, sub?: string) =>
`<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(t)}</p>` +
(sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 28px 0">${esc(sub)}</p>` : '');
const hello = (name?: string | null) => `<p style="margin:0 0 8px 0;color:#374151">Hello <strong>${esc(name || 'there')}</strong>,</p>`;
const para = (html: string) => `<p style="margin:0 0 20px 0;color:#374151">${html}</p>`;
const divider = () => `<div style="border-top:1px solid #f1f5f9;margin:28px 0"></div>`;
const small = (html: string) => `<p style="margin:0;font-size:13px;color:#94a3b8">${html}</p>`;
function button(b: Brand, label: string, url: string): string {
const href = esc(safeUrl(url));
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:28px auto 8px auto">
<tr><td align="center" style="border-radius:8px;background-color:${b.colour}">
<a href="${href}" target="_blank" style="display:inline-block;padding:14px 36px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT};letter-spacing:0.2px">${esc(label)}</a>
</td></tr>
</table>
<p style="text-align:center;margin:4px 0 0 0;font-size:12px;color:#94a3b8;word-break:break-all">Or copy this link: <a href="${href}" style="color:${b.colour}">${esc(url)}</a></p>`;
}
/** Info, a warning ("if this wasn't you") or neutral: these colours never follow the church's. */
function callout(html: string, kind: 'info' | 'warning' | 'success' = 'info'): string {
const s = { info: ['#eff6ff', '#3b82f6', '#1e40af'], warning: ['#fffbeb', '#f59e0b', '#92400e'], success: ['#f0fdf4', '#22c55e', '#166534'] }[kind];
return `<div style="background:${s[0]};border-left:4px solid ${s[1]};border-radius:0 6px 6px 0;padding:14px 18px;margin:24px 0;color:${s[2]};font-size:14px;line-height:1.6">${html}</div>`;
}
const code6 = (code: string) =>
`<p style="margin:8px 0 24px 0;font-size:34px;font-weight:800;letter-spacing:8px;color:#0f172a;text-align:center;font-family:${MONO}">${esc(code)}</p>`;
const contactLine = (b: Brand) => (b.email ? ` at <a href="mailto:${esc(b.email)}" style="color:${b.colour}">${esc(b.email)}</a>` : '');
// ─── The emails ───────────────────────────────────────────────────────────────
/** A sign-in or confirm-your-email code (the text is the WhatsApp message too). */
export async function codeEmail(ctx: Ctx, o: { name?: string | null; code: string; text: string; purpose: 'sign_in' | 'verify_email' | 'setup'; minutes: number }): Promise<Built> {
const b = await brand(ctx);
const what = o.purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
const body = title('Your code', o.purpose === 'verify_email' ? 'To confirm your email address' : `To sign in to ${b.name}`)
+ hello(o.name)
+ para(`Enter this code to ${esc(what)}. It works for <strong>${o.minutes} minutes</strong>.`)
+ code6(o.code)
+ divider()
+ small(`Never share this code with anyone, not even someone from the church. If you didn't ask for it, you can ignore this email: nobody can sign in without your password${o.purpose === 'sign_in' ? ' and this code' : ''}.`);
return { subject: `Your code: ${o.code}`, text: o.text, html: layout(b, body, `Your code is ${o.code}. It works for ${o.minutes} minutes.`) };
}
export async function resetPasswordEmail(ctx: Ctx, o: { name?: string | null; url: string; minutes: number }): Promise<Built> {
const b = await brand(ctx);
const body = title('Reset your password', 'Someone (we hope you) asked to reset it.')
+ hello(o.name)
+ para(`Choose a new password with the button below. The link works for <strong>${o.minutes} minutes</strong>, once.`)
+ button(b, 'Choose a new password', o.url)
+ divider()
+ small(`If you didn't ask, you can ignore this email: your password stays the same. Worried? Let the church office know${contactLine(b)}.`);
const text = `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${o.minutes} minutes):\n${o.url}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`;
return { subject: 'Reset your password', text, html: layout(b, body, `Choose a new password. The link works for ${o.minutes} minutes.`) };
}
/** A product (Cross Events) made someone an account: choose a password. */
export async function newAccountEmail(ctx: Ctx, o: { name: string; url: string; days: number }): Promise<Built> {
const b = await brand(ctx);
const body = title(`Welcome to ${b.name}`, 'An account has been made for you.')
+ hello(o.name)
+ para(`${esc(b.name)} has made you an account. It signs you in to all of the church's sites, such as events and registrations. Choose your password to start using it.`)
+ button(b, 'Choose my password', o.url)
+ callout(`The link works for <strong>${o.days} days</strong>. After that, use <em>Forgot your password?</em> on the sign-in page.`, 'info')
+ small('If you weren\'t expecting this, you can ignore this email.');
const text = `Hello ${o.name},\n\n${b.name} has made you an account. Choose your password here (the link works for ${o.days} days):\n${o.url}\n\nIf you weren't expecting this, you can ignore this email.`;
return { subject: `Your account at ${b.name}`, text, html: layout(b, body, `Choose your password for your ${b.name} account.`) };
}
export async function confirmNewEmail(ctx: Ctx, o: { name?: string | null; url: string }): Promise<Built> {
const b = await brand(ctx);
const body = title('Confirm your new email address')
+ hello(o.name)
+ para('You asked to sign in with this email address from now on. Confirm it\'s yours with the button below; until then you keep signing in with your old one.')
+ button(b, 'Confirm this address', o.url)
+ divider()
+ small('The link works for 24 hours. If you didn\'t ask for this, you can ignore this email.');
const text = `Confirm this is your new email address for signing in:\n${o.url}\n\nThe link works for 24 hours.`;
return { subject: 'Confirm your new email address', text, html: layout(b, body, 'Confirm your new sign-in email address.') };
}
export async function emailChangedNotice(ctx: Ctx, o: { name?: string | null; newEmail: string }): Promise<Built> {
const b = await brand(ctx);
const body = title('Your sign-in email address changed')
+ hello(o.name)
+ para(`Your account now signs in with <strong>${esc(o.newEmail)}</strong>. Emails about your account go there from now on.`)
+ callout(`<strong>Wasn't you?</strong> Contact the church office straight away${contactLine(b)}.`, 'warning');
const text = `Your account now signs in with ${o.newEmail}. If you didn't do this, contact the church office straight away.`;
return { subject: 'Your sign-in email address changed', text, html: layout(b, body, `Your account now signs in with ${o.newEmail}.`) };
}
export async function exportReadyEmail(ctx: Ctx, o: { name?: string | null; url: string; days: number }): Promise<Built> {
const b = await brand(ctx);
const body = title('Your data is ready', 'The copy you asked for')
+ hello(o.name)
+ para('The copy of your data you asked for is ready. Download it from your account page.')
+ button(b, 'Download my data', o.url)
+ callout(`It's kept for <strong>${o.days} days</strong>, then deleted. You need to be signed in to download it.`, 'info');
const text = `The copy of your data you asked for is ready. Download it from your account page (it's kept for ${o.days} days):\n${o.url}`;
return { subject: 'Your data is ready to download', text, html: layout(b, body, 'The copy of your data you asked for is ready.') };
}
/** A test from the admin page or from a linked product (`from`: "Cross Events"). */
export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Built> {
const b = await brand(ctx);
const body = title('Email works', o.from ? `A test sent from ${o.from}` : 'A test from Accounts')
+ para(`This is a test from ${esc(b.name)}'s sign-in (Accounts)${o.from ? `, sent from ${esc(o.from)}` : ''}.`)
+ callout('Email is set up: sign-in codes, password links and security notices can be sent.', 'success');
const text = o.from
? `This is a test from ${b.name}'s sign-in (Accounts), sent from ${o.from}. Email works: sign-in codes and password links can be sent.`
: 'Email from Accounts works.';
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
}
/** A sign-in happened (1.6.0, as Cross Events' "New login detected"). `whatsapp`: the same in a few lines. */
export async function newSignInEmail(ctx: Ctx, o: { name?: string | null; when: string; location: string; device: string; site: string | null }): Promise<Built & { whatsapp: string }> {
const b = await brand(ctx);
const row = (k: string, v: string) => `<tr><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#64748b;font-size:13px;font-weight:600;width:34%">${esc(k)}</td><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#1e293b;font-size:14px;word-break:break-word">${esc(v)}</td></tr>`;
const body = title('New sign-in', `Someone signed in to your ${b.name} account`)
+ hello(o.name)
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin:0 0 8px 0">`
+ row('When', o.when) + (o.site ? row('Signed in to', o.site) : '') + row('Where (roughly)', o.location) + row('Device', o.device)
+ '</table>'
+ callout(`<strong>Not you?</strong> Change your password straight away from your account page, and let the church office know${contactLine(b)}.`, 'warning')
+ small('If this was you, there\'s nothing to do.');
const lines = [`When: ${o.when}`, ...(o.site ? [`Signed in to: ${o.site}`] : []), `Where (roughly): ${o.location}`, `Device: ${o.device}`];
const text = `Hello ${o.name || 'there'},\n\nSomeone signed in to your ${b.name} account.\n\n${lines.join('\n')}\n\nIf this wasn't you, change your password straight away and let the church office know${b.email ? ` (${b.email})` : ''}.\nIf it was you, there's nothing to do.`;
const whatsapp = `🔐 *New sign-in*\n\nHello ${o.name || 'there'}, someone signed in to your *${b.name}* account.\n\n${lines.join('\n')}\n\nNot you? Change your password straight away and let the church office know.`;
return { subject: `New sign-in to your ${b.name} account`, text, html: layout(b, body, `New sign-in: ${o.when}, ${o.device}.`), whatsapp };
}
+4 -3
View File
@@ -5,7 +5,8 @@
import nodemailer from 'nodemailer';
import type { Ctx } from '../context.js';
export type Email = { to: string; subject: string; text: string };
/** `html` (1.4.0, src/lib/emails.ts): the styled version; `text` is always sent too. */
export type Email = { to: string; subject: string; text: string; html?: string };
export type WhatsApp = { to: string; text: string };
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
@@ -87,7 +88,7 @@ export class LiveMessenger implements Messenger {
return;
}
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
}
async emailReady(): Promise<boolean> {
@@ -112,7 +113,7 @@ export class LiveMessenger implements Messenger {
async emailWith(settings: SmtpTry, msg: Email): Promise<void> {
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text });
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
}
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
+1 -1
View File
@@ -9,7 +9,7 @@ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_i
/** The settings an admin may read and change through the generic settings API. */
export const ADMIN_SETTINGS = new Set([
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
'wawp_access_token', 'wawp_instance_id',
]);
+42 -9
View File
@@ -23,13 +23,18 @@ import type { Ctx } from '../context.js';
import type { ProductLink } from '../generated/prisma/client.js';
import { limit } from '../http.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { newAccountEmail, testEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { appVersion } from '../lib/version.js';
import { BUILT_IN_VERSION } from '../privacy/notice.js';
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js';
import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js';
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
const PROFILE_EDITORS = new Set(['website']);
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
@@ -224,16 +229,11 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
// Only the product's own address: never somewhere else.
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } });
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
// 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?"
// once email works); the product is told.
let emailSent = true;
try {
await ctx.messenger.email({
to: email,
subject: `Your account at ${churchName}`,
text: `Hello ${r.name},\n\n${churchName} has made you an account. Choose your password here (the link works for ${SET_PASSWORD_DAYS} days):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you weren't expecting this, you can ignore this email.`,
});
await ctx.messenger.email({ to: email, ...(await newAccountEmail(ctx, { name: r.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, days: SET_PASSWORD_DAYS })) });
} catch (e) {
emailSent = false;
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
@@ -307,6 +307,38 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
return reply({ removed, kept });
}
case 'people.check': {
// 1.5.0: the product's regular check that its copies are current. Profiles only for people
// this product knows; a deleted account is said to be deleted (its sub was that person's).
const subs = [...new Set(r.subs)];
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId));
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a]));
const people = subs.map((sub) => {
const a = accounts.get(sub);
if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null };
if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null };
return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) };
});
const count = (s: string) => people.filter((p) => p.status === s).length;
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people });
}
case 'church.update': {
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
// checks it's the Website, that the person signs in through it, and audits it as theirs.
if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403);
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } });
if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403);
try {
const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt });
await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) });
return reply({ church });
} catch (e) {
if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409);
if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400);
throw e;
}
}
case 'church.branding': {
const changed = await applyLook(ctx, r.church, r.overwrite);
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
@@ -325,7 +357,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
const pass = s.pass === null ? ((await ctx.settings.get('smtp_pass')) ?? '') : opened(secret, s.pass, 'SMTP password');
const tryWith = { host: s.host, port: s.port, secure: s.secure, user: s.user, pass: pass ?? '', from: s.from };
try {
await ctx.messenger.emailWith(tryWith, { to: r.email.to, subject: `Test email from ${church}'s sign-in`, text: `This is a test from ${church}'s sign-in (Accounts), sent from ${link.product === 'events' ? 'Cross Events' : link.product}. Email works: sign-in codes and password links can be sent.` });
await ctx.messenger.emailWith(tryWith, { to: r.email.to, ...(await testEmail(ctx, { from: link.product === 'events' ? 'Cross Events' : link.product })) });
email = { ok: true, error: null, saved: false };
if (save) {
await ctx.settings.setMany({ smtp_host: s.host, smtp_port: String(s.port), smtp_secure: String(s.secure), smtp_user: s.user, smtp_from: s.from, ...(s.pass === null ? {} : { smtp_pass: pass }) });
@@ -386,7 +418,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
}
const out = await handle(ctx, provider, link, secret, request, req);
// Checks write nothing, so they needn't be remembered.
const isCheck = 'check' in request && request.check;
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
if (!isCheck) {
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
}
+3 -2
View File
@@ -8,6 +8,7 @@ import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { confirmNewEmail, emailChangedNotice } from '../lib/emails.js';
import { hashPassword, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { emailProblem, normaliseEmail, normalisePhone, profileChanged, setNewsConsent } from '../accounts/service.js';
import { confirmTwoFactorSetup, recoveryCodesLeft, replaceRecoveryCodes, startTwoFactorSetup, turnOff } from '../accounts/twoFactor.js';
@@ -93,7 +94,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address.', { email: 'Another account uses that email address.' });
const token = randomToken();
await ctx.db.emailToken.create({ data: { accountId: s.account.id, purpose: `change_email:${email}`, tokenHash: hashToken(token), expiresAt: new Date(ctx.now().getTime() + 24 * 3600e3) } });
await ctx.messenger.email({ to: email, subject: 'Confirm your new email address', text: `Confirm this is your new email address for signing in:\n${ctx.config.publicUrl}/account/confirm-email?token=${token}\n\nThe link works for 24 hours.` });
await ctx.messenger.email({ to: email, ...(await confirmNewEmail(ctx, { name: s.account.name, url: `${ctx.config.publicUrl}/account/confirm-email?token=${token}` })) });
return { sent: true };
}));
@@ -105,7 +106,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address now.');
await ctx.db.account.update({ where: { id: s.account.id }, data: { email, emailVerified: true } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.messenger.email({ to: s.account.email, subject: 'Your sign-in email address changed', text: `Your account now signs in with ${email}. If you didn't do this, contact the church office straight away.` });
await ctx.messenger.email({ to: s.account.email, ...(await emailChangedNotice(ctx, { name: s.account.name, newEmail: email })) });
await loginEvent(ctx, s.account.id, 'email_changed', req);
await profileChanged(ctx, s.account.id);
return view(s);
+2 -1
View File
@@ -9,6 +9,7 @@ import path from 'node:path';
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { onReply, queueCall } from '../links/deliveries.js';
import { exportReadyEmail } from '../lib/emails.js';
const WAIT_MS = 24 * 3600e3;
const KEEP_MS = 7 * 24 * 3600e3;
@@ -71,7 +72,7 @@ export async function finishIfComplete(ctx: Ctx, exportId: string, force = false
}, null, 2), { mode: 0o600 });
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
if (a) await ctx.messenger.email({ to: a.email, ...(await exportReadyEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/account/privacy`, days: Math.round(KEEP_MS / 86400e3) })) });
return true;
}
@@ -0,0 +1,108 @@
// church.update (contracts 1.17.0, Accounts 1.7.0, WEBSITE-1.0-PLAN decision 10): the Website's
// admin changes shared profile facts through Accounts, and the brand style is kept by every save.
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, describe, test } from 'node:test';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, signedHeaders } from '@crosscode/contracts/signing';
import { startHarness, type Harness } from './support/harness.js';
import { church, mergeProfile, updateProfile } from '../src/church/profile.js';
const WEBSITE_ID = '7e2a1c3d-9b4f-4d6e-8f70-2b3c4d5e6f70';
const EVENTS_ID = '8f3b2d4e-0c5a-4e7f-9a81-3c4d5e6f7a81';
let h: Harness;
const secrets: Record<string, string> = {};
let editor: string;
before(async () => {
h = await startHarness();
for (const [id, product] of [[WEBSITE_ID, 'website'], [EVENTS_ID, 'events']] as const) {
secrets[id] = newLinkSecret();
await h.db.productLink.create({
data: { installId: id, product, url: `https://${product}.hope.test`, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secrets[id]!), connectedAt: new Date() },
});
}
const a = await h.makeAccount({ email: 'editor@hope.test' });
editor = a.id as string;
for (const linkId of [WEBSITE_ID, EVENTS_ID]) await h.db.productPerson.create({ data: { linkId, accountId: editor, via: 'sign_in', createdAt: new Date() } });
await updateProfile(h.ctx, { name: 'Hope Family Church', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } } });
});
after(async () => { await h.close(); });
async function ask(body: Record<string, unknown>, from = WEBSITE_ID) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: editor, type: 'church.update', ...body });
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret: secrets[from]!, rawBody: raw });
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}
describe('church.update from the Website', () => {
test('changes only the style, keeps the colours and logo, and goes live at once', async () => {
const res = await ask({ church: { branding: { style: { fontPairing: 'warm', corners: 'round' } } } });
assert.equal(res.status, 200, JSON.stringify(res.body));
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'round' });
assert.equal(c.branding.colours.primary, '#1f4e79');
assert.equal(c.name, 'Hope Family Church');
assert.deepEqual((res.body.church as { branding: unknown }).branding, c.branding);
});
test('tells every linked product the profile changed, and audits it as the editor', async () => {
const before = await h.db.delivery.count();
const res = await ask({ church: { shortName: 'Hope Family' } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.ok((await h.db.delivery.count()) > before);
const log = await h.db.auditLog.findFirst({ where: { action: 'church_profile_changed_by_product' }, orderBy: { createdAt: 'desc' } });
assert.equal(log?.actorId, editor);
});
test('refuses another product, someone who doesn\'t sign in through the Website, and a stale edit', async () => {
const events = await ask({ church: { name: 'Hijacked' } }, EVENTS_ID);
assert.equal(events.status, 403);
assert.equal(events.body.code, 'WRONG_PRODUCT');
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
const notKnown = await ask({ actor: stranger.id as string, church: { name: 'Hijacked' } });
assert.equal(notKnown.status, 403);
assert.equal(notKnown.body.code, 'NOT_ALLOWED');
const stale = await ask({ ifUpdatedAt: '2020-01-01T00:00:00.000Z', church: { name: 'Hijacked' } });
assert.equal(stale.status, 409);
assert.equal(stale.body.code, 'PROFILE_CHANGED');
assert.equal((await church(h.ctx)).name, 'Hope Family Church');
});
test('takes an edit made on the current version', async () => {
const current = await church(h.ctx);
const res = await ask({ ifUpdatedAt: current.updatedAt, church: { serviceTimes: [{ day: 'sunday', time: '09:00', label: null, campus: null, note: null }] } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal((await church(h.ctx)).serviceTimes.length, 1);
});
test('an invalid value is refused with what\'s wrong', async () => {
const res = await ask({ church: { contact: { email: null, phone: '016 123', whatsapp: null, address: null } } });
assert.equal(res.status, 400);
assert.equal(res.body.code, 'INVALID_REQUEST');
});
});
describe('saving the profile keeps the brand style', () => {
test('an admin form that sends branding without the style doesn\'t drop it', async () => {
await updateProfile(h.ctx, { branding: { style: { fontPairing: 'classic', corners: 'sharp' } } });
await updateProfile(h.ctx, { branding: { logoUrl: null, iconUrl: null, colours: { primary: '#204060', accent: null } } });
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'classic', corners: 'sharp' });
assert.equal(c.branding.colours.primary, '#204060');
});
test('mergeProfile replaces other fields whole and merges branding', () => {
const merged = mergeProfile({ name: 'A', social: [1], branding: { logoUrl: 'x', colours: { primary: '#000000' } } }, { social: [], branding: { colours: { primary: '#ffffff' } } });
assert.deepEqual(merged, { name: 'A', social: [], branding: { logoUrl: 'x', colours: { primary: '#ffffff' } } });
});
test('the sign-in pages get the style', async () => {
const res = await fetch(`${h.publicUrl}/api/v2/branding`);
const b = (await res.json()) as { style: unknown };
assert.deepEqual(b.style, { fontPairing: 'classic', corners: 'sharp' });
});
});
@@ -0,0 +1,103 @@
// 1.4.0: Admin → Background jobs (switch a job on or off, change its schedule, over the .env) and
// the styled emails (as Cross Events').
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { Browser, startHarness, type Harness } from './support/harness.js';
import { codeAt } from '../src/lib/totp.js';
import { JOBS, cronFor, isEnabled, useEnvForTest } from '../src/jobs.js';
import { esc, newAccountEmail, resetPasswordEmail } from '../src/lib/emails.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { useEnvForTest(process.env); await h.close(); });
let adminBrowser: Browser | null = null;
async function adminPage() {
if (adminBrowser) return adminBrowser;
await h.makeAccount({ email: 'jobs.admin@hope.test', password: 'Correct-horse-8', role: 'admin' });
const browser = new Browser();
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'jobs.admin@hope.test', password: 'Correct-horse-8' });
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' });
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
adminBrowser = browser;
return browser;
}
const backup = JOBS.find((j) => j.name === 'backup')!;
describe('background jobs', () => {
test('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
h.ctx.config.jobsEnabled = true; // the harness turns them off; nothing is started here either way
const browser = await adminPage();
let list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
assert.equal(list.status, 200);
let job = (list.body.jobs as { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, false);
assert.equal(job.envEnabled, false);
assert.equal(job.cron, '30 1 * * *');
assert.deepEqual(job.override, { enabled: null, cron: null });
const on = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: true, cron: '0 3 * * *' });
assert.equal(on.status, 200);
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
assert.equal(isEnabled(h.ctx, backup), true);
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
job = (list.body.jobs as typeof job[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, true);
assert.equal(job.envEnabled, false);
const back = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: null, cron: null });
assert.deepEqual(back.body.override, { enabled: null, cron: null });
assert.equal(isEnabled(h.ctx, backup), false);
assert.equal(cronFor(h.ctx, backup), '30 1 * * *');
const audit = await h.ctx.db.auditLog.findMany({ where: { action: 'job_settings_changed' } });
assert.equal(audit.length, 2);
});
test('a bad schedule, a bad switch and an unknown job are refused', async () => {
const browser = await adminPage();
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { cron: 'every night' })).status, 400);
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: 'yes' })).status, 400);
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/nope', { enabled: true })).status, 404);
});
test('only admins see them', async () => {
const anon = new Browser();
assert.equal((await h.api(anon, 'GET', '/api/v2/admin/jobs')).status, 401);
});
});
describe('styled emails', () => {
test('in the church colour, with its name escaped, and the same plain text as before', async () => {
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope <Church> & Co', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#336699', accent: null } }, contact: { email: 'office@hope.test', phone: null, whatsapp: null, address: null } }));
const r = await resetPasswordEmail(h.ctx, { name: '<b>Jane</b>', url: 'https://accounts.hope.test/reset?token=abc', minutes: 60 });
assert.equal(r.subject, 'Reset your password');
assert.match(r.text, /https:\/\/accounts\.hope\.test\/reset\?token=abc/);
assert.match(r.html, /background-color:#336699/);
assert.match(r.html, /Hope &lt;Church&gt; &amp; Co/);
assert.ok(!r.html.includes('<b>Jane</b>'));
assert.match(r.html, /href="https:\/\/accounts\.hope\.test\/reset\?token=abc"/);
assert.match(r.html, /office@hope\.test/);
const n = await newAccountEmail(h.ctx, { name: 'Sam', url: 'javascript:alert(1)', days: 7 });
assert.equal(n.subject, 'Your account at Hope <Church> & Co');
assert.ok(!n.html.includes('href="javascript:'));
assert.equal(esc('"x"'), '&quot;x&quot;');
});
test('the test email from admin goes as HTML too', async () => {
const browser = await adminPage();
const m = h.ctx.messenger as MemoryMessenger;
const before = m.emails.length;
assert.equal((await h.api(browser, 'POST', '/api/v2/admin/settings/test-email', {})).status, 200);
const sent = m.emails.slice(before).at(-1)!;
assert.equal(sent.subject, 'Test email from Accounts');
assert.match(sent.html ?? '', /<!DOCTYPE html>/);
});
});
@@ -199,6 +199,29 @@ describe('people.* from a product', () => {
assert.equal(again.body.created, true);
});
test('1.5.0 people.check: profiles of the product\'s people, deleted accounts, and unknown for the rest; never stored', async () => {
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
const known = await ensure('Check Known', 'check.known@hope.test');
const gone = await ensure('Check Gone', 'check.gone@hope.test');
await h.db.account.update({ where: { id: gone }, data: { status: 'deleted' } });
const off = await ensure('Check Off', 'check.off@hope.test');
await h.db.account.update({ where: { id: off }, data: { status: 'deactivated' } });
const stranger = (await h.makeAccount({ email: 'check.stranger@hope.test' })).id as string;
const nobody = crypto.randomUUID();
const requestId = crypto.randomUUID();
const res = await ask({ type: 'people.check', subs: [known, gone, off, stranger, nobody] }, { requestId });
assert.equal(res.status, 200, JSON.stringify(res.body));
const bySub = Object.fromEntries((res.body.people as { sub: string; status: string; profile: { name: string } | null }[]).map((p) => [p.sub, p]));
assert.equal(bySub[known]!.status, 'active');
assert.equal(bySub[known]!.profile!.name, 'Check Known');
assert.equal(bySub[gone]!.status, 'deleted');
assert.equal(bySub[gone]!.profile, null);
assert.equal(bySub[off]!.status, 'deactivated');
assert.deepEqual([bySub[stranger]!.status, bySub[stranger]!.profile], ['unknown', null], 'not known through this product: no profile');
assert.equal(bySub[nobody]!.status, 'unknown');
assert.equal(await h.db.productRequest.findUnique({ where: { requestId } }), null, 'the reply holds profiles: not kept');
});
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
const requestId = crypto.randomUUID();
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
@@ -0,0 +1,50 @@
// 1.6.0: a "New sign-in" email (and WhatsApp) after each sign-in, as Cross Events sends.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { startHarness, type Harness } from './support/harness.js';
import { describeDevice, sendSignInNotice } from '../src/accounts/signInNotice.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
describe('sign-in notices', () => {
test('an email with when, where, the device and the site; WhatsApp too for a verified number', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.person@hope.test' });
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: '127.0.0.1', userAgent: CHROME_WIN, clientId: 'accounts-self' }), 'sent');
const mail = m.emails.filter((e) => e.to === 'notice.person@hope.test').at(-1)!;
assert.match(mail.subject, /^New sign-in to your .+ account$/);
assert.match(mail.text, /Device: Chrome on Windows/);
assert.match(mail.text, /Signed in to: Your account page/);
assert.match(mail.html ?? '', /Not you\?/);
await h.db.account.update({ where: { id: a.id as string }, data: { phone: '+27821234567', phoneVerified: true } });
m.whatsappOn = true;
const before = m.whatsapps.length;
await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null });
assert.equal(m.whatsapps.length, before + 1);
assert.match(m.whatsapps.at(-1)!.text, /New sign-in/);
m.whatsappOn = false;
});
test('admins can switch them off; a failing email never throws', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.off@hope.test' });
await h.ctx.settings.set('signin_notices', 'false');
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'off');
await h.ctx.settings.set('signin_notices', null);
m.emailOn = false;
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'failed');
m.emailOn = true;
});
test('device names', () => {
assert.equal(describeDevice(CHROME_WIN), 'Chrome on Windows');
assert.equal(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone or iPad');
assert.equal(describeDevice(null), 'Unknown device');
});
});
+43
View File
@@ -0,0 +1,43 @@
import AxeBuilder from "@axe-core/playwright";
import { expect, test } from "@playwright/test";
// 1.7.0 (WEBSITE-1.0-PLAN §3, §9): the church's brand style and shared footer on Accounts' public
// pages. The e2e church (e2e/server.ts) has the "warm" pairing, round corners and service times.
const PRODUCT = "http://localhost:5211";
test("the sign-in page uses the church's fonts and corners, and shows its footer", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm");
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
const heading = page.getByRole("heading", { name: "Sign in to Hope Family Church" });
expect(await heading.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Fraunces");
expect(await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Nunito Sans");
// The font files themselves load from this site (self-hosted), not from anyone else.
await page.evaluate(() => document.fonts.ready);
expect(await page.evaluate(() => document.fonts.check('600 20px "CC Fraunces"'))).toBe(true);
expect(await page.getByRole("button", { name: "Sign in" }).evaluate((el) => getComputedStyle(el).borderRadius)).toBe("9999px");
const footer = page.locator("footer");
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
await expect(footer).toContainText("Sundays 09:00");
await expect(footer.getByRole("link", { name: "office@hope.test" })).toHaveAttribute("href", "mailto:office@hope.test");
await expect(footer.getByRole("link", { name: "Website" })).toHaveAttribute("href", PRODUCT);
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/privacy");
});
test("fonts never come from another site", async ({ page }) => {
const foreign: string[] = [];
page.on("request", (r) => { if (/\.(woff2?|ttf|otf)(\?|$)/.test(r.url()) && !r.url().startsWith("http://localhost:3210/")) foreign.push(r.url()); });
await page.goto(`${PRODUCT}/start?returnTo=/`);
await page.evaluate(() => document.fonts.ready);
expect(foreign).toEqual([]);
});
test("the sign-in page with the footer passes axe (WCAG 2.2 AA)", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.locator("footer")).toBeVisible();
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
});
+7 -1
View File
@@ -29,7 +29,13 @@ const messenger = new MemoryMessenger();
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
await ctx.settings.setMany({
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
// 1.7.0: a brand style, service times and contact details, so the pages show the church's fonts and footer.
church_profile: JSON.stringify({
name: 'Hope Family Church', shortName: 'Hope',
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' }, style: { fontPairing: 'warm', corners: 'round' } },
serviceTimes: [{ day: 'sunday', time: '09:00', label: 'Morning service', campus: null, note: null }],
contact: { email: 'office@hope.test', phone: '+27161234567', whatsapp: null, address: null },
}),
});
const linkSecret = newLinkSecret();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.3.0",
"version": "1.7.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
@@ -2,7 +2,8 @@
import Link from "next/link";
import { useState } from "react";
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
import { Card, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -20,12 +21,12 @@ export function ConfirmEmail({ token }: { token: string }) {
return () => { alive = false; };
}, [token]);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading>Your email address</Heading>
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
<Link href="/account" className="text-brand underline">Back to your account</Link>
</Card>
</Shell>
</PublicShell>
);
}
+166 -4
View File
@@ -2,7 +2,7 @@
import Link from "next/link";
import React, { useCallback, useState } from "react";
import { DatabaseBackup, Download } from "lucide-react";
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText";
@@ -10,6 +10,7 @@ import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
import { BrandStyle } from "./BrandStyle";
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
@@ -55,12 +56,13 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
{section === "people" && <People flash={flash} />}
<div className="max-w-3xl">
{section === "deletions" && <Deletions flash={flash} />}
{section === "church" && <Church flash={flash} />}
{section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>}
{section === "linked" && <Linked flash={flash} />}
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />}
{section === "licence" && <Licence flash={flash} />}
{section === "audit" && <Audit />}
</div>
@@ -251,6 +253,7 @@ function Linked({ flash }: { flash: Flash }) {
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
signup_enabled: ["Members can create their own account", "bool"],
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
signin_notices: ["Tell people by email (and WhatsApp) each time they sign in", "bool"],
session_days: ['Days "Keep me signed in" lasts', "number"],
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
@@ -265,7 +268,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
return () => { alive = false; };
}, []);
if (!values) return <p className="text-gray-600">Loading…</p>;
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
return (
<Card>
<form onSubmit={async (e) => {
@@ -463,3 +466,162 @@ function Backups({ flash }: { flash: Flash }) {
</div>
);
}
// ─── Background jobs (1.4.0, as Cross Events) ────────────────────────────────
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
};
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const RUN_STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700",
created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500",
};
const SCHEDULES = [
{ label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
];
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const h = /^(\d+) \* \* \* \*$/.exec(cron);
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
return cron;
}
function runText(r: JobRun): string {
if (r.output === null || r.output === undefined) return "";
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
try { return JSON.stringify(r.output); } catch { return ""; }
}
/** An on/off switch (role="switch", so screen readers hear on and off). */
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
return (
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${on ? "bg-brand" : "bg-gray-300"}`}>
<span className={`inline-block h-5 w-5 rounded-full bg-white shadow transition-transform ${on ? "translate-x-5" : "translate-x-0.5"}`} />
</button>
);
}
function Jobs({ flash }: { flash: Flash }) {
const [data, setData] = useState<JobList | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
// Not tied to `flash` (a new function each render): the list loads once, then on Refresh.
const load = useCallback(async () => {
const r = await call<JobList>("GET", "/admin/jobs");
if (r.ok) { setData(r.data); setLoadError(null); } else setLoadError(r.error.message);
}, []);
useExternalEffect(() => { void load(); }, [load]);
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
setBusy(job.name);
const r = await call("PUT", `/admin/jobs/${encodeURIComponent(job.name)}`, change);
setBusy(null);
if (r.ok) { flash("success", done); setEditing(null); void load(); } else flash("error", r.error.message);
};
const runNow = async (job: JobInfo) => {
setBusy(job.name);
const r = await call<{ queued: boolean }>("POST", `/admin/jobs/${encodeURIComponent(job.name)}/run`);
setBusy(null);
if (r.ok) {
flash("success", r.data.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.`);
setTimeout(() => void load(), r.data.queued ? 4000 : 0);
} else flash("error", r.error.message);
};
if (!data) return loadError ? <Notice tone="error">{loadError}</Notice> : <p className="text-gray-600">Loading…</p>;
const off = data.mode === "off";
return (
<Card>
<div className="mb-3 flex items-start justify-between gap-3">
<Heading icon={<Timer className="h-4 w-4" />} sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs</Heading>
<Button variant="secondary" onClick={() => void load()}><RefreshCw className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />Refresh</Button>
</div>
{off && <Notice tone="warning">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
{data.mode === "timers" && <Notice tone="warning">The job queue couldn&apos;t start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
<ul className="divide-y rounded-lg border">
{data.jobs.map((job) => {
const last = job.recent[0];
const mine = busy === job.name;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
<div className="mr-auto min-w-0">
<div className={`text-sm font-medium ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
<div className="text-xs text-gray-500">
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{job.override.enabled !== null
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the .env again.`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} title="Recent runs" className={`rounded px-2 py-0.5 text-xs ${RUN_STATE[last.state] ?? "bg-gray-100 text-gray-600"}`}>
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn)}
</button>
)}
<Button variant="secondary" disabled={mine || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}>Schedule</Button>
<Button variant="secondary" disabled={!!busy || off} onClick={() => void runNow(job)}><Play className="mr-1 inline h-3.5 w-3.5" aria-hidden />Run now</Button>
</div>
{isEditing && editing && (
<form className="mt-3 space-y-2 rounded-lg border bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{SCHEDULES.map((p) => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`rounded border px-2 py-1 text-xs ${editing.cron === p.cron ? "border-brand bg-white font-medium" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-3">
<Field label="Cron (minute hour day month weekday)" name="cron" value={editing.cron} maxLength={100} className="mb-0 w-64 font-mono"
onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} />
<div className="ml-auto flex gap-2 pb-6">
<Button type="button" variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
<Button type="submit" busy={mine} disabled={!editing.cron.trim()}>Save schedule</Button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "}
{job.override.cron !== null && <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}>Use that again</button>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<div className="mt-2 overflow-x-auto">
<table className="w-full text-xs">
<thead className="text-gray-500"><tr><th className="py-1 text-left font-medium">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
<tbody>
{job.recent.map((r, i) => (
<tr key={i} className="border-t">
<td className="whitespace-nowrap py-1 pr-2">{when(r.startedOn)}</td>
<td className="whitespace-nowrap pr-2">{when(r.completedOn)}</td>
<td className="pr-2"><span className={`rounded px-1.5 py-0.5 ${RUN_STATE[r.state] ?? ""}`}>{r.state}</span></td>
<td className="break-all font-mono text-[11px] text-gray-600">{runText(r)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</li>
);
})}
</ul>
<p className="mt-3 text-xs text-gray-500">Without a choice here, the server&apos;s .env applies: a job&apos;s own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;. The nightly backup also follows Backups → &quot;Back up every night&quot;.</p>
</Card>
);
}
@@ -0,0 +1,98 @@
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { CORNERS, FONT_PAIRING_IDS, FONT_PAIRINGS, type Corners, type FontPairing } from "@crosscode/contracts";
import { Button } from "@crosscode/ui";
import { Card, Heading } from "@/components/Panel";
import { call } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Style = { fontPairing: FontPairing | null; corners: Corners | null };
type ChurchStyle = { branding: { style?: Style } };
const CORNER_LABELS: Record<Corners, { name: string; radius: string }> = {
sharp: { name: "Sharp", radius: "0" },
soft: { name: "Soft", radius: "0.5rem" },
round: { name: "Round", radius: "9999px" },
};
/**
* The church's brand style (1.7.0, WEBSITE-1.0-PLAN §3): a font pairing and corners, shared by
* Accounts' pages, the Website and Cross Events. Each option is shown in its own fonts (fonts.css
* is loaded on every page; a pairing's files download only when shown).
*/
export function BrandStyle({ flash }: { flash: (tone: "success" | "error", text: string) => void }) {
const router = useRouter();
const [saved, setSaved] = useState<Style | null>(null);
const [style, setStyle] = useState<Style>({ fontPairing: null, corners: null });
const [busy, setBusy] = useState(false);
useExternalEffect(() => {
let alive = true;
call<ChurchStyle>("GET", "/admin/church").then((r) => {
if (!alive || !r.ok) return;
const s = { fontPairing: r.data.branding.style?.fontPairing ?? null, corners: r.data.branding.style?.corners ?? null };
setSaved(s);
setStyle(s);
});
return () => { alive = false; };
}, []);
if (!saved) return null;
const changed = saved.fontPairing !== style.fontPairing || saved.corners !== style.corners;
const option = (selected: boolean) => `block cursor-pointer rounded-xl border p-4 transition focus-within:ring-2 focus-within:ring-brand/50 ${selected ? "border-brand bg-brand/5 ring-1 ring-brand" : "border-gray-200 hover:border-gray-300"}`;
return (
<Card className="mt-6">
<Heading sub="How the church's sites look: these sign-in pages, the website and Cross Events' public pages. Colours and logo are above.">Brand style</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
const r = await call<ChurchStyle>("PUT", "/admin/church", { branding: { style } });
setBusy(false);
if (r.ok) {
setSaved(style);
flash("success", "Saved. The church's sites use the new style.");
router.refresh();
} else flash("error", r.error.message);
}}>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Fonts</legend>
<p className="mb-3 text-sm text-gray-600">A font for headings and one for text. The website&apos;s template recommends three, but any works.</p>
<div className="grid gap-3 sm:grid-cols-2">
<label className={option(style.fontPairing === null)}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === null} onChange={() => setStyle({ ...style, fontPairing: null })} />
<span className="block text-lg font-semibold [font-family:ui-sans-serif,system-ui,sans-serif]">Device fonts</span>
<span className="mt-1 block text-sm text-gray-600 [font-family:ui-sans-serif,system-ui,sans-serif]">Each phone and computer&apos;s own. The website uses its template&apos;s fonts.</span>
</label>
{FONT_PAIRING_IDS.map((id) => {
const p = FONT_PAIRINGS[id];
return (
<label key={id} className={option(style.fontPairing === id)} data-cc-fonts={id}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === id} onChange={() => setStyle({ ...style, fontPairing: id })} />
<span className="block text-lg font-semibold [font-family:var(--cc-font-heading)] [font-variation-settings:var(--cc-heading-variation,normal)]">{p.name}: Welcome home</span>
<span className="mt-1 block text-sm text-gray-700 [font-family:var(--cc-font-body)]">{p.feel}. <em>Sundays at 09:00.</em></span>
<span className="mt-2 block text-xs text-gray-500 [font-family:ui-sans-serif,system-ui,sans-serif]">{p.heading.family}{p.body.family !== p.heading.family && ` and ${p.body.family}`}</span>
</label>
);
})}
</div>
</fieldset>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Corners</legend>
<p className="mb-3 text-sm text-gray-600">Of buttons, cards, photos and fields.</p>
<div className="grid grid-cols-3 gap-3">
{CORNERS.map((id) => (
<label key={id} className={option((style.corners ?? "soft") === id)}>
<input type="radio" name="corners" className="sr-only" checked={(style.corners ?? "soft") === id} onChange={() => setStyle({ ...style, corners: id })} />
<span className="mb-2 block h-8 w-full bg-brand" style={{ borderRadius: CORNER_LABELS[id].radius }} aria-hidden />
<span className="block text-sm font-medium">{CORNER_LABELS[id].name}</span>
</label>
))}
</div>
</fieldset>
<Button type="submit" busy={busy} disabled={!changed}>Save</Button>
</form>
</Card>
);
}
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call } from "@/lib/api";
@@ -12,7 +13,7 @@ export function Forgot({ uid }: { uid: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
{sent ? (
@@ -32,6 +33,6 @@ export function Forgot({ uid }: { uid: string | null }) {
)}
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
</Card>
</Shell>
</PublicShell>
);
}
@@ -10,4 +10,11 @@
body {
@apply bg-gray-50 text-gray-900 antialiased;
/* 1.7.0: the church's font pairing when it has one (@crosscode/ui fonts.css), else the system font. */
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
}
h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
+7 -4
View File
@@ -1,8 +1,10 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { BrandingProvider } from "@/components/BrandingProvider";
import { loadBranding, rgbVars } from "@/lib/branding";
import { loadBranding, loadChurch, rgbVars } from "@/lib/branding";
export async function generateMetadata(): Promise<Metadata> {
const b = await loadBranding();
@@ -12,15 +14,16 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get("x-nonce") ?? undefined;
const b = await loadBranding();
const [b, church] = await Promise.all([loadBranding(), loadChurch()]);
const vars = rgbVars(b.colours.primary);
// 1.7.0: the church's font pairing and corners (fonts.css), shared with its other sites.
return (
<html lang="en-ZA">
<html lang="en-ZA" {...brandAttributes(b.style)}>
<head>
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
</head>
<body>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded, church }}>
{children}
</BrandingProvider>
</body>
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
@@ -11,7 +12,7 @@ export function Reset({ token }: { token: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
{error && <Notice tone="error">{error}</Notice>}
@@ -29,6 +30,6 @@ export function Reset({ token }: { token: string | null }) {
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
</form>
</Card>
</Shell>
</PublicShell>
);
}
@@ -1,18 +1,19 @@
"use client";
import { LogOut } from "lucide-react";
import { Card, Heading, Shell } from "@crosscode/ui";
import { Card, Heading } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { selfSignIn } from "@/lib/api";
export default function SignedOutPage() {
const branding = useBranding();
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You&apos;re signed out</Heading>
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
</Card>
</Shell>
</PublicShell>
);
}
@@ -3,7 +3,8 @@
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
import React, { useState } from "react";
import QRCode from "qrcode";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Checkbox, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { NoticeText } from "@/components/NoticeText";
import { call, type ApiError } from "@/lib/api";
@@ -82,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) {
return r;
};
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
const frame = (children: React.ReactNode) => <PublicShell><Card>{children}</Card></PublicShell>;
if (codes) {
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
@@ -4,7 +4,7 @@ import Link from "next/link";
import React, { useState } from "react";
import {
Activity, Building2, DatabaseBackup, FileText, KeyRound, LayoutDashboard, Link2, Lock, LogIn, LogOut, Mail, Menu, ScrollText,
ShieldCheck, User, Users, UserX, X, type LucideIcon,
ShieldCheck, Timer, User, Users, UserX, X, type LucideIcon,
} from "lucide-react";
import { ChurchMark } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
@@ -31,6 +31,7 @@ export const ADMIN_NAV: NavItem[] = [
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail },
{ href: "/admin/notice", label: "Privacy notice", icon: FileText },
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup },
{ href: "/admin/jobs", label: "Background jobs", icon: Timer },
{ href: "/admin/licence", label: "Licence", icon: KeyRound },
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
];
@@ -1,8 +1,10 @@
"use client";
import React, { createContext, useContext } from "react";
import type { FooterChurch } from "@crosscode/ui";
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
/** `church` (1.7.0): the profile for the shared footer, null when it couldn't be loaded. */
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean; church?: FooterChurch | null };
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
@@ -0,0 +1,16 @@
"use client";
import React from "react";
import { ChurchFooter, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
/**
* The frame of the public pages (sign in, forgot, reset, signed out, confirm email) with the
* church's shared footer (1.7.0, WEBSITE-1.0-PLAN §9): its service times, contact and links to its
* other sites, as on the Website and Cross Events.
*/
export function PublicShell({ children }: { children: React.ReactNode }) {
const branding = useBranding();
const footer = branding.church ? <ChurchFooter church={branding.church} current="accounts" privacyUrl="/privacy" /> : undefined;
return <Shell branding={branding} footer={footer}>{children}</Shell>;
}
@@ -1,9 +1,13 @@
import type { FooterChurch } from "@crosscode/ui";
/** The church's branding from the backend, for the server-rendered frame of every page. */
export type BrandingData = {
name: string;
shortName: string | null;
logoUrl: string | null;
colours: { primary: string; accent: string | null };
/** 1.7.0: the font pairing and corners (null: not picked). */
style?: { fontPairing: string | null; corners: string | null };
signupEnabled: boolean;
setupNeeded: boolean;
};
@@ -20,6 +24,17 @@ export async function loadBranding(): Promise<BrandingData> {
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
}
/** The church profile (`crosscode.church/1`) for the shared footer (1.7.0), or null while it can't be had. */
export async function loadChurch(): Promise<FooterChurch | null> {
try {
const res = await fetch(`${api}/api/church/v1`, { next: { revalidate: 60 } });
if (res.ok) return (await res.json()) as FooterChurch;
} catch {
// As loadBranding: the page works without it.
}
return null;
}
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
export function rgbVars(hex: string): { brand: string; dark: string } {
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
@@ -8,6 +8,7 @@ export const ADMIN_SECTIONS = {
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
} as const;
+3 -2
View File
@@ -13,8 +13,9 @@ curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/ma
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
```
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
Add `--central` on the central (FastPanel) server: there the agent only runs `check-ports`,
`probe-ports`, `status`, `update-agent`, and `frp-read` / `frp-write` (frps's config, from the
server's page on the Hub; agent 1.4.0+). The script installs Node 24 if needed, the agent in
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
`crosscode-agent.service`.
+75
View File
@@ -0,0 +1,75 @@
# What's new in the server agent
What each version of the Cross Code server agent changes, for whoever runs the Hub. The Hub shows
these notes on its Releases page and when you pick a version under Update agent.
<!--
How this file is used: the Cross Code Hub reads it from main every 15 minutes (release source
"Server agent", tags agent@1.2.3) and shows a section only once its version is tagged, so write it
before tagging; fixes to old sections show straight away. Each version is a "## 1.2.3" heading; add
"— urgent" (or "security") to the heading for a security or serious bug fix. Under it, lines
starting with "- " show as a list and other lines as paragraphs.
Write for the person updating servers: what the agent can now do from the Hub, and which Hub or
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
those go, and the church keeps the others. Naming every product it still has removes the whole
church, so the last product to go takes the church with it. Before, uninstalling a church's Cross
Events also removed its Accounts.
- The Hub (2.12.0 and later) uninstalls one product only on servers with this agent; older agents
can only remove the whole church.
## 1.4.0
- **frp's config from the Hub.** The agent finds frps's config (central server) or frpc's (church
server) wherever it is: the path set on the Hub, the `-c` in the systemd unit, or the usual places.
It reads INI and TOML.
- **Changing it from the Hub:** the agent checks the new file with `frp* verify`, keeps a backup,
restarts frp if asked, and puts the old file back if frp doesn't start. Secret values never leave
the server.
- **Ports checked before an install:** the Hub asks this server and the central server which ports
are free, so a new install gets ports free on both.
- Needed for frp config on a server's page and port checks (Hub 2.11.0).
## 1.3.1
- **Fix:** 1.3.0 reported itself as 1.2.0, so the Hub refused its .env jobs. It now reports its
real version. Install this instead of 1.3.0.
## 1.3.0
- **A site's .env from the Hub.** The agent reads an install's .env (secret values hidden) and
changes it: one file at a time, rebuilding the site when its frontend settings changed,
restarting it, and putting the old file back if the site doesn't answer.
- Needed for the Settings (.env) tab on an install's page (Hub 2.8.0).
## 1.2.0
- **Demo data from the Hub.** The agent loads a demo profile onto a site marked as a demo: a backup
first, then the demo data, keeping one admin account.
- Needed for demo sites (Hub 2.4.0).
## 1.1.1
- **Fix:** the server's stats now keep going while a long job runs. Before, a 30-minute install
stopped them and the Hub alerted that the server was down.
- **Fix:** 1.1.0 reported itself as 1.0.1; it now reports its real version.
## 1.1.0
- **Accounts installs.** The agent installs Accounts, and adds a product next to a church's others
on the same server (with the ports and release the Hub chose).
## 1.0.1
- **Fix:** on the central server, Check status failed (it has no `crosscode` script). It now answers
with its own stats, including whether frps is running.
## 1.0.0
- **The first server agent.** It polls the Hub every 30 seconds for signed jobs, runs the
`crosscode` script for them (install, update, status, export, uninstall), sends the results, and
sends the server's stats every minute. It listens on no port: every request goes out to the Hub.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.2.0",
"version": "1.5.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",
+17 -48
View File
@@ -1,51 +1,15 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import { paths } from "./paths";
import type { FrpSettings } from "./frp";
import { portAllowed } from "./frp";
export { parseFrpsIni, portAllowed } from "./frp";
/**
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
* The central server (AGENT-1.0-PLAN §6): the `check-ports` job after an install. Are the new
* tunnel's ports allowed by frps, open, and bound to 127.0.0.1 only? frps's config is found and
* read by ./frp.ts (INI or TOML, wherever it is).
*/
export interface FrpsSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
}
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
export function parseFrpsIni(text: string): FrpsSettings {
let inCommon = false;
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
if (!m) continue;
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
}
return out;
}
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
try {
return parseFrpsIni(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
export function portAllowed(port: number, allowPorts: string | null): boolean {
if (!allowPorts) return true;
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
const [a, b] = range.split("-").map((n) => Number(n.trim()));
if (!Number.isFinite(a)) return false;
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
});
}
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
export function parseSs(text: string): Map<number, string[]> {
const out = new Map<number, string[]>();
@@ -72,11 +36,16 @@ export interface PortCheck {
ok: boolean;
}
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
export function checkPorts(
ports: number[],
frps: Pick<FrpSettings, "proxyBindAddr" | "allowPorts"> | null,
listening: Map<number, string[]>,
configPath: string | null = null,
): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } {
const warnings: string[] = [];
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
if (!frps) warnings.push(configPath ? `frps's config isn't at ${configPath} (Hub → the central server → frp config).` : "frps's config wasn't found (Hub → the central server → frp config: set where it is).");
const bind = frps?.proxyBindAddr ?? null;
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 (frps.toml: proxyBindAddr = "127.0.0.1") in ${configPath ?? "frps's config"}.`);
const results = ports.map((port) => {
const addrs = listening.get(port) ?? [];
const allowed = portAllowed(port, frps?.allowPorts ?? null);
@@ -86,9 +55,9 @@ export function checkPorts(ports: number[], frps: FrpsSettings | null, listening
for (const r of results) {
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1 (${(listening.get(r.port) ?? []).join(", ")}).`);
}
return { ports: results, proxyBindAddr: bind, warnings };
return { ports: results, proxyBindAddr: bind, configPath, warnings };
}
export function listeningNow(): Promise<Map<number, string[]>> {
+18 -4
View File
@@ -3,7 +3,7 @@ import type { agent } from "@crosscode/contracts";
/**
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
* as an array passed straight to the process (never through a shell). Jobs the agent handles
* itself (update-agent, check-ports) have none.
* itself (update-agent, check-ports, frp-read, frp-write, probe-ports) have none.
*
* `--config <file>` is added by the runner when the job brings config; `--json` always.
*/
@@ -48,19 +48,33 @@ 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 "env-read":
return ["env", job.args.church, job.args.product];
case "env-set": {
// Each value is its own argument (no shell), so spaces and quotes in values are safe.
const out = ["env", job.args.church, job.args.product, "--file", job.args.file];
for (const [name, value] of Object.entries(job.args.set)) out.push("--set", `${name}=${value}`);
for (const name of job.args.unset) out.push("--unset", name);
if (job.args.restart) out.push("--restart");
return out;
}
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];
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
case "uninstall":
return ["uninstall", job.args.church, "--confirm", job.args.church];
// 1.5.0: only the products named go (the church keeps its others); none named: the church.
return ["uninstall", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "purge":
return ["purge", job.args.church, "--confirm", job.args.church];
return ["purge", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "status":
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
case "update-agent":
case "check-ports":
case "frp-read":
case "frp-write":
case "probe-ports":
return null;
}
}
+454
View File
@@ -0,0 +1,454 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { paths } from "./paths";
/**
* frp's config on this server (agent 1.4.0): frps's on the central server, frpc's on a church
* server. The agent finds the file itself (the path set from the Hub, else the systemd unit's
* `-c`, else a usual place), reads frp's two formats (INI and TOML), hides secret values before
* anything leaves the server, and writes a new file from the Hub the careful way: secrets put
* back, `verify`, a backup, a restart, and the old file back when the service doesn't come up.
*/
export type FrpService = "frps" | "frpc";
export type FrpSource = (typeof agent.FRP_CONFIG_SOURCES)[number];
export const serviceFor = (mode: agent.AgentMode): FrpService => (mode === "central" ? "frps" : "frpc");
// ─── Where the file is ────────────────────────────────────────────────────────
/** frps.toml, frpc.ini, frps-main.toml … */
const FRP_FILE = /^frp[A-Za-z0-9._-]*\.(ini|toml)$/;
const rememberedFile = () => path.join(paths.stateDir, "frp.json");
/** The path set from the Hub (an `frp-read` with a path), if any. */
export function rememberedPath(): string | null {
try {
const p = JSON.parse(fs.readFileSync(rememberedFile(), "utf8")).path;
return typeof p === "string" && path.isAbsolute(p) && FRP_FILE.test(path.basename(p)) ? p : null;
} catch {
return null;
}
}
export function rememberPath(p: string): void {
fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
fs.writeFileSync(rememberedFile(), `${JSON.stringify({ path: p, at: new Date().toISOString() })}\n`, { mode: 0o600 });
}
/** `-c <file>`, `-c=<file>`, `--config <file>` or `--config=<file>` in a command line. */
export function configFromCommand(argv: string): string | null {
const parts = argv.trim().split(/\s+/);
for (let i = 0; i < parts.length; i++) {
const a = parts[i]!;
const eq = /^(?:-c|--config)=(.+)$/.exec(a);
if (eq) return eq[1]!;
if ((a === "-c" || a === "--config") && parts[i + 1]) return parts[i + 1]!;
}
return null;
}
/** The config and the binary from `systemctl show <unit> -p ExecStart --value` ("{ path=… ; argv[]=… ; … }"). */
export function parseExecStart(text: string): { config: string | null; bin: string | null } {
const argv = /argv\[\]=([^;]*)/.exec(text)?.[1]?.trim() ?? text.trim();
const bin = argv.split(/\s+/)[0] || null;
return { config: configFromCommand(argv), bin: bin && bin.startsWith("/") ? bin : null };
}
function execText(cmd: string, args: string[], timeout = 10_000): Promise<{ ok: boolean; out: string; err: string; missing: boolean }> {
return new Promise((resolve) => {
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({
ok: !err, out: String(stdout ?? ""), err: String(stderr ?? "") || (err ? err.message : ""), missing: (err as NodeJS.ErrnoException | null)?.code === "ENOENT",
}));
});
}
async function fromSystemd(service: FrpService): Promise<{ config: string | null; bin: string | null }> {
const r = await execText("systemctl", ["show", service, "-p", "ExecStart", "--value"]);
return r.ok ? parseExecStart(r.out) : { config: null, bin: null };
}
/** Where frp is usually kept, in the order the agent looks. */
export function usualPlaces(service: FrpService): string[] {
const dirs = ["/etc/frp", `/etc/${service}`, "/usr/local/etc/frp", "/usr/local/frp", "/opt/frp", `/opt/${service}`, "/root/frp"];
return dirs.flatMap((d) => [`${d}/${service}.toml`, `${d}/${service}.ini`]);
}
export interface FoundConfig {
path: string | null;
source: FrpSource | null;
/** frps / frpc as the systemd unit runs it (for `verify`), else the name on PATH. */
bin: string;
looked: string[];
}
const exists = (f: string) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
let cache: { at: number; mode: agent.AgentMode; found: FoundConfig } | null = null;
/** The config this server's frp uses. The Hub's path wins (even when the file isn't there: the Hub then says so). */
export async function findConfig(mode: agent.AgentMode, opts: { fresh?: boolean } = {}): Promise<FoundConfig> {
if (!opts.fresh && cache && cache.mode === mode && Date.now() - cache.at < 5 * 60_000) return cache.found;
const service = serviceFor(mode);
const unit = await fromSystemd(service);
const bin = unit.bin ?? service;
const looked: string[] = [];
let found: FoundConfig | null = null;
const hub = rememberedPath();
// The old setting (agent 1.0–1.3) still works, for a server that set it in the unit.
const env = mode === "central" ? process.env.CROSSCODE_FRPS_INI : process.env.CROSSCODE_FRPC_INI;
if (hub) found = { path: hub, source: "hub", bin, looked };
else if (env) found = { path: env, source: "hub", bin, looked };
else {
const candidates: Array<[string, FrpSource]> = [];
if (unit.config) candidates.push([unit.config, "systemd"]);
for (const p of usualPlaces(service)) candidates.push([p, "usual-place"]);
for (const [p, source] of candidates) {
looked.push(p);
if (exists(p)) { found = { path: p, source, bin, looked: [] }; break; }
}
}
const result = found ?? { path: null, source: null, bin, looked: looked.slice(0, 20) };
cache = { at: Date.now(), mode, found: result };
return result;
}
export function forgetFound(): void {
cache = null;
}
// ─── Reading INI and TOML ─────────────────────────────────────────────────────
export type FrpFormat = "ini" | "toml";
export const formatOf = (file: string, text = ""): FrpFormat => (file.endsWith(".toml") ? "toml" : file.endsWith(".ini") ? "ini" : /^\s*\[common\]/m.test(text) ? "ini" : "toml");
interface Line {
/** `[common]`, `[[proxies]]`: the header the line is under ("" before any), with how many came before it. */
section: string;
sectionIndex: number;
key: string;
/** The value as written, after `=` (quotes kept, comments after it dropped for TOML). */
raw: string;
/** The value without quotes. */
value: string;
/** Where `raw` starts and ends in the line. */
start: number;
end: number;
}
function unquote(v: string): string {
const t = v.trim();
if ((t.startsWith('"') && t.endsWith('"') && t.length >= 2) || (t.startsWith("'") && t.endsWith("'") && t.length >= 2)) return t.slice(1, -1);
return t;
}
/** Each `key = value` line, with the section it's in. */
export function lines(text: string, format: FrpFormat): Array<Line | null> {
let section = "";
const seen = new Map<string, number>();
let sectionIndex = 0;
return text.split("\n").map((rawLine) => {
const line = rawLine.replace(/\r$/, "");
const t = line.trim();
if (!t || t.startsWith("#") || t.startsWith(";")) return null;
const header = /^(\[\[?[^\]]+\]\]?)\s*(#.*)?$/.exec(t);
if (header) {
section = header[1]!.replace(/\s+/g, "");
sectionIndex = seen.get(section) ?? 0;
seen.set(section, sectionIndex + 1);
return null;
}
const m = /^(\s*)([A-Za-z0-9_.-]+|"[^"]+")(\s*=\s*)(.*)$/.exec(line);
if (!m) return null;
let raw = m[4]!;
if (format === "toml") {
// A comment after the value (outside quotes).
let q: string | null = null;
for (let i = 0; i < raw.length; i++) {
const c = raw[i]!;
if (q) { if (c === q && raw[i - 1] !== "\\") q = null; continue; }
if (c === '"' || c === "'") q = c;
else if (c === "#") { raw = raw.slice(0, i); break; }
}
}
raw = raw.replace(/\s+$/, "");
const start = m[1]!.length + m[2]!.length + m[3]!.length;
return { section, sectionIndex, key: m[2]!.replace(/"/g, ""), raw, value: unquote(raw), start, end: start + raw.length };
});
}
export interface FrpSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
/** Ports frpc's proxies use (remote and local), or frps's own ports (bind, dashboard …). */
usedPorts: number[];
}
/** TOML's allowPorts = [{ start = 2000, end = 3000 }, { single = 3001 }] → "2000-3000,3001". */
export function tomlAllowPorts(text: string): string | null {
const m = /^\s*allowPorts\s*=\s*\[([\s\S]*?)\]\s*$/m.exec(text);
if (!m) return null;
const out: string[] = [];
for (const obj of m[1]!.matchAll(/\{([^}]*)\}/g)) {
const single = /single\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
const start = /start\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
const end = /end\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
if (single) out.push(single);
else if (start && end) out.push(`${start}-${end}`);
else if (start) out.push(start);
}
return out.length ? out.join(",") : null;
}
const PORT_KEYS = /^(remote_?port|remotePort|local_?port|localPort|bind_?port|bindPort|kcp_?bind_?port|kcpBindPort|quic_?bind_?port|quicBindPort|vhost_?http_?port|vhostHTTPPort|vhost_?https_?port|vhostHTTPSPort|dashboard_?port|admin_?port|webServer\.port|port|tcpmux_?httpconnect_?port|tcpmuxHTTPConnectPort)$/;
export function parseSettings(text: string, format: FrpFormat): FrpSettings {
const all = lines(text, format).filter((l): l is Line => !!l);
const used = new Set<number>();
for (const l of all) {
if (!PORT_KEYS.test(l.key)) continue;
// INI: `remote_port = 6000`; frpc's `local_port` of a proxy is a port on the server too.
for (const n of l.value.split(/[,\s]+/)) if (/^\d+$/.test(n)) used.add(Number(n));
}
if (format === "ini") {
const common = all.filter((l) => l.section === "[common]");
const get = (k: string) => common.find((l) => l.key === k)?.value || null;
return { proxyBindAddr: get("proxy_bind_addr"), allowPorts: get("allow_ports"), usedPorts: [...used].sort((a, b) => a - b) };
}
const top = all.filter((l) => l.section === "");
return {
proxyBindAddr: top.find((l) => l.key === "proxyBindAddr")?.value || null,
allowPorts: tomlAllowPorts(text),
usedPorts: [...used].sort((a, b) => a - b),
};
}
/** Keeps the old helper's shape (agent ≤ 1.3 tests and stats). */
export function parseFrpsIni(text: string): { proxyBindAddr: string | null; allowPorts: string | null } {
const s = parseSettings(text, "ini");
return { proxyBindAddr: s.proxyBindAddr, allowPorts: s.allowPorts };
}
// ─── Secrets ──────────────────────────────────────────────────────────────────
/** token, auth.token, dashboard_pwd, webServer.password, oidc client secret, privilege_token … */
const SECRET_KEY = /(token|pwd|passw(or)?d|secret|private_?key|privateKey|credential)/i;
export const isSecretKey = (key: string): boolean => SECRET_KEY.test(key);
/** A secret key, or an inline table with one in it (auth = { token = "…" }). */
const INLINE_SECRET = /[{,]\s*[A-Za-z0-9_.]*(token|pwd|passw(or)?d|secret|private_?key|credential)[A-Za-z0-9_]*\s*=/i;
const isSecretLine = (l: Line): boolean => isSecretKey(l.key) || INLINE_SECRET.test(l.raw);
const idOf = (l: Line) => `${l.section}#${l.sectionIndex}/${l.key}`;
const nameOf = (l: Line) => (l.section && !l.section.startsWith("[[") && l.section !== "[common]" ? `${l.section.replace(/[[\]]/g, "")}.${l.key}` : l.key);
function hiddenRaw(raw: string): string {
const t = raw.trim();
if (t.startsWith('"')) return `"${agent.FRP_HIDDEN}"`;
if (t.startsWith("'")) return `'${agent.FRP_HIDDEN}'`;
return agent.FRP_HIDDEN;
}
/** The file with secret values replaced, and their names. */
export function hideSecrets(text: string, format: FrpFormat): { content: string; hidden: string[] } {
const hidden: string[] = [];
const src = text.split("\n");
lines(text, format).forEach((l, i) => {
if (!l || !isSecretLine(l) || !l.value) return;
const line = src[i]!;
src[i] = line.slice(0, l.start) + hiddenRaw(l.raw) + line.slice(l.end);
hidden.push(nameOf(l));
});
return { content: src.join("\n"), hidden: [...new Set(hidden)].slice(0, 50) };
}
/**
* A file from the Hub with the server's secret values put back. Refused when it changes a secret,
* or has a hidden value the server's file has no value for.
*/
export function restoreSecrets(incoming: string, current: string, format: FrpFormat): { ok: true; content: string } | { ok: false; message: string } {
const now = new Map<string, Line>();
for (const l of lines(current, format)) if (l && isSecretLine(l)) now.set(idOf(l), l);
const src = incoming.split("\n");
const parsed = lines(incoming, format);
for (let i = 0; i < parsed.length; i++) {
const l = parsed[i];
if (!l || !isSecretLine(l)) continue;
const old = now.get(idOf(l));
if (l.value === agent.FRP_HIDDEN) {
if (!old) return { ok: false, message: `${nameOf(l)} shows ${agent.FRP_HIDDEN}, but the file on the server has no value for it there. Secrets are set on the server.` };
src[i] = src[i]!.slice(0, l.start) + old.raw + src[i]!.slice(l.end);
} else if (l.value && (!old || old.value !== l.value)) {
return { ok: false, message: `${nameOf(l)} is a secret: it can't be set or changed from the Hub. Change it on the server.` };
}
}
return { ok: true, content: src.join("\n") };
}
// ─── Read, write ──────────────────────────────────────────────────────────────
/** systemd's view of a unit: true / false, or null when there's no systemctl. */
export async function serviceActive(unit: string): Promise<boolean | null> {
const r = await execText("systemctl", ["is-active", unit]);
if (r.missing) return null;
return r.out.trim() === "active";
}
export interface FrpDeps {
/** For tests: systemctl and `frp* verify`. */
exec?: (cmd: string, args: string[]) => Promise<{ ok: boolean; out: string; err: string; missing: boolean }>;
wait?: (ms: number) => Promise<void>;
}
export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise<agent.FrpReadResult> {
const service = serviceFor(mode);
if (opts.path) {
if (exists(opts.path)) rememberPath(opts.path);
forgetFound();
}
const found = opts.path ? { ...(await findConfig(mode, { fresh: true })), ...(exists(opts.path) ? {} : { path: opts.path, source: "hub" as const }) } : await findConfig(mode, { fresh: true });
const exec = deps.exec ?? execText;
const running = await (async () => { const r = await exec("systemctl", ["is-active", service]); return r.missing ? null : r.out.trim() === "active"; })();
const base = { service, path: found.path, source: found.source, serviceRunning: running, readAt: new Date().toISOString() };
let text: string | null = null;
if (found.path) {
try {
const st = fs.statSync(found.path);
if (st.size > agent.FRP_CONFIG_MAX) throw new Error(`${found.path} is ${st.size} bytes; the Hub shows files up to ${agent.FRP_CONFIG_MAX}.`);
text = fs.readFileSync(found.path, "utf8");
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
}
if (text === null) {
return { ...base, found: false, format: null, content: null, hidden: [], proxyBindAddr: null, allowPorts: null, looked: found.path ? [found.path] : found.looked };
}
const format = formatOf(found.path!, text);
const settings = parseSettings(text, format);
const { content, hidden } = hideSecrets(text, format);
return {
...base, found: true, format, content, hidden,
proxyBindAddr: service === "frps" ? settings.proxyBindAddr : null,
allowPorts: service === "frps" ? settings.allowPorts : null,
};
}
export interface WriteOutcome {
status: agent.JobStatus;
message?: string;
steps: agent.ReportStep[];
result: Record<string, unknown>;
}
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
export async function writeConfig(mode: agent.AgentMode, args: { path: string; content: string; restart: boolean }, deps: FrpDeps = {}): Promise<WriteOutcome> {
const exec = deps.exec ?? execText;
const wait = deps.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
const service = serviceFor(mode);
const steps: agent.ReportStep[] = [];
const step = (name: string, outcome: agent.ReportStep["outcome"], detail?: string) => {
const at = new Date().toISOString();
steps.push({ name, startedAt: at, finishedAt: at, outcome, ...(detail ? { detail: detail.slice(0, 2000) } : {}) });
};
const refuse = (message: string): WriteOutcome => ({ status: "refused", message, steps, result: {} });
const found = await findConfig(mode, { fresh: true });
if (found.path !== args.path) return refuse(`This server's ${service} config is ${found.path ?? "not found"}, not ${args.path}. Read it again on the Hub first.`);
if (!path.basename(args.path).startsWith(service)) return refuse(`${args.path} isn't ${service}'s config (the name must start with ${service}).`);
let current: string;
try { current = fs.readFileSync(args.path, "utf8"); } catch { return refuse(`There's no file at ${args.path} to replace.`); }
const format = formatOf(args.path, current);
const restored = restoreSecrets(args.content.replace(/\r\n/g, "\n"), current, format);
if (!restored.ok) return refuse(restored.message);
const next = restored.content.endsWith("\n") ? restored.content : `${restored.content}\n`;
if (next === current) {
step("Compare", "skipped", "The file is already like this; nothing changed.");
return { status: "succeeded", message: "Nothing changed: the file is already like this.", steps, result: await readConfig(mode, {}, deps) as unknown as Record<string, unknown> };
}
const dir = path.dirname(args.path);
const tmp = path.join(dir, `.${path.basename(args.path)}.crosscode-${process.pid}${path.extname(args.path)}`);
const mode0 = fs.statSync(args.path).mode & 0o777;
fs.writeFileSync(tmp, next, { mode: mode0 });
try {
const v = await exec(found.bin, ["verify", "-c", tmp]);
if (v.missing) { step(`${service} verify`, "failed", `${found.bin} wasn't found.`); return { status: "failed", message: `${found.bin} wasn't found, so the new config couldn't be checked; nothing changed.`, steps, result: {} }; }
if (!v.ok) { step(`${service} verify`, "failed", `${v.out}\n${v.err}`.trim()); return { status: "failed", message: `${service} verify refused the new config, so nothing changed: ${(v.err || v.out).trim().slice(0, 500)}`, steps, result: {} }; }
step(`${service} verify`, "ok");
} catch (e) {
fs.rmSync(tmp, { force: true });
throw e;
}
const backups = path.join(dir, "backups");
fs.mkdirSync(backups, { recursive: true, mode: 0o700 });
const backup = path.join(backups, `${path.basename(args.path)}.${stamp()}`);
fs.copyFileSync(args.path, backup);
fs.chmodSync(backup, mode0);
fs.renameSync(tmp, args.path);
step("Replace the config", "ok", `Backup: ${backup}`);
if (!args.restart) {
step(`Restart ${service}`, "skipped", "Not asked: the new config is used when frp next starts.");
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
}
const restart = await exec("systemctl", ["restart", service]);
await wait(3000);
const up = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
if (restart.ok && up) {
step(`Restart ${service}`, "ok");
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
}
step(`Restart ${service}`, "failed", restart.err || `${service} isn't running after the restart.`);
fs.copyFileSync(backup, args.path);
await exec("systemctl", ["restart", service]);
await wait(3000);
const back = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
step("Put the old config back", back ? "rolled-back" : "failed", back ? `${service} runs with the old config again.` : `${service} isn't running with the old config either: look at it on the server (journalctl -u ${service}).`);
return {
status: back ? "rolled-back" : "failed",
message: back ? `${service} didn't start with the new config, so the old one was put back.` : `${service} didn't start with the new config, and isn't running after putting the old one back either.`,
steps,
result: { ...(await readConfig(mode, {}, deps)), backup },
};
}
// ─── Free ports (probe-ports) ─────────────────────────────────────────────────
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
export function portAllowed(port: number, allowPorts: string | null): boolean {
if (!allowPorts) return true;
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
const [a, b] = range.split("-").map((n) => Number(n.trim()));
if (!Number.isFinite(a)) return false;
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
});
}
export function probePorts(ports: number[], mode: agent.AgentMode, settings: FrpSettings | null, listening: Map<number, string[]>, configPath: string | null): agent.ProbePortsResult {
const used = new Set(settings?.usedPorts ?? []);
return {
configPath,
ports: ports.map((port) => {
const addrs = listening.get(port);
if (addrs?.length) return { port, free: false, reason: `In use: something listens on ${[...new Set(addrs)].join(", ")}.` };
if (mode === "central" && settings && !portAllowed(port, settings.allowPorts)) return { port, free: false, reason: "Not in frps's allow_ports." };
if (used.has(port)) return { port, free: false, reason: `Used in ${mode === "central" ? "frps" : "frpc"}'s config.` };
return { port, free: true, reason: null };
}),
};
}
/** The settings of the config this server uses, or null when there's none. */
export async function currentSettings(mode: agent.AgentMode): Promise<{ path: string | null; settings: FrpSettings | null }> {
const found = await findConfig(mode);
if (!found.path) return { path: null, settings: null };
try {
const text = fs.readFileSync(found.path, "utf8");
return { path: found.path, settings: parseSettings(text, formatOf(found.path, text)) };
} catch {
return { path: found.path, settings: null };
}
}
+23 -3
View File
@@ -2,7 +2,8 @@ import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { encryptExport } from "@crosscode/contracts/signing";
import { checkPorts, listeningNow, readFrps } from "./central";
import { checkPorts, listeningNow } from "./central";
import { currentSettings, findConfig, probePorts, readConfig, writeConfig } from "./frp";
import { crosscodeArgs } from "./command";
import type { AgentConfig, Keys } from "./config";
import { type HubClient, HubRequestError } from "./hub";
@@ -153,10 +154,25 @@ export class Agent {
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
}
case "check-ports": {
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
const { path: configPath, settings } = await currentSettings("central");
const res = checkPorts(job.args.ports, settings, await listeningNow(), configPath);
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-read": {
const result = await readConfig(this.deps.config.mode, { path: job.args.path });
const message = result.found ? undefined : `No ${result.service} config found${result.path ? ` at ${result.path}` : ""}.`;
return { status: result.found ? "succeeded" : "failed", steps: [], result: result as unknown as Record<string, unknown>, message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-write": {
const w = await writeConfig(this.deps.config.mode, job.args);
return { status: w.status, steps: w.steps, result: w.result, message: w.message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "probe-ports": {
const { path: configPath, settings } = await currentSettings(this.deps.config.mode);
const result = probePorts(job.args.ports, this.deps.config.mode, settings, await listeningNow(), configPath);
return { status: "succeeded", steps: [], result: result as unknown as Record<string, unknown>, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "export":
return await this.runExport(job, limit);
case "status":
@@ -181,7 +197,11 @@ export class Agent {
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
if (this.deps.run) return this.deps.run(args, job);
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
return (async () => {
// crosscode edits frpc's config on installs: tell it where the file is (agent 1.4.0).
const frpc = this.deps.config.mode === "church" ? (await findConfig("church").catch(() => null))?.path : null;
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit, env: frpc ? { FRPC_INI: frpc } : {} });
})();
}
/**
-2
View File
@@ -15,8 +15,6 @@ export const paths = {
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
/** frps.ini on the central server. */
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
/** The churches on a church server. */
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
};
+3 -1
View File
@@ -27,6 +27,8 @@ export interface RunOptions {
sealedConfig?: agent.Sealed | null;
x25519Pem: string;
timeLimitMinutes: number;
/** Extra environment for crosscode (FRPC_INI). */
env?: Record<string, string>;
/** For tests. */
bin?: string;
}
@@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
const child = spawn(opts.bin ?? paths.crosscode, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
env: { ...process.env, ...opts.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
});
let timedOut = false;
const timer = setTimeout(() => {
+5 -4
View File
@@ -3,7 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { agent } from "@crosscode/contracts";
import { readFrps } from "./central";
import { currentSettings, serviceActive } from "./frp";
import { paths } from "./paths";
/**
@@ -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.2.0";
export const AGENT_VERSION = "1.5.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
@@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentSt
frpcRunning,
processes,
};
const frp = await currentSettings(mode).catch(() => ({ path: null, settings: null }));
stats.frpConfigPath = frp.path;
if (mode === "central") {
const frps = readFrps();
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
stats.central = { proxyBindAddr: frp.settings?.proxyBindAddr ?? null, allowPorts: frp.settings?.allowPorts ?? null, frpsRunning: await serviceActive("frps") };
}
return stats;
}
+13
View File
@@ -36,6 +36,10 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
// 1.5.0: one product of the church.
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope", products: ["events"] } }))).toEqual(["uninstall", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope", products: ["events"] } }))).toEqual(["purge", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] } }), { exportFile: "/x/e.zip" })).toEqual(["export", "hope", "accounts", "--out", "/x/e.zip"]);
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
});
@@ -45,6 +49,15 @@ describe("crosscode arguments for each job", () => {
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
expect(crosscodeArgs(parsed({ type: "env-read", args: { church: "hope", product: "accounts" } }))).toEqual(["env", "hope", "accounts"]);
expect(crosscodeArgs(parsed({
type: "env-set",
args: { church: "hope", product: "events", file: "backend/.env", set: { FRONTEND_URL: "https://events.hope.co.za", ORG_NAME: "Hope; rm -rf /" }, unset: ["OLD"], restart: true },
}))).toEqual(["env", "hope", "events", "--file", "backend/.env", "--set", "FRONTEND_URL=https://events.hope.co.za", "--set", "ORG_NAME=Hope; rm -rf /", "--unset", "OLD", "--restart"]);
expect(() => parsed({ type: "env-set", args: { church: "hope", product: "events", file: "backend/.env", set: { JWT_SECRET: "x" }, unset: [], restart: false } })).toThrow();
});
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"]);
+167
View File
@@ -0,0 +1,167 @@
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import {
configFromCommand, findConfig, forgetFound, hideSecrets, parseExecStart, parseSettings, probePorts, readConfig, restoreSecrets, writeConfig,
} from "../src/frp";
import { tempState } from "./helpers";
const H = agent.FRP_HIDDEN;
const TOML = `bindPort = 7000
proxyBindAddr = "127.0.0.1"
auth.token = "s3cret-token" # the shared token
allowPorts = [
{ start = 20000, end = 29999 },
{ single = 3001 },
]
[webServer]
port = 7500
password = 'dash-pass'
`;
const FRPC_INI = `[common]
server_addr = 203.0.113.10
server_port = 7000
token = abc123
[hope-events-web]
type = tcp
local_ip = 127.0.0.1
local_port = 20010
remote_port = 20010
`;
const noSystemd = async () => ({ ok: false, out: "", err: "", missing: true });
describe("finding frp's config", () => {
it("reads -c from the systemd unit", () => {
expect(configFromCommand("/usr/local/bin/frps -c /usr/local/frp/frps.toml")).toBe("/usr/local/frp/frps.toml");
expect(configFromCommand("/usr/bin/frps --config=/etc/frps/frps.ini")).toBe("/etc/frps/frps.ini");
expect(configFromCommand("/usr/bin/frps")).toBeNull();
expect(parseExecStart("{ path=/usr/local/bin/frps ; argv[]=/usr/local/bin/frps -c /opt/frp/frps.toml ; ignore_errors=no ; start_time=[n/a] }"))
.toEqual({ config: "/opt/frp/frps.toml", bin: "/usr/local/bin/frps" });
});
it("the path from the Hub wins, and is remembered", async () => {
const dir = tempState();
const file = path.join(dir, "frps.toml");
fs.writeFileSync(file, TOML);
forgetFound();
const exec = async () => ({ ok: true, out: "active\n", err: "", missing: false });
const r = await readConfig("central", { path: file }, { exec });
expect(r).toMatchObject({ found: true, source: "hub", path: file, format: "toml", proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001", serviceRunning: true });
forgetFound();
expect((await findConfig("central", { fresh: true })).path).toBe(file);
});
it("a path that isn't there is reported, not remembered", async () => {
const dir = tempState();
forgetFound();
const r = await readConfig("central", { path: path.join(dir, "nope", "frps.ini") }, { exec: noSystemd });
expect(r).toMatchObject({ found: false, content: null });
expect(fs.existsSync(path.join(dir, "frp.json"))).toBe(false);
});
});
describe("frp settings, INI and TOML", () => {
it("TOML", () => {
expect(parseSettings(TOML, "toml")).toMatchObject({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001" });
expect(parseSettings(TOML, "toml").usedPorts).toEqual(expect.arrayContaining([7000, 7500]));
});
it("INI: frpc's tunnels use their ports", () => {
expect(parseSettings(FRPC_INI, "ini").usedPorts).toEqual([20010]);
});
});
describe("secrets never leave the server", () => {
it("are hidden in TOML and INI, keeping the quotes", () => {
const t = hideSecrets(TOML, "toml");
expect(t.content).toContain(`auth.token = "${H}" # the shared token`);
expect(t.content).toContain(`password = '${H}'`);
expect(t.content).not.toMatch(/s3cret|dash-pass/);
expect(t.hidden).toEqual(["auth.token", "webServer.password"]);
const i = hideSecrets(FRPC_INI, "ini");
expect(i.content).toContain(`token = ${H}`);
expect(i.content).not.toContain("abc123");
});
it("in inline tables too", () => {
expect(hideSecrets(`auth = { method = "token", token = "zzz" }\n`, "toml").content).not.toContain("zzz");
});
it("are put back on write, and can't be changed from the Hub", () => {
const shown = hideSecrets(TOML, "toml").content.replace("bindPort = 7000", "bindPort = 7001");
const back = restoreSecrets(shown, TOML, "toml");
expect(back.ok && back.content).toBe(TOML.replace("bindPort = 7000", "bindPort = 7001"));
expect(restoreSecrets(shown.replace(`"${H}"`, '"new"'), TOML, "toml")).toMatchObject({ ok: false, message: expect.stringMatching(/auth.token is a secret/) });
expect(restoreSecrets(`${shown}\n[extra]\ntoken = "${H}"\n`, TOML, "toml")).toMatchObject({ ok: false });
});
});
describe("writing the config", () => {
const setup = () => {
const dir = tempState();
const file = path.join(dir, "frps.toml");
fs.writeFileSync(file, TOML);
fs.writeFileSync(path.join(dir, "frp.json"), JSON.stringify({ path: file }));
forgetFound();
return { dir, file };
};
const shown = () => hideSecrets(TOML, "toml").content;
it("verify, backup, replace, restart", async () => {
const { dir, file } = setup();
const calls: string[] = [];
const exec = async (cmd: string, args: string[]) => { calls.push(`${cmd} ${args.join(" ")}`); return { ok: true, out: "active", err: "", missing: false }; };
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("succeeded");
expect(fs.readFileSync(file, "utf8")).toContain("bindPort = 7001");
expect(fs.readFileSync(file, "utf8")).toContain("s3cret-token");
expect(fs.readdirSync(path.join(dir, "backups"))).toHaveLength(1);
expect(calls.some((c) => / verify -c /.test(c))).toBe(true);
expect(calls).toContain("systemctl restart frps");
expect(JSON.stringify(r.result)).not.toContain("s3cret");
});
it("verify refuses: nothing changes", async () => {
const { file } = setup();
const exec = async (cmd: string) => ({ ok: cmd === "systemctl", out: "", err: "bad key", missing: false });
const r = await writeConfig("central", { path: file, content: "nonsense = [", restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("failed");
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
});
it("frps doesn't come back: the old file is put back", async () => {
const { file } = setup();
let restarts = 0;
const exec = async (_cmd: string, args: string[]) => {
if (args[0] === "restart") restarts++;
if (args[0] === "is-active") return { ok: true, out: restarts >= 2 ? "active" : "failed", err: "", missing: false };
return { ok: true, out: "", err: "", missing: false };
};
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("rolled-back");
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
});
it("only the file the agent uses", async () => {
const { dir } = setup();
const r = await writeConfig("central", { path: path.join(dir, "frpc.toml"), content: "x = 1", restart: false }, { exec: noSystemd });
expect(r.status).toBe("refused");
});
});
describe("free ports before an install", () => {
it("central: not listening and inside allow_ports", () => {
const listening = new Map([[20001, ["0.0.0.0"]]]);
const r = probePorts([20000, 20001, 30000], "central", parseSettings(TOML, "toml"), listening, "/etc/frp/frps.toml");
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20000, true], [20001, false], [30000, false]]);
});
it("church: not listening and not in frpc's tunnels", () => {
const r = probePorts([20010, 20011], "church", parseSettings(FRPC_INI, "ini"), new Map(), "/etc/frp/frpc.ini");
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20010, false], [20011, true]]);
});
it("with no config found, listening is all it can check", () => {
expect(probePorts([20010], "central", null, new Map(), null).ports[0]!.free).toBe(true);
});
});
+68
View File
@@ -5,6 +5,74 @@ 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/).
## [3.6.1] - 2026-11-20
### Fixed
- **Uploading a logo or favicon under Settings → Branding failed on some servers** with "The logo was
uploaded, but the site can't show it yet". The upload worked, but on a server whose proxy has a
rule for file extensions (static-file caching) every `/api/…` path ending in `.png`, `.ico`,
`.pdf`, `.json` and so on went to the site (Next.js), which answered 404. So the check after the
upload failed, as did pictures, certificate PDFs and `/api/v2/openapi.json`. Two changes:
- The site passes `/api/*` and `/uploads/*` that reach it on to the backend
(`next.config.ts` rewrites, `beforeFiles`). New frontend setting `BACKEND_INTERNAL_URL`
(`http://127.0.0.1:<apiPort>`, added to `.env.production` on deploy). Unset, nothing is
passed on, as before. The end-to-end tests' `E2E_API_PROXY` uses the same rewrites.
- The nginx site the installers write (and DEPLOYMENT.md) sends `/api/` and `/uploads/` to the
backend with `location ^~`, so no regex location can take them. Existing servers keep their
nginx file: change it by hand (DEPLOYMENT.md §4).
## [3.6.0] - 2026-11-20
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
### Added
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
## [3.5.0] - 2026-11-20
### Fixed
- **After "Load demo data" nobody could sign in** ("Sign-in isn't available right now",
`ACCOUNTS_UNAVAILABLE`). `scripts/set-demo.js` emptied `ProductLink` (it keeps only a few tables)
but kept `AppSetting`, so the site stayed in Accounts mode with no Accounts link, and
`accounts_auto_connected` stopped it reconnecting. Demo data now keeps `ProductLink` and
`LinkNonce`, and a site in Accounts mode without a link connects to the Accounts the Hub lists at
its next heartbeat whatever happened before (a site on its own sign-in still keeps an admin's
Disconnect).
### Added
- Heartbeat `stats.signIn` (contracts 1.13.0): the sign-in mode, the linked Accounts (install id and
address) and the last failure to start or finish a sign-in (`accounts_last_signin_error`, cleared
by the next sign-in that works). The Hub 2.9.0 alerts on it.
## [3.4.0] - 2026-11-20
### Added
- **Background jobs are switched on and off from Settings → Background jobs.** Each job has a
switch and a Schedule button (presets or a cron expression). The choice is saved in the database
(`AppSetting` `job_overrides`), wins over the .env (the job's own flag such as
`WAITLIST_JOB_ENABLED`, and `JOB_SCHEDULE_<NAME>`), and applies straight away: the queue is
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
off elsewhere is skipped). "use the .env" goes back to what the server says.
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
### Changed
- "Run now" also works for a job that's switched off.
## [3.3.0] - 2026-11-20
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
+26 -15
View File
@@ -127,13 +127,17 @@ server {
access_log /var/log/nginx/hope-events.access.log hope_proxy;
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
@@ -147,7 +151,10 @@ server {
```
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
unchanged (frps picks the site by its host name). Send every path through as it is: no
`location ~* \.(png|css|js…)$` caching rules for this site on the VPS, which would send
`/api/uploads/…/logo.png` to the site instead of the backend. (Since 3.6.1 the site passes such
requests on to the backend itself, but they're slower that way.) For nginx on the VPS, roughly:
```nginx
server {
@@ -188,13 +195,17 @@ server {
client_max_body_size 25m;
access_log /var/log/nginx/hope-events.access.log hope_proxy;
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
+28
View File
@@ -12,6 +12,34 @@ 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".
-->
## 3.6.1
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
the site can't show it yet", depending on how the server is set up. Uploaded pictures, certificate
downloads and the like now show on those servers too.
## 3.6.0
- **People's details are checked every night.** Cross Events compares everyone's name, email,
phone and news choices with their church account and fixes any that are out of date, and handles
accounts that were deleted, in case a change never reached this site. You can see it, run it or
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
## 3.5.0
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
sign-in (Accounts). Demo data keeps it now, and a site that lost it connects again by itself
within about 15 minutes of updating.
- When signing in fails, Cross Code is told why, so it can help sooner.
## 3.4.0
- **Switch background jobs on and off yourself.** Settings → Background jobs has a switch for each
job (reminders, backups, the daily summary and so on) and lets you change when it runs, with ready
choices such as "every 15 minutes" or "daily at 07:00". It works straight away, no restart needed,
and one click puts a job back to how the server normally runs it.
- **Run now** works for a job that's switched off too, for when you want it once.
## 3.3.0
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.3.0",
"version": "3.6.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+3
View File
@@ -76,6 +76,9 @@ const LIST_ONLY = process.argv.includes('--list');
const KEEP_TABLES = new Set([
'_prisma_migrations', 'AppSetting', 'User',
'SecurityEvent', 'PasswordReset', 'TwoFactorChallenge', 'TrustedDevice',
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
// its link nobody can sign in). Their feeds are data and go.
'ProductLink', 'LinkNonce',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -7,12 +7,16 @@
import { connectTo } from '../links/connect';
import { linkedProducts } from '../links/store';
import { accountsLink } from './client';
import { getSetting, setSetting } from './mode';
import { getSetting, setSetting, viaAccounts } from './mode';
export const AUTO_KEY = 'accounts_auto_connected';
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
if (await getSetting(AUTO_KEY)) return 'skipped';
// 3.5.0: a site that signs in through Accounts but has lost its link (before 3.5.0, loading demo
// data deleted it) can't sign anyone in, so it reconnects whatever was done before. A site on its
// own sign-in keeps an admin's Disconnect.
const stranded = (await viaAccounts()) && !(await accountsLink());
if ((await getSetting(AUTO_KEY)) && !stranded) return 'skipped';
if (await accountsLink()) {
await setSetting(AUTO_KEY, now.toISOString());
return 'skipped';
@@ -0,0 +1,102 @@
/**
* The nightly people check (3.6.0, contracts 1.14.0 `people.check`, Accounts 1.5.0): Accounts tells
* Events about every change (`user.updated`, `user.deleted`), retried for about a week; this catches
* whatever never arrived (a link that was down, as after a demo load before 3.5.0). For everyone here
* with an account it asks Accounts, a page at a time, and:
*
* - updates the local copy when the profile differs (as `user.updated` does);
* - handles a deleted account as `user.deleted` does (anonymised, or deferred while the person has a
* registration for an event that hasn't ended);
* - only counts people Accounts doesn't know through this site (`unknown`). When most of a page is
* unknown, Events is probably linked to the wrong Accounts: the check stops and fails, so it
* shows on Background jobs and the Hub, and nothing is changed for those people.
*/
import { PEOPLE_CHECK_MAX, peopleCheckReplySchema, type PeopleCheckReply, type Profile } from '@crosscode/contracts';
import { accounts, accountsLink } from './client';
import { handleAccountsCall } from './calls';
import { viaAccounts } from './mode';
import { recordSignInError } from './status';
import { updateLocalCopy } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
type Local = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
export type PeopleCheckResult = { checked: number; updated: number; deleted: number; deferred: number; deactivated: number; unknown: number } | { skipped: string };
/** Asks Accounts about these subs (tests replace it). */
export type Ask = (subs: string[]) => Promise<PeopleCheckReply>;
const defaultAsk: Ask = async (subs) => {
const auth = await accounts();
const raw = await auth.request({ type: 'people.check', actor: null, subs }, { timeoutMs: 120000 });
return peopleCheckReplySchema.parse(raw);
};
/** Whether the local copy already says what the profile says (only what Events keeps). */
export function sameAsLocal(u: Local, p: Profile): boolean {
return u.name === p.name
&& u.email.toLowerCase() === p.email.toLowerCase()
&& (u.phoneNumber ?? null) === (p.phone_number ?? null)
&& u.newsEmail === p.news_consent.email
&& u.newsWhatsApp === p.news_consent.whatsapp;
}
/** More than this share of a page unknown (with at least MIN_FOR_ALARM people) stops the check. */
const UNKNOWN_ALARM = 0.5;
const MIN_FOR_ALARM = 10;
export async function runPeopleCheck(opts: { ask?: Ask; pageSize?: number } = {}): Promise<PeopleCheckResult> {
if (!(await viaAccounts())) return { skipped: 'This site uses its own sign-in.' };
if (!(await accountsLink())) return { skipped: 'Accounts isn\'t linked.' };
const ask = opts.ask ?? defaultAsk;
const size = Math.min(opts.pageSize ?? PEOPLE_CHECK_MAX, PEOPLE_CHECK_MAX);
const out = { checked: 0, updated: 0, deleted: 0, deferred: 0, deactivated: 0, unknown: 0 };
let cursor: string | undefined;
for (;;) {
const page: Local[] = await prisma.user.findMany({
where: { accountId: { not: null } },
select: { id: true, accountId: true, name: true, email: true, phoneNumber: true, newsEmail: true, newsWhatsApp: true },
orderBy: { id: 'asc' },
take: size,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
});
if (!page.length) break;
cursor = page[page.length - 1]!.id;
const bySub = new Map(page.map((u) => [u.accountId, u]));
let reply: PeopleCheckReply;
try {
reply = await ask(page.map((u) => u.accountId));
} catch (e) {
// Accounts before 1.5.0 doesn't know people.check: nothing to do until it's updated.
const err = e as { code?: string; message?: string };
if (err.code === 'INVALID_REQUEST' && /\btype\b/.test(err.message ?? '')) return { skipped: 'The church\'s Accounts is older than 1.5.0, which this check needs.' };
throw e;
}
const unknown = reply.people.filter((p) => p.status === 'unknown').length;
if (page.length >= MIN_FOR_ALARM && unknown / page.length > UNKNOWN_ALARM) {
const message = `Accounts doesn't know ${unknown} of ${page.length} people here: is this site linked to the church's own Accounts? Nothing was changed for them.`;
await recordSignInError('PEOPLE_UNKNOWN', message);
throw new Error(message);
}
for (const p of reply.people) {
const u = bySub.get(p.sub);
if (!u) continue; // not one we asked about
out.checked++;
if (p.status === 'unknown') { out.unknown++; continue; }
if (p.status === 'deleted') {
const r = await handleAccountsCall({ type: 'user.deleted', sub: p.sub } as never) as { status?: string };
if (r.status === 'deferred') out.deferred++; else out.deleted++;
continue;
}
if (p.status === 'deactivated') out.deactivated++;
if (p.profile && !sameAsLocal(u, p.profile)) {
await updateLocalCopy(u.id, p.profile);
out.updated++;
}
}
if (page.length < size) break;
}
return out;
}
+9 -2
View File
@@ -20,6 +20,7 @@ import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
import { clearSignInError, recordSignInError } from './status';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
@@ -144,7 +145,10 @@ async function startSignIn(req: Request, res: Response) {
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
const failed = e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED';
// 3.5.0: the reason goes to the Hub with the next heartbeat (the page only says "try again").
await recordSignInError(failed, (e as Error).message);
return problem(res, failed, returnTo);
}
}
@@ -158,7 +162,8 @@ async function callback(req: Request, res: Response) {
let auth;
try {
auth = await accounts();
} catch {
} catch (e) {
await recordSignInError('ACCOUNTS_UNAVAILABLE', (e as Error).message);
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
@@ -168,8 +173,10 @@ async function callback(req: Request, res: Response) {
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
if (code !== 'NO_PENDING') await recordSignInError('FINISH_FAILED', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
await clearSignInError();
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
@@ -0,0 +1,32 @@
/**
* How people sign in here, for the Hub (3.5.0, heartbeat `stats.signIn`, contracts 1.13.0): the
* mode, the Accounts this site is linked to, and the last sign-in that failed to start or finish.
* A site in `accounts` mode without a link can't sign anyone in; the Hub raises an alert for it.
*/
import { accountsLink } from './client';
import { authMode, getSetting, setSetting } from './mode';
export const LAST_ERROR_KEY = 'accounts_last_signin_error';
type LastError = { at: string; code: string; message: string };
/** Keeps the last failure (a code and a sentence; never tokens or cookies). */
export async function recordSignInError(code: string, message: string, now = new Date()): Promise<void> {
const value: LastError = { at: now.toISOString(), code: code.slice(0, 60), message: message.replace(/\s+/g, ' ').slice(0, 500) };
await setSetting(LAST_ERROR_KEY, JSON.stringify(value)).catch(() => {});
}
/** A sign-in that worked clears it. */
export async function clearSignInError(): Promise<void> {
if (await getSetting(LAST_ERROR_KEY).catch(() => null)) await setSetting(LAST_ERROR_KEY, null).catch(() => {});
}
export async function signInStatus(): Promise<{ mode: 'local' | 'accounts'; accounts: { installId: string; url: string } | null; lastError: LastError | null }> {
const [mode, link, raw] = await Promise.all([authMode(), accountsLink(), getSetting(LAST_ERROR_KEY).catch(() => null)]);
let lastError: LastError | null = null;
try {
const parsed = raw ? JSON.parse(raw) : null;
if (parsed && typeof parsed.at === 'string' && typeof parsed.code === 'string' && typeof parsed.message === 'string') lastError = parsed;
} catch { /* an unreadable value is no error */ }
return { mode, accounts: link ? { installId: link.installId, url: link.url } : null, lastError };
}
@@ -31,4 +31,22 @@ const runJobNow = async (req, res) => {
}
};
module.exports = { listJobs, runJobNow };
// @desc Switch a background job on or off, or change its schedule (3.4.0). Wins over the .env;
// null for either goes back to the .env.
// @route PUT /api/admin/jobs/:name
// @access Private/Admin
const updateJob = async (req, res) => {
try {
const body = req.body || {};
const choice = await jobs.setOverride(req.params.name, { enabled: body.enabled, cron: body.cron });
logAdminAction({
actorId: req.user.id, actorRole: req.user.role, action: 'job_settings_changed',
targetType: 'Job', targetId: req.params.name, metadata: { enabled: body.enabled, cron: body.cron }, ip: getClientIp(req),
});
res.json({ name: req.params.name, override: choice });
} catch (error) {
res.status(error.statusCode || 500).json({ message: safeErrorMessage(error) });
}
};
module.exports = { listJobs, runJobNow, updateJob };
+3
View File
@@ -145,10 +145,13 @@ async function stats(now = new Date()) {
const live = await liveNow(now).catch(() => undefined);
const campusesOn = await campusesEnabled().catch(() => false);
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
// 3.5.0: how people sign in (the Hub flags a site in Accounts mode without a link, or failing).
const signIn = await require('../accounts/status').signInStatus().catch(() => undefined);
return {
users,
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
...(live ? { live } : {}),
...(signIn ? { signIn } : {}),
registrations: { last30d: regs30, total: regsTotal },
tickets: { last30d: tickets30, total: ticketsTotal },
checkIns: { last30d: checkIns30 },
+166 -45
View File
@@ -10,7 +10,10 @@
*
* Each job can be switched off with its env flag (e.g. WAITLIST_JOB_ENABLED=false), and
* its schedule changed with JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*\/5 * * * *").
* JOBS_ENABLED=false turns all of them off (used by the end-to-end tests).
* 3.4.0: an admin can do both on the Background jobs page; their choice is kept in the database
* (AppSetting job_overrides), wins over the .env and takes effect straight away (other processes
* within 30 seconds).
* JOBS_ENABLED=false still turns all of them off (used by the end-to-end tests).
* If the queue can't start (e.g. the database user can't create the pgboss schema), the
* same jobs run on in-process timers instead, as before.
*/
@@ -95,6 +98,11 @@ const JOBS = [
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
},
{
// 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts).
name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED',
run: () => require('../accounts/peopleCheck').runPeopleCheck(),
},
{
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
@@ -117,13 +125,69 @@ const flag = (name, def = true) => {
return v === undefined || v === '' ? def : String(v).toLowerCase() !== 'false';
};
/** Whether a job is switched on (JOBS_ENABLED and its own flag). */
function isEnabled(job) {
return flag('JOBS_ENABLED') && (!job.env || flag(job.env));
// ─── The admin's choices (3.4.0) ──────────────────────────────────────────────
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30 * 1000;
/** { [job name]: { enabled?: boolean, cron?: string } } from the database, cached here. */
let overrides = {};
let overridesAt = 0;
/** Reads the admin's choices again when the copy here is older than 30 s (or with `force`). */
async function loadOverrides(force = false) {
if (!force && overridesAt && Date.now() - overridesAt < OVERRIDES_TTL_MS) return overrides;
try {
const prisma = require('../config/db');
const row = await prisma.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
overridesAt = Date.now();
} catch (e) {
// Keep the last copy (or none): the .env still applies.
if (force) console.warn('[jobs] Could not read the job overrides:', e?.message || e);
}
return overrides;
}
/** A job's cron schedule, with any JOB_SCHEDULE_<NAME> override (checked). */
/** Sets the cached choices (tests, and after saving). */
function setOverridesForTest(value) {
overrides = value || {};
overridesAt = Date.now();
}
/** A cron expression with five fields that cron-parser understands. */
function isCron(cron) {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
CronExpressionParser.parse(cron, { tz: TIMEZONE });
return true;
} catch {
return false;
}
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
function envEnabled(job) {
return !job.env || flag(job.env);
}
/** Whether a job is switched on: JOBS_ENABLED=false turns all off; then the admin's choice; then its env flag. */
function isEnabled(job) {
if (!flag('JOBS_ENABLED')) return false;
const o = overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** A job's cron schedule: the admin's choice, else JOB_SCHEDULE_<NAME>, else its default. */
function cronFor(job) {
const o = overrides[job.name];
if (o && isCron(o.cron)) return o.cron;
return envCronFor(job);
}
/** A job's cron schedule from the .env (JOB_SCHEDULE_<NAME>, checked), else its default. */
function envCronFor(job) {
const override = process.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (override) {
try {
@@ -208,31 +272,75 @@ const timers = new Map();
// Timer mode keeps its own short history so the admin page still has something to show.
const timerHistory = new Map();
/** One job on an in-process timer while it's on. The schedule and the switch are read each time. */
function startTimer(job) {
const scheduleNext = () => {
if (!isEnabled(job)) { timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(job)).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
await loadOverrides();
if (!isEnabled(job)) { timers.delete(job.name); return; }
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
function startTimers(jobs) {
mode = 'timers';
for (const job of jobs) {
const cron = cronFor(job);
const scheduleNext = () => {
const delay = Math.max(1000, nextRun(cron).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
for (const job of jobs) startTimer(job);
console.log(`[jobs] Running ${jobs.filter(isEnabled).length} job(s) on in-process timers.`);
}
/** Puts one job's schedule in line with its switch and schedule now (queue or timers). */
async function applyJob(job) {
if (mode === 'queue' && boss) {
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
} else if (mode === 'timers') {
clearTimeout(timers.get(job.name));
timers.delete(job.name);
startTimer(job);
}
console.log(`[jobs] Running ${jobs.length} job(s) on in-process timers.`);
}
const badRequest = (message) => Object.assign(new Error(message), { statusCode: 400 });
/**
* Saves an admin's choice for one job and applies it straight away. `enabled` / `cron`: a value
* wins over the .env; null goes back to the .env; undefined leaves it as it is.
* @returns the job's choices now ({ enabled, cron }, null where the .env applies)
*/
async function setOverride(name, { enabled, cron } = {}) {
const job = JOBS.find(j => j.name === name);
if (!job) throw Object.assign(new Error('Unknown job'), { statusCode: 404 });
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw badRequest('"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim()))) {
throw badRequest('That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const prisma = require('../config/db');
const all = { ...(await loadOverrides(true)) };
const entry = { ...(all[name] || {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = cron.trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await prisma.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
setOverridesForTest(all);
await applyJob(job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/**
@@ -240,12 +348,13 @@ function startTimers(jobs) {
* @returns {Promise<'queue'|'timers'|'off'>}
*/
async function startJobs() {
const enabled = JOBS.filter(isEnabled);
if (!flag('JOBS_ENABLED')) {
console.log('[jobs] All background jobs disabled by env JOBS_ENABLED=false');
mode = 'off';
return mode;
}
await loadOverrides(true);
const enabled = JOBS.filter(isEnabled);
try {
const PgBoss = require('pg-boss');
boss = new PgBoss({ connectionString: process.env.DATABASE_URL, schema: SCHEMA, application_name: 'hope-events-jobs' });
@@ -257,19 +366,21 @@ async function startJobs() {
// stately: at most one waiting and one running, so a slow run never piles up.
await boss.createQueue(job.name, { policy: 'stately', retryLimit: 2, retryDelay: 60, expireInSeconds: 60 * 60 });
}
if (isEnabled(job)) {
await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
await boss.work(job.name, async () => {
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
} else {
await boss.unschedule(job.name).catch(() => {});
}
// 3.4.0: every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
const list = Array.isArray(batch) ? batch : [batch];
await loadOverrides();
// Switched off (perhaps in another process) after this run was scheduled: skip it. "Run now" still runs.
if (!isEnabled(job) && !list.some(j => j?.data?.manual)) return { skipped: 'switched off' };
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
}
// One-off tasks: any number can wait and run (unlike the stately scheduled jobs).
for (const name of Object.keys(TASKS)) {
@@ -295,7 +406,7 @@ async function startJobs() {
console.warn('[jobs] Job queue unavailable, falling back to timers:', e?.message || e);
if (boss) { try { await boss.stop({ graceful: false }); } catch { /* ignore */ } }
boss = null;
startTimers(enabled);
startTimers(JOBS);
}
return mode;
}
@@ -318,8 +429,9 @@ async function runNow(name) {
err.statusCode = 404;
throw err;
}
if (mode === 'queue' && isEnabled(job)) {
const id = await boss.send(job.name, null, { singletonKey: `${job.name}-manual` });
if (mode === 'queue' && boss) {
// Marked manual so it runs even when the job is switched off.
const id = await boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true, id };
}
const output = await runJob(job);
@@ -330,6 +442,7 @@ async function runNow(name) {
/** Each job with its schedule, next run and recent runs, for the admin page. */
async function jobStatus(prisma) {
await loadOverrides(true);
const recent = new Map();
if (mode === 'queue') {
// pg-boss columns are timestamptz, and Prisma's pg adapter drops their offset in raw queries
@@ -356,11 +469,16 @@ async function jobStatus(prisma) {
return {
mode,
timezone: TIMEZONE,
jobsEnabledEnv: flag('JOBS_ENABLED'),
jobs: JOBS.map(job => {
const cron = cronFor(job);
const enabled = isEnabled(job);
const o = overrides[job.name] || {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
// 3.4.0: what the .env says, and the admin's choice over it (null: the .env applies).
envEnabled: envEnabled(job), envCron: envCronFor(job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron) ? o.cron : null },
nextRun: enabled && mode !== 'off' ? nextRun(cron) : null,
recent: recent.get(job.name) || [],
};
@@ -368,4 +486,7 @@ async function jobStatus(prisma) {
};
}
module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, cronFor, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask };
module.exports = {
JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask,
setOverride, loadOverrides, setOverridesForTest,
};
@@ -100,7 +100,8 @@ v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary:
// ─── Admin ───────────────────────────────────────────────────────────────────
v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('queue, timers or off'), timezone: D.str, jobsEnabledEnv: D.bool.describe('JOBS_ENABLED in the .env'), jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, envEnabled: D.bool.describe('What the .env says'), envCron: D.str, defaultCron: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }).describe('What an admin chose over the .env (null: the .env applies)'), nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'put', path: '/admin/jobs/:name', tag: 'Admin', summary: 'Switch a background job on or off, or change its schedule', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: z.object({ enabled: z.boolean().nullable().optional().describe('true or false wins over the .env; null goes back to it'), cron: z.string().max(100).nullable().optional().describe('A cron schedule (five fields) that wins over the .env; null or empty goes back to it') }), documented: { response: D.obj({ name: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }) }) }, v1: jobs.updateJob });
v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow });
v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions });
v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation });
@@ -7,7 +7,9 @@ let mockLink: object | null = null;
jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } }));
jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
let mockMode = 'local';
jest.mock('../src/accounts/mode', () => ({
viaAccounts: async () => mockMode === 'accounts',
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
@@ -21,6 +23,7 @@ beforeEach(() => {
mockConnects.length = 0;
mockListed = [];
mockLink = null;
mockMode = 'local';
});
test('connects to the Accounts the Hub lists, as the system, once', async () => {
@@ -46,3 +49,13 @@ test('already connected by an admin: just remembers it', async () => {
expect(mockConnects).toEqual([]);
expect(mockSettings.has(AUTO_KEY)).toBe(true);
});
test('3.5.0: a site in Accounts mode that lost its link (a demo load before 3.5.0) connects again', async () => {
mockSettings.set(AUTO_KEY, '2026-11-19T10:00:00.000Z');
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
// On its own sign-in, an earlier Disconnect stays.
expect(await connectAccountsIfListed()).toBe('skipped');
mockMode = 'accounts';
expect(await connectAccountsIfListed()).toBe('connected');
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
});
@@ -0,0 +1,83 @@
// 3.6.0: the nightly people check against Accounts (contracts 1.14.0 people.check).
type U = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
let mockUsers: U[] = [];
const mockUpdated: string[] = [];
const mockCalls: { type: string; sub: string }[] = [];
const mockErrors: string[] = [];
let mockMode = true;
let mockLinked = true;
let mockDeferred = new Set<string>();
jest.mock('../src/config/db', () => ({
user: {
findMany: async ({ take, cursor }: { take: number; cursor?: { id: string } }) => {
const sorted = [...mockUsers].sort((a, b) => a.id.localeCompare(b.id));
const start = cursor ? sorted.findIndex((u) => u.id === cursor.id) + 1 : 0;
return sorted.slice(start, start + take);
},
},
}));
jest.mock('../src/accounts/mode', () => ({ viaAccounts: async () => mockMode }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => (mockLinked ? { installId: 'acc-1' } : null), accounts: async () => { throw new Error('not in tests'); } }));
jest.mock('../src/accounts/signin', () => ({ updateLocalCopy: async (id: string) => { mockUpdated.push(id); } }));
jest.mock('../src/accounts/calls', () => ({
handleAccountsCall: async (c: { type: string; sub: string }) => { mockCalls.push(c); return { status: mockDeferred.has(c.sub) ? 'deferred' : 'deleted' }; },
}));
jest.mock('../src/accounts/status', () => ({ recordSignInError: async (_c: string, m: string) => { mockErrors.push(m); } }));
import type { PeopleCheckReply, Profile } from '@crosscode/contracts';
import { runPeopleCheck, sameAsLocal } from '../src/accounts/peopleCheck';
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
const user = (n: number, over: Partial<U> = {}): U => ({ id: `u${String(n).padStart(3, '0')}`, accountId: sub(n), name: `Person ${n}`, email: `p${n}@hope.test`, phoneNumber: null, newsEmail: false, newsWhatsApp: false, ...over });
const profile = (u: U, over: Partial<Profile> = {}): Profile => ({ name: u.name, given_name: null, family_name: null, email: u.email, email_verified: true, phone_number: u.phoneNumber, phone_number_verified: false, news_consent: { email: u.newsEmail, whatsapp: u.newsWhatsApp }, ...over });
beforeEach(() => {
mockUsers = []; mockUpdated.length = 0; mockCalls.length = 0; mockErrors.length = 0;
mockMode = true; mockLinked = true; mockDeferred = new Set();
});
test('updates only copies that differ, handles deleted accounts as user.deleted does, counts the rest', async () => {
mockUsers = [user(1), user(2), user(3), user(4), user(5)];
mockDeferred = new Set([sub(4)]);
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({
schema: 'crosscode.identity-request/1',
people: subs.map((s) => {
const u = mockUsers.find((x) => x.accountId === s)!;
if (s === sub(1)) return { sub: s, status: 'active' as const, profile: profile(u) };
if (s === sub(2)) return { sub: s, status: 'active' as const, profile: profile(u, { name: 'New Name', news_consent: { email: true, whatsapp: false } }) };
if (s === sub(3) || s === sub(4)) return { sub: s, status: 'deleted' as const, profile: null };
return { sub: s, status: 'unknown' as const, profile: null };
}),
});
expect(await runPeopleCheck({ ask, pageSize: 2 })).toEqual({ checked: 5, updated: 1, deleted: 1, deferred: 1, deactivated: 0, unknown: 1 });
expect(mockUpdated).toEqual(['u002']);
expect(mockCalls.map((c) => [c.type, c.sub])).toEqual([['user.deleted', sub(3)], ['user.deleted', sub(4)]]);
});
test('stops, changing nothing, when Accounts knows hardly anyone (linked to the wrong Accounts?)', async () => {
mockUsers = Array.from({ length: 12 }, (_, i) => user(i + 1));
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({ schema: 'crosscode.identity-request/1', people: subs.map((s) => ({ sub: s, status: 'unknown' as const, profile: null })) });
await expect(runPeopleCheck({ ask })).rejects.toThrow(/doesn't know 12 of 12/);
expect(mockCalls).toEqual([]);
expect(mockErrors).toHaveLength(1);
});
test('skipped on its own sign-in, or without a link', async () => {
mockMode = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
mockMode = true; mockLinked = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
});
test('sameAsLocal ignores email case and what Events doesn\'t keep', () => {
const u = user(1, { email: 'Jane@Hope.test' });
expect(sameAsLocal(u, profile(u, { email: 'jane@hope.test', email_verified: false, given_name: 'Jane' }))).toBe(true);
expect(sameAsLocal(u, profile(u, { phone_number: '+27821234567' }))).toBe(false);
});
test('an Accounts before 1.5.0 (people.check unknown there) skips the check instead of failing every night', async () => {
mockUsers = [user(1)];
const ask = async () => { throw Object.assign(new Error('Not a crosscode.identity-request/1 request: type Invalid input'), { code: 'INVALID_REQUEST' }); };
expect(await runPeopleCheck({ ask })).toEqual({ skipped: expect.stringContaining('1.5.0') });
});
@@ -0,0 +1,32 @@
// 3.5.0: how people sign in, for the Hub (heartbeat stats.signIn, contracts 1.13.0).
import { hub } from '@crosscode/contracts';
const mockSettings = new Map<string, string>();
let mockMode = 'accounts';
let mockLink: object | null = null;
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
jest.mock('../src/accounts/mode', () => ({
authMode: async () => mockMode,
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
import { clearSignInError, recordSignInError, signInStatus } from '../src/accounts/status';
beforeEach(() => { mockSettings.clear(); mockMode = 'accounts'; mockLink = null; });
test('Accounts mode without a link, and why the last sign-in failed', async () => {
await recordSignInError('ACCOUNTS_UNAVAILABLE', 'Accounts isn\'t connected.\nConnect it under Settings → Linked products.', new Date('2026-11-20T10:00:00.000Z'));
const s = await signInStatus();
expect(s).toEqual({ mode: 'accounts', accounts: null, lastError: { at: '2026-11-20T10:00:00.000Z', code: 'ACCOUNTS_UNAVAILABLE', message: 'Accounts isn\'t connected. Connect it under Settings → Linked products.' } });
// It fits the heartbeat's contract.
expect(hub.eventsStatsSchema.shape.signIn.safeParse(s).success).toBe(true);
await clearSignInError();
expect((await signInStatus()).lastError).toBeNull();
});
test('linked: the Accounts install and its address', async () => {
mockLink = { installId: 'acc-1', url: 'https://accounts.hope.test', secret: 'x', updatedAt: new Date() };
expect((await signInStatus()).accounts).toEqual({ installId: 'acc-1', url: 'https://accounts.hope.test' });
});
+35
View File
@@ -36,6 +36,41 @@ describe('job registry', () => {
warn.mockRestore();
});
test('3.4.0: an admin choice wins over the env flag and schedule; JOBS_ENABLED=false still wins over everything', () => {
const { setOverridesForTest, envEnabled } = require('../src/jobs');
try {
delete process.env.JOBS_ENABLED;
process.env.WAITLIST_JOB_ENABLED = 'false';
process.env.JOB_SCHEDULE_WAITLIST = '*/5 * * * *';
setOverridesForTest({ waitlist: { enabled: true, cron: '*/20 * * * *' }, backup: { enabled: false } });
expect(envEnabled(job('waitlist'))).toBe(false);
expect(isEnabled(job('waitlist'))).toBe(true);
expect(cronFor(job('waitlist'))).toBe('*/20 * * * *');
expect(isEnabled(job('backup'))).toBe(false);
expect(isEnabled(job('temp-cleanup'))).toBe(true); // no env flag, no choice
process.env.JOBS_ENABLED = 'false';
expect(isEnabled(job('waitlist'))).toBe(false);
// A broken saved schedule falls back to the env's.
delete process.env.JOBS_ENABLED;
setOverridesForTest({ waitlist: { cron: 'nonsense' } });
expect(cronFor(job('waitlist'))).toBe('*/5 * * * *');
expect(isEnabled(job('waitlist'))).toBe(false); // the env flag again
} finally {
setOverridesForTest({});
}
});
test('3.4.0: setOverride checks its input before saving', async () => {
const { setOverride, isCron } = require('../src/jobs');
expect(isCron('*/10 * * * *')).toBe(true);
expect(isCron('0 7 * * *')).toBe(true);
expect(isCron('every day')).toBe(false);
expect(isCron('* * * * * *')).toBe(false); // seconds aren't offered
await expect(setOverride('nope', { enabled: true })).rejects.toMatchObject({ statusCode: 404 });
await expect(setOverride('waitlist', { enabled: 'yes' })).rejects.toMatchObject({ statusCode: 400 });
await expect(setOverride('waitlist', { cron: 'every day' })).rejects.toMatchObject({ statusCode: 400 });
});
test('daily jobs fire at local (Johannesburg) time', () => {
// 07:00 SAST = 05:00 UTC
const next = nextRun('0 7 * * *', new Date('2026-11-04T06:00:00Z'));
+6
View File
@@ -108,6 +108,12 @@
"layer": "install",
"from": "https://{domain}",
"required": true
},
{
"name": "BACKEND_INTERNAL_URL",
"layer": "install",
"from": "http://127.0.0.1:{apiPort}",
"description": "The backend on this server: requests for /api or /uploads that reach the site are passed to it (3.6.1)"
}
]
}
+23 -4
View File
@@ -1,6 +1,15 @@
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
// Requests for the backend (/api, /uploads) that reach the site anyway are passed to it (3.6.1).
// On a server nginx sends those paths to the backend, but a proxy in front can send some to the
// site instead: one with a rule for file extensions (static-file caching) sent every
// /api/uploads/…png here, so an uploaded logo never showed. BACKEND_INTERNAL_URL is the backend on
// this server (http://127.0.0.1:<port>), never the public address, which would come straight back
// here. The end-to-end tests set E2E_API_PROXY (3.0.0): the site and its API on one address, as
// nginx does, so Accounts' sign-in comes back to <site>/api/auth/callback.
const backend = (process.env.BACKEND_INTERNAL_URL || process.env.E2E_API_PROXY || "").replace(/\/+$/, "");
const nextConfig: NextConfig = {
// The end-to-end tests run their own dev server; a separate build folder keeps it
// from clashing with one already running.
@@ -12,10 +21,20 @@ const nextConfig: NextConfig = {
compiler: {
removeConsole: process.env.NODE_ENV === 'production',
},
// The end-to-end tests only (3.0.0): the site and its API on one address, as nginx does on a
// server, so Accounts' sign-in comes back to <site>/api/auth/callback. Unset everywhere else.
...(process.env.E2E_API_PROXY
? { async rewrites() { return [{ source: '/api/:path*', destination: `${process.env.E2E_API_PROXY}/api/:path*` }]; } }
...(backend
? {
// beforeFiles: ahead of every page, so a dynamic route like /[redirectUrl] never catches them.
async rewrites() {
return {
beforeFiles: [
{ source: '/api/:path*', destination: `${backend}/api/:path*` },
{ source: '/uploads/:path*', destination: `${backend}/uploads/:path*` },
],
afterFiles: [],
fallback: [],
};
},
}
: {}),
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.3.0",
"version": "3.6.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,16 +1,21 @@
"use client";
import React, { useCallback, useState } from "react";
import { Timer, Play, RefreshCw } from "lucide-react";
import { Timer, Play, RefreshCw, Pencil, RotateCcw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
import { Switch } from "@/components/ui/switch";
type JobRun = { state: string; createdOn?: string; startedOn: string | null; completedOn: string | null; output: unknown };
type JobInfo = { name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[] };
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobs: JobInfo[] };
type Override = { enabled: boolean | null; cron: string | null };
type JobInfo = {
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
envEnabled: boolean; envCron: string; defaultCron: string; override: Override;
};
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800",
@@ -21,12 +26,23 @@ const STATE: Record<string, string> = {
cancelled: "bg-gray-100 text-gray-500",
};
const PRESETS: { label: string; cron: string }[] = [
{ label: "Every minute", cron: "* * * * *" },
{ label: "Every 5 minutes", cron: "*/5 * * * *" },
{ label: "Every 15 minutes", cron: "*/15 * * * *" },
{ label: "Every hour", cron: "0 * * * *" },
{ label: "Daily at 02:00", cron: "0 2 * * *" },
{ label: "Daily at 07:00", cron: "0 7 * * *" },
];
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
function describeCron(cron: string): string {
if (cron === "* * * * *") return "Every minute";
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
if (m) return `Every ${m[1]} minutes`;
const h = /^(\d+) \* \* \* \*$/.exec(cron);
if (h) return `Every hour at :${h[1].padStart(2, "0")}`;
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
if (d) return `Daily at ${d[2].padStart(2, "0")}:${d[1].padStart(2, "0")}`;
return cron;
@@ -38,13 +54,16 @@ function outputText(run: JobRun): string {
try { return JSON.stringify(run.output); } catch { return ""; }
}
// Settings → Background jobs: what runs when, the last runs of each job, and "Run now".
// Settings → Background jobs: what runs when, the last runs of each job, "Run now", and (3.4.0)
// switching a job on or off and changing its schedule here, over what the server's .env says.
export function JobsTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [data, setData] = useState<JobsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState<string | null>(null);
const [saving, setSaving] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(async () => {
@@ -75,6 +94,24 @@ export function JobsTab({ active }: { active: boolean }) {
}
};
/** Saves a choice for one job: a value wins over the .env, null goes back to it. */
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
if (!token) return;
setSaving(job.name);
try {
await apiV2Data("put", "/admin/jobs/{name}", { params: { name: job.name }, authToken: token, body: change });
setMessage({ type: "ok", text: done });
setEditing(null);
await load();
} catch (e) {
setMessage({ type: "err", text: errorMessage(e) || "Couldn't save that" });
} finally {
setSaving(null);
}
};
const off = data?.mode === "off";
return (
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {
<h2 className="text-lg font-semibold flex items-center gap-2"><Timer className="w-5 h-5 text-brand-600" /> Background jobs</h2>
<p className="text-sm text-gray-500 mt-0.5">
Tasks the server runs on a schedule ({data?.timezone || "local"} time). Each runs once per schedule, even with more than one server process, and failed runs are retried.
Switch a job on or off, or change when it runs: what you choose here wins over the server&apos;s .env and takes effect straight away.
</p>
</div>
<button type="button" onClick={load} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50 shrink-0">
@@ -89,24 +127,37 @@ export function JobsTab({ active }: { active: boolean }) {
</button>
</div>
{message && <div className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{message && <div role="status" className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{data?.mode === "timers" && (
<div className="p-3 border rounded bg-amber-50 text-amber-900 text-sm">The job queue couldn&apos;t start, so jobs are running on simple timers in this server process (no retries, history only since the last restart). Check the server log for &quot;[jobs]&quot;.</div>
)}
{data?.mode === "off" && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off (JOBS_ENABLED=false).</div>
{off && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.</div>
)}
<ul className="divide-y border rounded-lg">
{(data?.jobs || []).map(job => {
const last = job.recent[0];
const busy = saving === job.name;
const enabledHere = job.override.enabled !== null;
const cronHere = job.override.cron !== null;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Switch
checked={job.enabled}
disabled={busy || off}
onCheckedChange={(on) => save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)}
aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`}
/>
<div className="min-w-0 mr-auto">
<div className="font-medium text-sm text-gray-900">{job.label}</div>
<div className={`font-medium text-sm ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
<div className="text-xs text-gray-500">
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : `Off${job.envFlag ? ` (${job.envFlag}=false)` : ""}`}
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{enabledHere
? <> · {job.enabled ? "switched on" : "switched off"} here <button type="button" disabled={busy} className="underline hover:text-gray-700" onClick={() => save(job, { enabled: null }, `"${job.label}" follows the .env again (${job.envEnabled ? "on" : "off"}).`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
@@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) {
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)}
</button>
)}
<button type="button" disabled={running !== null || data?.mode === "off"} onClick={() => runNow(job)}
<button type="button" disabled={busy || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
<Pencil className="w-3.5 h-3.5" /> Schedule
</button>
<button type="button" disabled={running !== null || off} onClick={() => runNow(job)}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
<Play className="w-3.5 h-3.5" /> {running === job.name ? "Starting…" : "Run now"}
</button>
</div>
{isEditing && editing && (
<form className="mt-3 rounded border bg-gray-50 p-3 space-y-2" onSubmit={e => { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{PRESETS.map(p => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`text-xs px-2 py-1 rounded border ${editing.cron === p.cron ? "bg-brand-50 border-brand-300 text-brand-800" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-2">
<label className="text-xs text-gray-600">
Cron (minute hour day month weekday)
<input value={editing.cron} onChange={e => setEditing({ name: job.name, cron: e.target.value })} maxLength={100}
className="mt-1 block w-56 rounded border px-2 py-1 font-mono text-sm" aria-label="Cron schedule" />
</label>
<span className="text-xs text-gray-500 pb-1.5">{describeCron(editing.cron.trim())}</span>
<div className="ml-auto flex gap-2">
<button type="button" onClick={() => setEditing(null)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-100">Cancel</button>
<button type="submit" disabled={busy || !editing.cron.trim()} className="text-xs px-2.5 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save schedule"}</button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}.
{cronHere && <> <button type="button" disabled={busy} className="inline-flex items-center gap-1 underline hover:text-gray-700" onClick={() => save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}><RotateCcw className="w-3 h-3" /> Use that again</button></>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<table className="mt-2 w-full text-xs">
<thead className="text-gray-500"><tr><th className="text-left font-medium py-1">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
@@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) {
})}
{!loading && data && data.jobs.length === 0 && <li className="p-3 text-sm text-gray-500">No jobs.</li>}
</ul>
<p className="text-xs text-gray-400">Change a schedule with the env var JOB_SCHEDULE_&lt;NAME&gt; (cron, e.g. JOB_SCHEDULE_WAITLIST=&quot;*/5 * * * *&quot;), or switch one off with its own flag.</p>
<p className="text-xs text-gray-400">Without a choice here, the server&apos;s .env applies: each job&apos;s own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;.</p>
</div>
);
}
@@ -61198,11 +61198,15 @@
"properties": {
"mode": {
"type": "string",
"description": "on, off or timers"
"description": "queue, timers or off"
},
"timezone": {
"type": "string"
},
"jobsEnabledEnv": {
"type": "boolean",
"description": "JOBS_ENABLED in the .env"
},
"jobs": {
"type": "array",
"items": {
@@ -61229,6 +61233,38 @@
"null"
]
},
"envEnabled": {
"type": "boolean",
"description": "What the .env says"
},
"envCron": {
"type": "string"
},
"defaultCron": {
"type": "string"
},
"override": {
"type": "object",
"properties": {
"enabled": {
"type": [
"boolean",
"null"
]
},
"cron": {
"type": [
"string",
"null"
]
}
},
"required": [
"enabled"
],
"additionalProperties": {},
"description": "What an admin chose over the .env (null: the .env applies)"
},
"nextRun": {
"anyOf": [
{
@@ -61254,6 +61290,10 @@
"name",
"label",
"enabled",
"envEnabled",
"envCron",
"defaultCron",
"override",
"recent"
],
"additionalProperties": {}
@@ -61263,6 +61303,7 @@
"required": [
"mode",
"timezone",
"jobsEnabledEnv",
"jobs"
],
"additionalProperties": {}
@@ -61299,6 +61340,157 @@
}
}
},
"/admin/jobs/{name}": {
"put": {
"tags": [
"Admin"
],
"summary": "Switch a background job on or off, or change its schedule",
"description": "**Who:** Admins only.",
"operationId": "putAdminJobsName",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"description": "The name",
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 100
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"enabled": {
"description": "true or false wins over the .env; null goes back to it",
"type": [
"boolean",
"null"
]
},
"cron": {
"description": "A cron schedule (five fields) that wins over the .env; null or empty goes back to it",
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
}
}
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"override": {
"type": "object",
"properties": {
"enabled": {
"type": [
"boolean",
"null"
]
},
"cron": {
"type": [
"string",
"null"
]
}
},
"required": [
"enabled"
],
"additionalProperties": {}
}
},
"required": [
"name",
"override"
],
"additionalProperties": {}
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found (NOT_FOUND)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/admin/jobs/{name}/run": {
"post": {
"tags": [
+114 -1
View File
@@ -6290,6 +6290,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/admin/jobs/{name}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Switch a background job on or off, or change its schedule
* @description **Who:** Admins only.
*/
put: operations["putAdminJobsName"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/admin/jobs/{name}/run": {
parameters: {
query?: never;
@@ -35118,15 +35138,28 @@ export interface operations {
content: {
"application/json": {
data: {
/** @description on, off or timers */
/** @description queue, timers or off */
mode: string;
timezone: string;
/** @description JOBS_ENABLED in the .env */
jobsEnabledEnv: boolean;
jobs: ({
name: string;
label: string;
cron?: string | null;
enabled: boolean;
envFlag?: string | null;
/** @description What the .env says */
envEnabled: boolean;
envCron: string;
defaultCron: string;
/** @description What an admin chose over the .env (null: the .env applies) */
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
nextRun?: string | null;
/** @description Recent runs */
recent: {
@@ -35161,6 +35194,86 @@ export interface operations {
};
};
};
putAdminJobsName: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The name */
name: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description true or false wins over the .env; null goes back to it */
enabled?: boolean | null;
/** @description A cron schedule (five fields) that wins over the .env; null or empty goes back to it */
cron?: string | null;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
name: string;
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
} & {
[key: string]: unknown;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAdminJobsNameRun: {
parameters: {
query?: never;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.3.0",
"version": "3.6.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+11 -8
View File
@@ -116,7 +116,7 @@ else
echo " backend/.env exists — kept"
fi
if [ ! -f "$DIR/frontend/.env.production" ]; then
echo "NEXT_PUBLIC_API_URL=$SITE_URL" > "$DIR/frontend/.env.production"
printf 'NEXT_PUBLIC_API_URL=%s\nBACKEND_INTERNAL_URL=http://127.0.0.1:%s\n' "$SITE_URL" "$API_PORT" > "$DIR/frontend/.env.production"
fi
if [ ! -f "$DIR/ecosystem.config.js" ]; then
sed -e "s/'hope-events-backend'/'$NAME-backend'/" -e "s/'hope-events-frontend'/'$NAME-frontend'/" -e "s/-p 3000/-p $WEB_PORT/" \
@@ -140,14 +140,17 @@ server {
server_name $DOMAIN;
client_max_body_size 25m;
# For the backend locations below ("location /" sets its own).
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
# The API, uploaded files, health and API docs go to the backend; everything else to the site.
location ~ ^/(api|uploads|health|docs)(/|\$) {
proxy_pass http://127.0.0.1:$API_PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# ^~ so a regex location added later (e.g. caching *.png) can't send /api/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ~ ^/(api|uploads|health|docs)(/|\$) { proxy_pass http://127.0.0.1:$API_PORT; }
location / {
proxy_pass http://127.0.0.1:$WEB_PORT;
proxy_http_version 1.1;
+1 -1
View File
@@ -1,3 +1,3 @@
# Church Website
Placeholder: the church's public website and its admin. Built in phase 4 of ROADMAP-v3 (see §6 there).
Placeholder: the church's public website and its admin. Built in phase 5 of ROADMAP-v3 (see §6 there).
+1 -1
View File
@@ -2,5 +2,5 @@
"name": "@crosscode/website",
"version": "0.0.0",
"private": true,
"description": "Placeholder: Church Website, built in phase 4 (ROADMAP-v3 §6)"
"description": "Placeholder: Church Website, built in phase 5 (ROADMAP-v3 §6)"
}
+2 -1
View File
@@ -354,6 +354,7 @@ Confirmed by Joshua on 2026-11-18 (1, 4, 5 and 6 asked directly; the rest as pro
## Still open
- Whether the Website's admin edits the church profile through Accounts' API (as proposed in §7)
or Accounts' own screen is the only place. Decide with the Website plan (phase 5).
or Accounts' own screen is the only place. Decide with the Website plan (phase 5). **Decided 2026-11-21 (WEBSITE-1.0-PLAN decision 10):**
through Accounts' API, live at once.
- Session lengths (30 days with "Keep me signed in") are a starting point; check them with Joshua
before release.
+40 -12
View File
@@ -83,7 +83,8 @@ build differs from this plan, see [Changes while building](#changes-while-buildi
- **Polling:** every 30 s `POST /api/agent/v1/poll` (signed) with a short status; the reply holds
any jobs due. Every 60 s the stats (§10). Requests back off when the Hub doesn't answer.
- **Modes:** `church` (default) and `central` (§6). The central agent can't run any job but
`check-ports` and `status`.
`check-ports`, `status` and `update-agent`, and from agent 1.4.0 `frp-read`, `frp-write` and
`probe-ports` (below).
- **Updating itself:** an `update-agent` job checks out the newest `agent@…` tag, builds it next
to the running copy, switches the systemd unit over and reports its new version. If the new one
doesn't poll within 2 minutes, a systemd timer starts the previous one again.
@@ -246,7 +247,25 @@ remote_port = 20011
- The `.ini` format is deprecated in newer frp versions in favour of TOML. The agent reads the
format the server has; moving to TOML is a separate job for later.
**The central agent** (`--central`, on the FastPanel server, read-only) answers `check-ports`:
**frp's config from the Hub (agent 1.4.0, Hub 2.11.0).** frps and frpc aren't always in
`/etc/frp/*.ini`: the agent finds the file itself (the path set on the Hub for that server, else
the `-c` in the systemd unit's ExecStart, else the usual places) and reads INI and TOML. The
server's page on the Hub shows it (`frp-read`) and can change it (`frp-write`, with two-factor):
secret values (token, passwords) never leave the server (shown as `***hidden***`, put back on
write, and can't be changed from the Hub), the new file is checked with `frps verify` /
`frpc verify`, a backup is kept in `<dir>/backups/`, the service is restarted, and the old file
goes back if it doesn't come up. **This ends "the central agent is read-only":** it can change
frps's config, and nothing else (no FastPanel, no firewall).
**Ports checked before an install (agent 1.4.0, Hub 2.11.0).** A new install reserves a few
candidate ports and sends `probe-ports` to every central server and to the church server. The
central agent says which are free (nothing listening, inside allow_ports); the church agent says
which are free there (nothing listening, not in frpc's config). The install waits (scheduled) and
then runs on the first pair free on both; busy ports go in the port list as taken. Too few free:
another round with new ports (3 rounds), then the install is called off and its ports freed.
With an agent older than 1.4.0 on either server, the install runs as before, with a warning.
**The central agent** (`--central`, on the FastPanel server) answers `check-ports` after an install:
- the port is inside `allow_ports` in `frps.ini`,
- frps has the tunnel open (the port is listening; frps's dashboard API is used if it's enabled
@@ -280,7 +299,8 @@ It changes nothing on the central server: no frps edits, no firewall changes, no
with the Hub using its licence.
5. **On failure** anything this job created is removed again (PM2 processes, frpc block, database
and role, folder), in reverse order, and the report says what failed and what was cleaned up.
6. **Central check:** the Hub asks the central agent to `check-ports` for both ports.
6. **Central check:** the Hub asks the central agent to `check-ports` for both ports. (From Hub
2.11.0 the ports were already checked free on both servers before step 1; see §6.)
7. **Emails to Joshua:** the install report and, if everything passed, the **FastPanel email**
(§11). The install shows **Waiting for proxy** in the Hub.
8. Joshua sets up FastPanel by hand and clicks **Proxy done**. The Hub checks the public URLs
@@ -382,16 +402,24 @@ All in the Hub (Jobs page, with the full report) and by email:
```
Set up in FastPanel: events.hope.co.za (Hope Family Church, Cross Events)
1. Add the site events.hope.co.za.
2. Proxy:
/api → http://127.0.0.1:20011 (backend; Events 2.2.0+, older
releases also need /uploads, /health, /docs)
everything else → http://127.0.0.1:20010 (frontend)
Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.
Allow uploads up to 25 MB.
1. Add the site events.hope.co.za as a proxy to http://127.0.0.1:20010 (the frontend). Pass the
Host header and X-Forwarded-For / X-Forwarded-Proto: https, and allow uploads up to 25 MB.
2. Send /api to the backend: add this to the site's nginx configuration. Keep the ^~: without
it FastPanel's static-file rule sends every /api path with a file extension to the frontend.
location ^~ /api/ {
proxy_pass http://127.0.0.1:20011;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location = /api { proxy_pass http://127.0.0.1:20011; }
3. Turn on Let's Encrypt for the site.
4. DNS: events.hope.co.za → <central server IP> (checked: ✅ points there / ⚠ not yet)
5. Then click "Proxy done" in the Hub: <link>
4. DNS: events.hope.co.za → <central server IP> (checked: points there / not yet)
5. Click "Proxy done" in the Hub. It checks the site, its /api and a file under /api, then
makes it live: <link>
Central check: both ports are open in frps and only on 127.0.0.1.
```
+95 -20
View File
@@ -1,6 +1,6 @@
# Handover — Cross Code, all products
Last updated: 2026-11-19. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
Last updated: 2026-11-24. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
decisions table near the end). This file says where each phase stands and what comes next.
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
@@ -25,28 +25,90 @@ every release).
| Phase | What | State |
|-------|------|-------|
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04. Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
| 1 | Hub 2.0.x | **Released** (`v2.0.0` 2026-11-05, `v2.0.1` AI tokens and `v2.0.2` refunds / voiding refunded invoices, 2026-11-17). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). Deploy straight to the latest 2.1.x (below) |
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released** 2026-11-17 (`events@2.2.0`, with AI use in tokens and the backend under `/api`). **VM tested 2026-11-17** (EVENTS-2.2-PLAN §6, all passing after fixes). **Not rolled out:** servers still run `hope-events` `v2.1.1` until each install is adopted |
| 1c | Cross Events 2.3.x: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). **`events@2.3.1`** 2026-11-18: Next.js 16.4.6 (security advisories for 16.2.0–16.4.4), so roll out 2.3.1, not 2.3.0. crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) |
| 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Released** 2026-11-18 (`events@2.4.0`, `contracts@1.4.0`, Hub `v2.2.0`, crosscode-site `v1.4.0`; [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). **Before any church gets it:** the Events e2e run on Postgres and the VM test (EVENTS-2.4-PLAN §8) |
| 3 | Accounts 1.0.0 (+ contracts 1.5.0, agent 1.1.0, Hub 2.3.0) | **Released** 2026-11-18 (`accounts@1.0.0`, `contracts@1.5.0`, `agent@1.1.0`, Hub `v2.3.0`, crosscode-site `v1.5.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). 37 backend and 8 Playwright tests pass without Postgres. **Before installing it for a church:** the VM test and a run on real Postgres; a Hub release source for `accounts@` tags |
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Released** 2026-11-19 (`events@3.0.0`, `accounts@1.1.0`, `contracts@1.8.0`, Hub `v2.5.0`, crosscode-site `v1.6.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Tested on Postgres 18: both migrations, `test:accounts` on real databases (14/14), the Events e2e suite (111, incl. `sign-in-accounts.spec.ts`). **Not VM tested yet.** Roll out: Hub 2.5.0 deployed first, then per church Accounts 1.1.0 → Events 3.0 → Move (MIGRATING-TO-3.md); crosscode-site 1.6.0 once the first church has moved |
| 5–7 | Website 1.0.0 → App 1.0.0 → App 1.x | Not started |
| 0 | contracts 1.0.0 → 1.17.0 | **Released and in use.** Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
| 1 | Hub 2.0 → 2.20.0 | **Released, deployed and tested** (Hub `v2.20.0`) |
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released, rolled out and tested.** Every install adopted onto the monorepo |
| 1c | Cross Events 2.3.x: authenticator app 2FA | **Released and rolled out** (carried into Accounts in phase 4) |
| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.5.0` on every server: from 1.4.0 the Hub reads and changes frps's / frpc's config and probes ports before an install; from 1.5.0 one product of a church can be uninstalled, exported or purged) |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | **Released, rolled out and tested** ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)) |
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.6.1`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
| 5 | Church Website 1.0.0 | **Planned** 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (all decisions confirmed). Font pairings confirmed 2026-11-24 (§3). `contracts@1.17.0` and `accounts@1.7.0` released 2026-11-24 (Accounts not yet rolled out); Events 3.7.0 next |
| 6–7 | App 1.0.0 → App 1.x | Not started |
## Released 2026-11-23
All tagged, pushed and deployed on 2026-11-23. Details in [VERSIONS.md](./VERSIONS.md) and the Hub's
CHANGELOG.
| Release | What |
|---------|------|
| `agent@1.4.0`, `contracts@1.15.0`, Hub `v2.11.0` | The agent finds frps's / frpc's config wherever it is (TOML too); each server's Hub page reads and changes it (secrets stay on the server, verify, backup, put back if frp doesn't start, two-factor). New installs probe their ports on the central and church server first (`probe-ports`) |
| `agent@1.5.0`, `contracts@1.16.0`, Hub `v2.12.0`, `crosscode` script | Uninstall, export and purge **one product** of a church (`crosscode uninstall|export|purge <church> [product …]`); the last one removes the church; Accounts goes last. Stale installs removable from the Hub; customers archivable; several emails per customer |
| Hub `v2.13.0` | Alerts cleared by hand; billing tables sortable |
| Hub `v2.14.0` – `v2.17.0` | Customer and install pages as a header, tiles and tabs; every add and edit in a popup (frontend only) |
| Hub `v2.18.0`, `v2.19.0` | Releases picked from a list; the server agent's own releases on the Releases page and in Update agent (migration `AgentRelease`) |
| Hub `v2.20.0` | The port list says what each port is for; frps's allow_ports checked against it |
| crosscode.co.za `v1.6.1` | Clearer web address choices on the Cross Events page |
## Released 2026-11-20
All tagged, pushed, deployed and tested (confirmed by Joshua 2026-11-21). Details in [CHANGELOG.md](../CHANGELOG.md), the apps' CHANGELOGs
and What's New, and [VERSIONS.md](./VERSIONS.md).
| Release | What |
|---------|------|
| `events@3.4.0`, `accounts@1.4.0`, `contracts@1.12.0`, `agent@1.3.0`, Hub `v2.8.0` | Background jobs switched on/off and rescheduled from each site's admin (saved in `job_overrides`, wins over the .env, applies at once; Accounts gets an Admin → Background jobs page). Accounts' emails styled as Events' (`src/lib/emails.ts`). The Hub reads and changes an install's .env (`env-read` / `env-set` jobs → `crosscode env`; secrets never leave the server; the file is put back if the site doesn't start; the frontend's file triggers a rebuild) |
| `events@3.5.0`, `contracts@1.13.0`, `agent@1.3.1`, Hub `v2.9.0` | **Fix:** "Load demo data" deleted the Accounts link (`set-demo.js` truncated `ProductLink`), so events-demo couldn't sign anyone in (`ACCOUNTS_UNAVAILABLE`). Demo data keeps the link; a site in Accounts mode without a link reconnects at its next heartbeat. Heartbeat `stats.signIn`; Hub alerts: not linked (critical), wrong Accounts, sign-in failing, an Accounts nothing links to. **Agent 1.3.0 reported itself as 1.2.0**: use 1.3.1 |
| `accounts@1.6.0` | A "New sign-in" email (and WhatsApp) after every sign-in; Sign-in settings → `signin_notices` turns it off |
| Hub `v2.10.0` | Every Hub email laid out as Events' and Accounts' (`src/utils/emailLayout.js`: header with the logo, button, notes, job steps, code blocks; plain text kept). The FastPanel email gives `location ^~ /api/` as config to paste; Proxy done checks a file under `/api` reaches the backend. Billing emails unchanged |
| `events@3.6.1` | **Fix:** logo/favicon uploads failed on events-demo ("uploaded, but the site can't show it yet"). FastPanel's static-file rule sent every `/api/…` path with a file extension (`.png`, `.pdf`, …) to the frontend. The site now passes `/api/*` and `/uploads/*` on to the backend (`BACKEND_INTERNAL_URL`); the installers' nginx uses `location ^~`. Change each FastPanel site too (below) |
| `events@3.6.0`, `accounts@1.5.0`, `contracts@1.14.0` | The nightly people check (`accounts-people-check`, 04:30): `people.check` 500 subs at a time; fixes out-of-date copies, handles deleted accounts as `user.deleted`, stops (changing nothing) when most people are unknown. Skipped with an Accounts before 1.5.0 |
## FastPanel sites (central server)
FastPanel's nginx on the central server is the only router for sites behind frp: the church
server has no nginx. Its static-file handling adds a regex location for file extensions
(`png|jpg|ico|svg|css|js|pdf|txt|…`) that falls back to the site's main proxy, the frontend. A
plain `location /api` loses to it, so `/api/uploads/…/logo.png` reached Next.js and got a 404
(fixed in the site by Events 3.6.1, but slower and without the visitor's IP). In each Events
site's nginx config in FastPanel, the backend locations must be `^~` (a prefix match that no
regex can override):
```nginx
location ^~ /api/ {
proxy_pass http://127.0.0.1:<api port>;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location = /api { proxy_pass http://127.0.0.1:<api port>; }
```
Since **Hub 2.10.0** the FastPanel email (AGENT-1.0-PLAN §11) gives this block to paste, and
**Proxy done** refuses a site whose `/api/proxy-check.png` reaches the frontend. Sites set up
before that need the change by hand, and so does the Hub's own site (`events-hub`,
`/api/…/statement.pdf`; its deployment.md §8). Check after a change:
`curl -sI https://<domain>/api/health.png` must not say `X-Powered-By: Next.js` (a 404 is fine).
## Next up
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) (with the latest patch
releases: Hub 2.1.1, agent 1.0.1, Events 2.3.1): Hub 2.1 (make and back up
the job-signing key first) → the central server's agent (check `proxy_bind_addr = 127.0.0.1`)
→ each church server's agent → **adopt** the demo site, then each church (Link existing → Move
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events`
(with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its
order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0).
Everything up to and including the 2026-11-23 releases is deployed (VERSIONS.md, "Deployed / rolled
out").
1. **Phase 5, Church Website 1.0.0** (ROADMAP §6, §9). Planned in
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
ships with contracts because it answers the new `church.update`) → Events 3.7.0 (shared fonts and footer) → **Hub 2.21.0** (the
plan said 2.13.0; the Hub has moved on since) → `website@1.0.0` → Hope Family Church → a second
church → crosscode-site 1.7.0.
2. **Archive `hope-events`** if it isn't yet (every install now reports 2.2.0 or later;
EVENTS-2.2-PLAN §7).
3. **FastPanel sites set up before Hub 2.10.0** need `location ^~ /api/` by hand, and so does the
Hub's own site ("FastPanel sites" above). Not yet recorded which are done: check each with
`curl -sI https://<domain>/api/health.png`.
## The VM test (2026-11-17)
@@ -95,6 +157,19 @@ rollout.
- **AI for a church:** set the licence's monthly AI cap above R0 on the Hub; with no cap the
buttons don't show (rules in Events' handover, "AI rules"). Churches see tokens; only the Hub
shows rand (markup 15% by default).
- **The agent's version is in two places:** `apps/agent/package.json` *and* `AGENT_VERSION` in
`apps/agent/src/stats.ts` (what it reports to the Hub). Bump both; the agent's test checks they match,
so run `npm run check` *after* the bump (1.3.0 shipped reporting 1.2.0).
- **Background jobs:** each job's switch and schedule can be set in the site's admin (Events and
Accounts, AppSetting `job_overrides`); that wins over the .env flag and `JOB_SCHEDULE_<NAME>`.
`JOBS_ENABLED=false` still turns everything off. A new job gets a `label` and, if it may be turned
off from the .env, an `env` flag.
- **An install's .env from the Hub** (install page → Settings (.env), agent 1.3.0+): plain values
only. Names matching `SECRET_ENV_NAME` (contracts) / `SECRET_NAME` (`scripts/lib/envedit.cjs`;
keep them in step) and generated values can't be read or changed from the Hub. Changing an
address there doesn't change the Hub's domain for the install or FastPanel.
- **Demo data keeps the links** to the church's other products (`KEEP_TABLES` in
`apps/events/backend/scripts/set-demo.js`). Anything that must survive a demo load goes there.
- **Releasing:** branch → merge → tag (`<product>@<version>` here, `v<version>` in events-hub and
crosscode-site) → push, with a CHANGELOG entry, and `npm run check` first. Pushes to c-git often
fail authentication the first time; retry once. A push can also hang waiting on a login prompt
+40 -8
View File
@@ -29,6 +29,12 @@ change decisions 10 and 23.
**Updated 2026-11-19:** phases 4 and 5 swapped: **Cross Events 3.0.0** (sign-in through Accounts)
comes before the **Church Website** (§9, decision 38).
**Updated 2026-11-21:** the Church Website (phase 5) is planned in
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): more room to customise each template, one Publish for
the whole site after a clickable preview, Coming soon until then, a brand style and footer shared
with Cross Events (3.7), and no address moves or redirects in 1.0 (§6, §9, §10, §11; decisions
40–48).
---
## Contents
@@ -398,6 +404,11 @@ picks one; its **logo and colours come from the church profile** (`crosscode.chu
release for every church using them. More templates can be added in later releases.
- Every template meets the same bar: tested in Playwright (layout at phone / tablet / desktop,
axe accessibility) and with the §11 SEO checks.
- **Room to make it their own** (decision 40): every section type comes in two or three
**variants** (e.g. the hero as photo, video, collage, split or text only), **style settings**
(font pairing, corners, section colour, spacing, buttons, image treatment, header) and **custom
pages** built from blocks. No free layout or custom CSS. The font pairing and corners are part of
the church's shared brand style (decision 47). Details in WEBSITE-1.0-PLAN §3.
### Admin (`www.church.co.za/admin`, signed in through Accounts)
@@ -407,13 +418,18 @@ picks one; its **logo and colours come from the church profile** (`crosscode.chu
- Pages and sections, About, Leadership, Ministries, Messages, Media library, Contact and
service times, Navigation, Settings (including SEO and search engine verification, §11).
- **Events:** simple events, plus the feed settings (§4) and sync health.
- **Draft → preview → publish**, archive instead of delete, an audit log of who changed what.
- **Draft → preview → publish** (decision 41): every change is a draft; the preview is the whole
site, fully clickable, at phone / tablet / desktop width, and can be shared by link; **one
Publish** puts every change live; every published version is kept and can be restored. Until the
first publish the site shows **Coming soon** (decision 42). Archive instead of delete, an audit
log of who changed what.
- **Roles:** Owner, Admin, Editor, Ministry leader (own ministry only), Viewer.
### Not in the first release
Prayer requests and other forms with personal information (they belong in the App), a member
directory, online giving processing.
Prayer requests and other forms with personal information (they belong in the App; the Contact
page is contact details only, decision 43), a member directory, online giving processing, moving
to the church's own domain with redirects (decision 45).
---
@@ -625,7 +641,7 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists |
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0). **Released 2026-11-18** (`accounts@1.0.0`, 1.0.1 on 2026-11-19); the VM test and a run on real Postgres are still to do before a church gets it | Every later product signs in through it |
| 4 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide. **Planned 2026-11-19:** [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0; decisions confirmed 2026-11-19) | Breaking change, so a major version. **Moved before the Website on 2026-11-19** (decision 38): Events is the product churches use today, so Accounts is proven on real users first, and the Website then starts with a church whose people already have accounts |
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats. **Planned 2026-11-21:** [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (with contracts 1.17.0, Accounts 1.7.0, Events 3.7.0 for the shared fonts and footer, Hub 2.21.0) | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed) | Starts with shared users and the feed already in place |
| 7 | Church App 1.x | Reading plans, sermons, groups, pastoral care, serving, giving links, directory | After House of Prayer is in use |
@@ -695,7 +711,7 @@ charged **once per church**, not per product.
| Option | Price | What it means |
|--------|-------|---------------|
| **Own domain** | R0 | The church already has a domain (e.g. `hopefamily.co.za`). They, or whoever manages it, add the DNS records we send. We look after the certificates |
| **Cross Code address** | **+R10 / month** | For churches that don't want a domain of their own: `hopefamily.crosscode.co.za`, with the products at `events.hopefamily.crosscode.co.za`, `app.hopefamily.crosscode.co.za` and so on. Can move to a domain of their own at any time (old addresses redirect for 12 months). Trials use this address for free |
| **Cross Code address** | **+R10 / month** | For churches that don't want a domain of their own: `hopefamily.crosscode.co.za`, with the products at `events.hopefamily.crosscode.co.za`, `app.hopefamily.crosscode.co.za` and so on. Can move to a domain of their own (old addresses redirect for 12 months; not before Website 1.0, decision 45). Trials use this address for free |
| **Domain included** | **+R25 / month** | We register a `.co.za` or `.org.za` **in the church's name**, renew it every year and manage the DNS. Other endings (`.com`, `.church`, `.org`) are charged at cost on top. If the church leaves, the domain is transferred to them, free |
### Church Website: one price plus storage
@@ -709,7 +725,8 @@ charged **once per church**, not per product.
Uploads are photos, documents and sermon notes. Sermon audio and video are linked (YouTube,
Spotify, SoundCloud…) rather than uploaded, so most churches never need extra storage. Admins see
how much they've used in the website's settings and get an email at 80%. Storage is counted per
church and reported to the Hub, which bills the add-on.
church and reported to the Hub, which bills the add-on. **When it's full, uploads stop** until more
is bought (decision 48); what's already uploaded keeps showing.
### Church App: on active members
@@ -783,7 +800,8 @@ data from the same `crosscode.event/1` and `crosscode.church/1`. Cross Events mo
When a church moves from the Cross Code address to its own domain (§10), every old URL
**301-redirects** to the same page on the new domain for 12 months, so it keeps its search
ranking.
ranking. **Not in Website 1.0** (decision 45): moving addresses, with a Hub job for all of a
church's products, comes in a later release.
### Checks (in every product's tests)
@@ -859,7 +877,21 @@ ranking.
| 38 | Order after Accounts | **Cross Events 3.0.0 (sign-in through Accounts) is phase 4, the Church Website phase 5** (swapped). Events is what churches use today, so Accounts is proven on real users and their migrated passwords and 2FA first; the Website then starts with a church whose people already have accounts |
| 39 | Emergency updates now | An emergency update (reason and 2FA, as before) can run **as soon as possible**, at the agent's next poll (within a minute), as well as at a time at least 15 minutes away. The church is told it's happening now. When the church's Events heartbeat shows an event on now (a session or a one-day event, or check-ins in the last hour), the Hub names it and needs a second "yes". Hub 2.7.0, Events 3.2.0 |
**Added 2026-11-21** (phase 5, [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md))
| # | Question | Decision |
|---|----------|----------|
| 40 | Enough customisation | Keep **four templates**, each with **section variants**, **style settings** and **custom pages from blocks**, within limits that keep every site designed, accessible and fast. No free layout, custom CSS or custom fonts. More templates can come in 1.x, but not instead of this |
| 41 | Publishing | Every change is a draft. A **fully clickable preview** of the whole site (shareable by a 7-day link) and **one Publish for the whole site**; any pending change can be discarded; every published version is kept and can be restored |
| 42 | Before the first publish | The public address shows a **Coming soon** page from the church profile (logo, service times, contact, links to Events), `noindex` |
| 43 | Contact page | **Contact details only**, no form |
| 44 | Shared vs Website-only content | The church profile (`crosscode.church/1`) gains the **brand style** (font pairing, corners). Leaders, ministries, About, giving and messages are **Website-only for now**; the App plan decides whether they move into the profile |
| 45 | Moving to the church's own domain | **Not in Website 1.0**, and no Hub "Change address" job yet (§10, §11 "Moving addresses") |
| 46 | Messages | **From a YouTube channel or playlist automatically** (latest video as the latest message), or **by hand** with a YouTube or Spotify link |
| 47 | Feeling like one church | The **brand style and footer are shared**: the Website, Accounts' pages and **Cross Events 3.7**'s public pages use the church's fonts, corners and one `ChurchFooter`, with links between the products |
| 48 | Full storage | Admins are emailed at 80% and 100%; at 100% **uploads stop** until more storage is bought (Get more storage asks the Hub; the new limit arrives with the licence) |
## Still open
Nothing. crosscode-site is updated at the end of each phase (§9, "Updating crosscode-site"); the
Nothing for the roadmap. WEBSITE-1.0-PLAN lists its own proposals still to confirm. crosscode-site is updated at the end of each phase (§9, "Updating crosscode-site"); the
Website and App move from "coming later" to their own pages and prices when they ship.
+121 -15
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-20. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-24. 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
@@ -10,13 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.3.0** | `events@3.3.0` | 2026-11-20 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.3.0** | `accounts@1.3.0` | 2026-11-20 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.11.0** | `contracts@1.11.0` | 2026-11-20 |
| Cross Code Hub | `events-hub` | **2.7.1** | `v2.7.1` | 2026-11-19 |
| crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.6.1** | `events@3.6.1` | 2026-11-20 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.0** | `accounts@1.7.0` | 2026-11-24 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.17.0** | `contracts@1.17.0` | 2026-11-24 |
| Cross Code Hub | `events-hub` | **2.20.0** | `v2.20.0` | 2026-11-23 |
| crosscode.co.za | `crosscode-site` | **1.6.1** | `v1.6.1` | 2026-11-23 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
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
@@ -28,8 +28,8 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
|------|-------|-------------------------|
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.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 5) |
| `@crosscode/ui` | `packages/ui` | 0.2.0 (fonts, `ChurchFooter`; released with Accounts 1.7.0) |
| Website | `apps/website` | 0.0.0 (phase 5, being built: contracts 1.17.0 released) |
| 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
@@ -37,6 +37,111 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Contracts 1.17.0 + Accounts 1.7.0 (2026-11-24):** the first piece of the Church Website. Contracts:
the 8 font pairings, corner styles and template ids (`./style`), an optional `branding.style` on the
church profile, `church.update` (the Website changes shared profile facts), an optional `website`
part of the church export and an optional `limits.storageBytes` on the licence. Accounts: Brand
style under Church profile, the church's fonts, corners and shared footer on its pages, and
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **Not deployed yet.**
- **Hub 2.20.0 (2026-11-23):** the port list says what each port is for (church, product, web or API,
linked to the install); a church server's hand-written frpc tunnels are listed as taken on each frp
config read. frps's allow_ports is checked against the port list (the Hub's range plus listed ports
outside it): an alert and Edit → Use the Hub's allow_ports when it leaves ports out. No migration.
Deployed 2026-11-23.
- **Hub 2.19.0 (2026-11-23):** the server agent's releases: a release source for the Server agent (in
the defaults: `agent@` tags, notes in `apps/agent/WHATS-NEW.md`), shown on the Releases page with how
many servers run each. Update agent picks a release (Latest by default, with its notes); the
Servers pages say when a newer agent is out. **Migration** (`AgentRelease`): run `prisma migrate
deploy`. A saved list of sources gets an "Add the agent's source" button.
Deployed 2026-11-23.
- **Hub 2.18.0 (2026-11-23):** releases are picked from a list, not typed: New install and Move onto
the monorepo (Events from 2.2.0) as well as an install's Update and the Updates page. Latest first,
then the newest 10, with Show older versions for the rest. Plan for agent releases (2.19.0) in the
Hub's `docs/VERSION-PICKERS-PLAN.md`. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **Hub 2.17.0 (2026-11-23):** popups on the remaining pages: a server's configuration and Update
agent, the frp config (read-only on the card, Edit with the two-factor code), install defaults and
Mark as taken (Ports & defaults), Clear public key and notes on an install, and an invoice's lines
(Edit for drafts and approved ones; Void and Refund instead of the browser's prompt). Settings
forms that are the page itself stay as they are. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **Hub 2.16.0 (2026-11-23):** every add and edit on the list pages is a popup like the customer
and install pages: Add server (the join command in the same popup), Add customer, New install,
Link existing, notices and releases (new and edit), release sources (a table; Edit opens the rows
and the token) and One-off invoice on Billing (with a church picker; `/billing/invoices/new` opens
it). Plan for the rest in the Hub's `docs/POPUPS-PLAN.md`. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **Hub 2.15.0 (2026-11-23):** an install's page (Servers → Installs → one install) is a header
(status, Schedule update, a ⋯ menu for move onto the monorepo, demo site, uninstall and the two
removals) with tiles for the site, version, server, ports and last heartbeat, then tabs: Jobs,
Settings (.env), Exports. Every action is a popup like the customer page's, the .env files too
(the tab shows the values, Edit opens a file). Banners for not registered, no heartbeat and a
planned uninstall. Confirmations unchanged. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **Hub 2.14.0 (2026-11-23):** the customer page is a summary header (products, owing, next invoice
with its estimate, address, AI) and three tabs: Overview, Products, Invoices and payments. Every
add and edit is a popup; each product is one card (licence and billing, one Save, suspend/revoke/
release in a ⋯ menu); contact and billing details are one form; the history is one timeline with
a filter. Record payment is a popup on Billing too. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **crosscode.co.za 1.6.1 (2026-11-23):** the web address choices on the Cross Events page are three
cards (name, price, "best if", an example address, short points); the option names were white on
a light background and couldn't be seen. Prices unchanged. Deployed 2026-11-23.
- **Hub 2.13.0 (2026-11-23):** alerts can be cleared by hand (one, or Clear all); a cleared alert
stays away until its problem is fixed and comes back, and isn't emailed again meanwhile. Billing
invoices, payments and churches, and a customer's invoices and payments, can be sorted by column
(remembered per browser). Fixed a stray scrollbar beside tab rows. Migration
`20261123120000_alert_cleared`.
- **Agent 1.5.0 + contracts 1.16.0 + Hub 2.12.0 + `crosscode` script (2026-11-23):** uninstalling
one product no longer removes the whole church (it removed cross-events-demo's Accounts with its
Events, which the Hub still showed as live). `crosscode uninstall|export|purge <church>
[product …]`; the last product to go removes the church. On the Hub: a second product's
uninstall can join one already planned or get its own time; Accounts goes last; a stale install
(no heartbeat for 24 hours) can be removed from the Hub; customers can be archived; a customer's
email and billing email take several addresses; statements show R0 invoices' amounts. **Update
the agents first** (the Hub refuses a one-product uninstall on an older agent while the church
has other products), then deploy the Hub (migration `20261123090000_customer_archive`).
- **Agent 1.4.0 + contracts 1.15.0 + Hub 2.11.0:** the agent finds frps's / frpc's config wherever
it is (the path set on the Hub, the systemd unit's `-c`, the usual places) and reads TOML too;
each server's Hub page reads and changes that config (secrets stay on the server, `verify`,
backup, restart, put back if frp doesn't start, two-factor); a new install first checks its
ports are free on the central server and the church server (`probe-ports`) and runs on a pair
free on both. Update the agents first (central and church), then deploy the Hub (migration
`20261121110000_server_frp_config`). With older agents the Hub installs as before, with a warning.
- **`crosscode` script (2026-11-20, later):** the database dump made before each Accounts deploy
(`backend/backups/`) no longer stops the next deploy as "added by hand" on Accounts below 1.3.0.
Released by pushing `main`; the next Hub job pulls it.
- **Hub 2.10.0:** every Hub email (job reports, alerts, emails to church admins, notices) laid out
as Events' and Accounts' are. The FastPanel email gives `location ^~ /api/` to paste, and Proxy
done refuses a site whose `/api` files reach the frontend. No migration.
- **Events 3.6.1 (fix):** logo and favicon uploads failed on events-demo: FastPanel's static-file
rule sent every `/api/…` path with a file extension to the frontend. The site now passes those on
to the backend. Also change the FastPanel site (HANDOVER.md, "FastPanel sites"). No migration.
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp) after every sign-in, as Cross Events'
own sign-in sends; admins can turn it off. No migration.
- **Events 3.6.0 + Accounts 1.5.0 + contracts 1.14.0:** a nightly people check (Events asks Accounts
about everyone with an account, 500 at a time, `people.check`): out-of-date copies are fixed,
deleted accounts handled as `user.deleted`, and it stops if most people are unknown. Update
Accounts first (Events skips the check with an older one). No migrations; the Hub is unchanged.
- **Events 3.5.0 + contracts 1.13.0 + agent 1.3.1 + Hub 2.9.0:** loading demo data no longer deletes
the Accounts link (on events-demo nobody could sign in); a site in Accounts mode without a link
reconnects at its next heartbeat; the heartbeat says how the site signs in and the last failure,
and the Hub alerts when it isn't linked, is linked wrongly or sign-ins fail. **Agent 1.3.0
reported itself as 1.2.0**, so the Hub refused its .env jobs: install 1.3.1. No migrations.
- **Events 3.4.0 + Accounts 1.4.0 + contracts 1.12.0 + agent 1.3.0 + Hub 2.8.0:** background jobs
switched on and off (and rescheduled) from each site's admin, over the .env (saved in the
database, no migration); Accounts' emails styled as Cross Events'; the Hub shows an install's
.env (secrets only as set or not) and changes plain values with a restart or frontend rebuild
(`env-read` / `env-set` jobs, `crosscode env`; the file is put back if the site doesn't start).
The Hub's .env panel needs agent 1.3.0 on the server. No migrations.
- **Events 3.3.0 + Accounts 1.3.0 + contracts 1.11.0:** Accounts' pages in Cross Events' layout
(sidebar, a page per section), quick links to the church's sites, nightly backups (Admin →
Backups; needs `pg_dump` on the server), a fuller built-in privacy notice, a fixed favicon.
@@ -107,8 +212,9 @@ 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 |
| Hub | 2.20.0 | 2026-11-23 | Port list says what each port is for; hand-written frpc tunnels listed as taken; frps allow_ports checked against the port list (no migration) |
| Agent on church-server1 | 1.5.0 | 2026-11-23 | Uninstalls one product of a church at a time |
| Agent on the central server | 1.5.0 | 2026-11-23 | Reads and changes frps's config from the Hub (no longer read-only; decision 35 superseded) |
| Cross Events (churches) | 3.6.1 | 2026-11-20 | Every install adopted onto the monorepo and signing in through Accounts |
| Accounts (churches) | 1.6.0 | 2026-11-20 | |
| crosscode.co.za | 1.6.1 | 2026-11-23 | Clearer web address choices on the Cross Events page |
+458
View File
@@ -0,0 +1,458 @@
# Church Website 1.0.0 — the church's own public site
Phase **5** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§6, §9, §10, §11; decisions 19, 20, 40–47).
Written 2026-11-21. **All decisions confirmed by Joshua on 2026-11-21** (12 changed: a full
storage stops uploads). Not started.
**Updated 2026-11-24:** the Hub release is **2.21.0**, not 2.13.0 (the Hub reached 2.20.0 on
2026-11-23 with other work). The 8 font pairings in §3 ("Font pairings") were **confirmed by Joshua
on 2026-11-24** (decision 15).
**What the Website is:** the church's public site at `www.<church's address>` (or
`<church>.crosscode.co.za` on the Cross Code address), plus its admin at `/admin`. Admins sign in
through the church's Accounts. The church picks one of **four templates** and makes it its own with
section layouts, style settings and its own pages. Changes are drafts until an admin **previews**
the whole site and presses **Publish**. Until the first publish, visitors see a **Coming soon**
page. The Website, Cross Events and (later) the App share the church's **brand style** (colours,
logo, fonts, corners) and **footer**, so the three feel like one church.
**Who uses 1.0:** Hope Family Church first, then a second test church on a different template, to
prove it repeats. Then it goes on sale (crosscode-site, ROADMAP §9).
**Done when:**
- `website@1.0.0`, `contracts@1.17.0`, `accounts@1.7.0`, `events@3.7.0` and Hub `v2.21.0` are
tagged; the Hub installs the Website from New install (after Accounts) and lists its releases.
- All four templates pass the same checks (§13) at phone, tablet and desktop sizes: layout, axe, the
§11 SEO checks, and Lighthouse (SEO 100, accessibility 95+, performance 90+).
- An editor can change anything, preview the whole site as a visitor would, share the preview, and
publish it all at once. An earlier version can be restored.
- Switching template keeps all content, and the preview shows the switch before it goes live.
- Cross Events' public pages use the church's fonts and the shared footer.
- Hope Family Church and a second church are live on different templates.
- crosscode-site sells it (ROADMAP §9, "Updating crosscode-site").
## Contents
1. [The shape](#1-the-shape)
2. [Content: shared and Website-only](#2-content-shared-and-website-only)
3. [Templates and customisation](#3-templates-and-customisation)
4. [Drafts, preview and publish](#4-drafts-preview-and-publish)
5. [Coming soon](#5-coming-soon)
6. [Pages](#6-pages)
7. [Messages](#7-messages)
8. [Events](#8-events)
9. [Connected with Events and the App](#9-connected-with-events-and-the-app)
10. [Admin, roles and storage](#10-admin-roles-and-storage)
11. [Hub, licence and servers](#11-hub-licence-and-servers)
12. [What changes in each repo](#12-what-changes-in-each-repo)
13. [Testing](#13-testing)
14. [Releasing and rolling it out](#14-releasing-and-rolling-it-out)
15. [Decisions](#decisions)
16. [Still open](#still-open)
## 1. The shape
`apps/website`, the same stack as Events and Accounts (decision 8 in the roadmap): an **Express +
Prisma + pg-boss backend** (TypeScript) and a **Next.js frontend**, one PostgreSQL database, served
on one address with `/api` to the backend (`location ^~ /api/` in FastPanel, HANDOVER "FastPanel
sites").
```
visitor ─► www.hopefamily.co.za ─► Next.js (server-rendered from the published version, cached)
│ template + section variants + style → HTML
editor ──► /admin (signed in through Accounts, @crosscode/auth-client)
edits the working copy ─► /admin/preview: the whole site from the working copy
Publish ─► a new SiteVersion (snapshot) ─► public pages revalidated
backend: content API (/api/v1/admin/…), public API (/api/v1/site/…), uploads (/api/uploads/…),
event feed (/api/links/v1/*, as Events 2.4), Hub client (protocol v2, product "website"),
jobs (YouTube feed, storage count, sitemap, feed sync)
Accounts ── crosscode.church/1 (name, logo, colours, service times, contact, social, brand style)
Events ──── crosscode.event/1 (the event feed, both directions)
```
- **Rendering:** public pages are server components rendered from the **latest published
version** and cached; Publish revalidates them. Preview renders the same components from the
**working copy**, uncached. Visitors and the preview run the same code, so the preview is exactly
what will go live.
- **Shared packages:** `@crosscode/ui` (branded shell, footer, fonts, form fields, now also the
public site's building blocks), `@crosscode/seo` (meta, JSON-LD, sitemap), `@crosscode/auth-client`
(sign-in), `@crosscode/contracts`.
## 2. Content: shared and Website-only
**The rule:** facts that more than one product shows live in the **church profile**
(`crosscode.church/1`, owned by Accounts). How the Website presents them, and anything only the
Website shows, lives in the **Website's own database**. Leaders, ministries, About, giving and
messages stay **Website-only for now** (decision 5), and can move into the profile when the App needs
them (phase 6–7).
| Shared: `crosscode.church/1` | Website-only |
|---|---|
| Already there: name, short name, logo, icon, colours, campuses, service times, contact, social, links | Template, section variants, style settings other than fonts and corners (§3), homepage order |
| **New in contracts 1.17.0:** `branding.style`: `fontPairing` (an id from the shared list, §3) and `corners` (`sharp` / `soft` / `round`). Optional and additive, so a minor version | Pages, sections and blocks, navigation, custom pages |
| | About (story, mission, vision, values, beliefs), Plan your visit, Leaders, Ministries, Give |
| | Messages and series (§7), simple events (§8), media library, per-page SEO |
| | Drafts, published versions, preview links |
- **Editing shared facts from the Website** (decision 10): the Website's admin shows the profile's
fields where they're used (service times on the Service times screen, the logo on Branding) and
saves them through **Accounts' API** with the admin's token, as ACCOUNTS-1.0-PLAN §7 proposed.
Accounts → Church profile stays the other way in.
- **Shared facts aren't drafts:** Accounts has no draft state, and Events shows the profile too.
A change to a shared fact goes live in every product straight away, and the Website's screens
say so ("Changes here show on all your church's sites at once"). The preview always shows the
current profile.
- **Legal pages:** the privacy notice is Accounts' (the version people agreed to), linked from the
footer. The Website adds its own terms and safeguarding pages from starter text.
- **Content is never tied to a template.** Every section stores its data (validated with a zod
schema per section type) and its chosen variant. Switching template keeps the data, and each
template maps every variant to its nearest look.
## 3. Templates and customisation
Four templates, decided in decision 19: **Heritage, Bold, Community, Clean** (ROADMAP §6). Rather
than adding more templates (more looks, but churches on the same one still look the same), each
template has room to vary in four ways, within limits that keep every site designed, accessible
and fast (decision 1).
**1. Template = structure.** The header and navigation style, the page rhythm, the default homepage
order and which variant each section starts with.
**2. Section variants.** Every section type comes in two or three layouts, and every template can
render every variant in its own style.
| Section | Variants |
|---|---|
| Hero | Photo · Video (muted, with a still for phones and reduced motion) · Collage · Split (image and text) · Text only |
| Service times and location | Panel · Inline strip · With map |
| Welcome / introduction | Text · Image and text · With pastor's photo and quote |
| Ministries | Cards · List · Alternating bands |
| Team / leaders | Faces grid · List · Featured (one large, rest small) |
| Upcoming events | Cards · List · Calendar strip |
| Latest message | Large video · Card · Compact |
| Invitation (call to action) | Banner · Centred · Image background |
**3. Style settings**, on one screen with a live preview:
| Setting | Options | Shared? |
|---|---|---|
| Font pairing | 8 pairings in a shared list (self-hosted, no Google Fonts requests); each template marks 3 as recommended, all 8 work everywhere | **Shared** (Events, Accounts, App) |
| Corners | Sharp · Soft · Round | **Shared** |
| Colours | From the profile (primary, accent); tints and shades built and contrast-checked (WCAG AA, darkened or lightened automatically, with a note why) | **Shared** (already) |
| Section colour | Light · Tinted (the church colour as a soft background) · Mixed with dark bands | Website |
| Spacing | Airy · Compact | Website |
| Buttons | Solid · Outline · Pill | Website |
| Image treatment | Natural · Black and white · Duotone in the church colour | Website |
| Header | Each template's options (e.g. Bold: transparent over the hero, or solid) | Website |
**4. Pages from blocks.** Besides the fixed pages (§6), churches add **custom pages** (Youth camp,
Our history, Kids…) from blocks: text, image and text, gallery, quote, video, FAQ, map, people
cards, call to action, divider. Blocks come in the same variants and follow the style settings.
**Not in 1.0:** free drag-and-drop layout, custom CSS, custom fonts. Each would break phone
layouts, accessibility or speed for some churches, and create support work. More templates can come
in 1.x (they're part of the product, ROADMAP §1 rule 3).
**Photos:** the setup checklist explains what photos work (people, not buildings; landscape for
heroes). The duotone treatment makes uneven photos look consistent. Every image needs alt text.
Uploads are resized into responsive sizes (WebP and JPEG).
### Font pairings (confirmed 2026-11-24)
Eight pairings, a heading font and a body font each. All are **SIL Open Font License 1.1** (free to
self-host and bundle; the licence text ships with them), all are **variable fonts** (one file per
style covers every weight) and all cover **Latin Extended** (Afrikaans ê, ë, ô and names from other
languages). The id is what `branding.style.fontPairing` stores, so ids never change once released;
names and fonts shown to churches can.
| Id | Shown as | Headings | Body | Feel | Recommended for |
|----|----------|----------|------|------|-----------------|
| `classic` | Classic | Lora | Source Sans 3 | Traditional serif headings, a plain readable body | Heritage, Clean |
| `scholarly` | Scholarly | EB Garamond | EB Garamond | Old-style book type throughout; dignified | Heritage |
| `editorial` | Editorial | Playfair Display | Inter | High-contrast magazine headlines over a neutral body | Heritage, Bold |
| `impact` | Impact | Oswald | Source Sans 3 | Tall condensed headlines, uppercase-friendly; loud over photos | Bold |
| `contemporary` | Contemporary | Outfit | DM Sans | Geometric, modern, light-handed | Bold, Community, Clean |
| `friendly` | Friendly | Nunito | Nunito | Rounded ends throughout; warm and informal | Community |
| `warm` | Warm | Fraunces (soft) | Nunito Sans | A soft, characterful serif with a gentle sans | Community |
| `modern` | Modern | Inter | Inter | One neutral sans, tight headings; lets colour and photos lead | Clean |
Each template recommends three (its first is the default when a church picks that template):
| Template | Recommended (default first) |
|----------|-----------------------------|
| Heritage | `classic`, `scholarly`, `editorial` |
| Bold | `impact`, `contemporary`, `editorial` |
| Community | `friendly`, `warm`, `contemporary` |
| Clean | `modern`, `classic`, `contemporary` |
**Why these:** two each of traditional serif, display serif, strong sans and soft sans, so every
template has a real choice of mood; every pairing is recommended at least once. Avoided: script and
handwritten faces (hard to read, poor in long text), fonts that only exist as static weights (many
files, slower), and very thin display faces (fail contrast at small sizes).
**How they're served** (`packages/ui`):
- From the `@fontsource-variable/*` npm packages, pinned in the lockfile and copied into each app's
build; no request leaves the church's site (decision 13).
- Only the Latin and Latin Extended subsets, `woff2` only. A pairing is at most four files (heading
and body, upright and italic; one family = two). Budget: **≤ 160 KB per pairing** for the files a
page actually uses; checked in CI.
- The heading font is preloaded; the body font is not. `font-display: swap` with a metric-matched
fallback (`size-adjust`, `ascent-override`) on Georgia or Arial, so swapping doesn't shift the
layout (CLS, the Lighthouse target in §13).
- CSS variables `--cc-font-heading` and `--cc-font-body` from the profile, next to the colours and
`--cc-radius` (corners).
**A church without a `fontPairing`** (every church today): the Website uses its template's default;
Events and Accounts keep the system fonts they use now, so Events 3.7 and Accounts 1.7 look the same
until an admin picks a pairing. `corners` missing means `soft`.
## 4. Drafts, preview and publish
Decision 2: **one Publish for the whole site.**
- **The working copy** is the content tables the admin edits. **A published version** is an
immutable snapshot of all of them (`SiteVersion`: JSON, who, when, an optional note). Visitors
always see the latest published version.
- **Pending changes:** the admin header shows "N changes not published". The Publish screen lists
each change (page, section, setting; who made it, when), and any one can be **discarded** (back
to its published value).
- **Preview** (`/admin/preview`, or the Preview button anywhere): the whole site from the working
copy, **fully clickable** (navigation, events, messages, video), with a bar on top: phone /
tablet / desktop width, "Back to editing", the change count and **Publish**. The bar is outside
the page, so the page is laid out exactly as it will be.
- **Share a preview:** a link (`/preview/<token>`) for someone without an account, e.g. the pastor.
It expires after 7 days (or when revoked), shows the working copy as it is when opened, sends
`noindex`, and can't edit or publish.
- **Version history:** every publish is kept. **Restore** copies a version back into the working
copy, so it's previewed and published like any other change; nothing is lost.
- **Two editors at once:** one shared working copy, saved per field. A field changed by someone else
since it was opened warns before it's overwritten. Publish publishes everyone's changes, and the
list shows whose they are.
- **What doesn't wait for Publish** (decision 9): simple events and messages are things that happen
rather than the site's design, so each has its own Publish (and messages found automatically on
YouTube appear on their own, §7). Changes to shared profile facts go live straight away (§2).
- **Template switch:** the new template is a pending change like any other, so the whole site can be
previewed in it before publishing.
- Every publish, discard and restore is in the audit log.
## 5. Coming soon
Decision 3: until the site's **first publish**, the public address shows a **Coming soon** page, not
an empty site.
- From the church profile: logo, name, colours and fonts, service times and address, contact
details, social links, and buttons to the church's Events (and App) when they're linked. A short
"Our new website is on its way" line the admin can change.
- `noindex`, an empty sitemap, `robots.txt` as usual. Real HTTP 200, so the church's details are
still useful to someone who finds the address.
- Signed-in admins see a banner on it: "Your site isn't published yet. Preview it or publish it."
- After the first publish there is no going back to Coming soon in 1.0 (unpublishing isn't needed).
## 6. Pages
As ROADMAP §6, with these changes:
- **Contact:** **contact details only** (decision 4): address with a map, phone, email, WhatsApp,
service times, social links. No contact form (personal information belongs in the App, §6 "Not in
the first release").
- **Give:** information and the church's provider links (SnapScan, Zapper, PayFast page, bank
details as text). No giving processed.
- **Events:** list, detail, calendar, past (§8).
- **Messages:** list, series, detail (§7).
- **Home:** the sections in the template's order; the church can reorder, hide and show them.
- Every page: unique title and description, canonical, Open Graph image (generated from the logo and
colours when the page has none), JSON-LD (`Church` on home and contact, `Event`, `VideoObject`,
`BreadcrumbList`), exactly one `<h1>`, `lang="en-ZA"`. Slug changes get a 301 to the new slug
(within the site; moving domains is decision 6).
## 7. Messages
Decision 7: two ways in, chosen in **Messages → Settings**:
- **From YouTube, automatically.** The admin gives the church's **channel** or a **playlist** (a
playlist is better when the channel has other uploads). A job reads YouTube's public feed
(`youtube.com/feeds/videos.xml?channel_id=…` / `?playlist_id=…`, no API key) every hour, and each
new video becomes a message (title, date, thumbnail, video). Admins can add the speaker, series,
Bible passage and notes afterwards, or hide one. The newest is the home page's **Latest message**.
- **By hand.** Add a message with a **YouTube or Spotify link** (episode or show) and the same
details.
Both can be used together. Embeds load only when clicked (a thumbnail first), use
`youtube-nocookie.com`, and set `VideoObject` (or `PodcastEpisode` for Spotify) JSON-LD. Audio and
video are never uploaded (ROADMAP §10), so they don't count towards storage.
## 8. Events
- **Simple events** made in the Website (title, date and time, place, description, image, an
optional link). Only Cross Events takes registrations and payments (roadmap decision 4).
- **The event feed** as Events 2.4: Settings → Linked products, "Publish my events" and "Show events
from". Events from Cross Events show in the template's event cards and link through to Cross
Events for registering.
- **Imported events** carry `<link rel="canonical">` to the origin's page and aren't in the
Website's sitemap (ROADMAP §11). A source that's down keeps its last events showing.
## 9. Connected with Events and the App
Decision 8. The three products look like one church without looking like each other:
- **Brand style is shared** (§2, §3): the same colours, logo, font pairing and corners in the
Website, in Cross Events' public pages and Accounts' sign-in pages, and later in the App.
- **One footer.** `@crosscode/ui` gets a `ChurchFooter` built from the profile (logo, service times,
address, contact, social, links to the church's Website, Events and App, the privacy notice). The
Website uses it in every template (styled by the template), Events 3.7 and Accounts 1.7 use it on
their public pages.
- **Links between products:** each product's header has a link to the others that exist (from the
profile's `links`): "Events", "Website", later "App".
- **One sign-in and account menu** (already, through Accounts).
- **Events 3.7.0:** public pages (event list and detail, registration, the church's home) use the
shared fonts, corners and footer. Admin and staff screens stay as they are. Nothing else changes.
## 10. Admin, roles and storage
**Admin** (`/admin`, as ROADMAP §6): dashboard with the setup checklist ("Choose your template"
first, previewed with the church's own logo, colours and content, or sample content), pending
changes and recent edits; Template and style; Pages; About; Leaders; Ministries; Messages; Events;
Media library; Contact and service times; Navigation; Settings (SEO, search engine verification,
linked products, email); Version history; Audit log. Each field shows the Google-style snippet
preview and SEO warnings where they apply (ROADMAP §11).
**Roles** (per product, held in the Website; proposed in decision 11):
| Role | Can |
|---|---|
| Owner | Everything, including roles and the licence |
| Admin | Everything but the licence and Owners |
| Editor | Edit everything, preview, share previews, **publish** |
| Ministry leader | Edit their own ministry's page and events; their changes wait for an Editor or above to publish |
| Viewer | See the admin and the preview, change nothing |
Admin roles can require 2FA through Accounts (`acr_values=mfa`, ACCOUNTS-1.0-PLAN decision 8): on by
default for Owner and Admin.
**Storage** (ROADMAP §10): 5 GB of uploads included. Settings shows what's used; admins get an email
at 80% and at 100%. **When it's full, uploads stop** (decision 12) until more storage is bought:
the media library and every upload field say so, with **Get more storage** (Settings → Storage).
That asks the Hub, as Request update does, and the Hub emails Joshua. Once he adds a 5 GB step to the
licence, the new limit reaches the site with the next heartbeat answer (within a minute or so) and
uploads work again. Everything already uploaded keeps showing; only new uploads are refused. The
limit is the licence's (5 GB plus the steps bought), never the site's own setting. An upload is
only freed when neither the working copy nor the last 10 published versions use it.
## 11. Hub, licence and servers
- **Hub protocol v2, product `website`.** The heartbeat's `websiteStatsSchema` is already in the
contracts (pages, messages, events, editors, storage). A Website licence needs the church's
Accounts, installed first (as Events 3.x).
- **Hub 2.21.0:** New install offers the Website; release sync for `website@` tags and
`apps/website/WHATS-NEW.md`; its env template; the Website's price (R99) and the storage add-on
(R20 per extra 5 GB, sent to the site with the licence as its storage limit, and the "Get more storage"
request with its email to Joshua) in `frontend/src/lib/tiers.ts` and `backend/src/utils/billing/tiers.js`, in
step with crosscode-site; the FastPanel email for `www.` (and the bare domain sent to `www.` with a
301, for an own domain) or `<church>.crosscode.co.za`.
- **`crosscode`:** `scripts/products/website.sh` with the same hooks as Events and Accounts (`website`
is already in `PRODUCT_ORDER`), `website.env.template.json`, `crosscode add <church> website`. The
env template in three places, plus any value rules (HANDOVER, "A new .env variable").
- **Agent:** none expected. The job schemas already take `website` (`releaseTagSchema`, `PRODUCTS`).
The frp port list gets the Website's two ports.
- **Accounts 1.7.0:** `branding.style` on the church profile (and Accounts → Church profile), the
Website as a client through Connect (as Events), the profile API allowing the Website's admins to
save, the shared fonts and footer on its pages.
- **Uninstall:** the church export (`crosscode.church-export/1`) gets a `website` section (content,
versions' notes, messages, events) and the uploaded media, as Events' export does its uploads.
- **Demo church:** `npm run demo` loads a fictional church (fictional people and photos only) into
each template, for the crosscode-site screenshots and the Hub's demo sites.
## 12. What changes in each repo
| Repo | Change | Version |
|------|--------|---------|
| `crosscode-platform` `apps/website` | New (§1–§11), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `website@1.0.0` |
| `crosscode-platform` `packages/contracts` | `branding.style` (`fontPairing`, `corners`) on `crosscode.church/1`, the font pairing ids, a `website` part of the church export | `contracts@1.17.0` |
| `crosscode-platform` `packages/ui` | Fonts (self-hosted), the theme from the profile (colours, fonts, corners as CSS variables), `ChurchFooter`, links between products, the public site's building blocks | workspace |
| `crosscode-platform` `packages/seo` | `Church`, `VideoObject`, `PodcastEpisode`, `BreadcrumbList` builders, the generated share image | workspace |
| `crosscode-platform` `apps/accounts` | `branding.style` in the church profile, the shared fonts and footer, the Website's admins saving the profile | `accounts@1.7.0` |
| `crosscode-platform` `apps/events` | Public pages with the shared fonts, corners and footer | `events@3.7.0` |
| `crosscode-platform` `scripts/` | `products/website.sh`, `website.env.template.json`, bats tests | — |
| `events-hub` | Website in New install, its releases, env template, prices and storage add-on, FastPanel email | Hub `v2.21.0` |
| `crosscode-site` | Church Website on sale (ROADMAP §9): its page, prices, a page per template, screenshots of the demo church, FAQ, `SoftwareApplication` JSON-LD | `v1.7.0` |
## 13. Testing
- **Unit (Jest):** section schemas and variants, the palette builder and contrast fixes, publish /
discard / restore, pending change lists, preview tokens (expiry, revoke, no edit rights), roles
(a Ministry leader can't publish or edit another ministry), the YouTube feed parser (channel,
playlist, duplicates, a removed video), storage counting, uploads refused when full (and allowed again when the licence's limit goes
up), uploads kept by older versions.
- **Playwright, every template at phone / tablet / desktop:** the demo church's pages look right
(screenshots compared), axe has no violations, the §11 checks (title, description, canonical,
`og:image`, one `<h1>`, JSON-LD parses, sitemap, `robots.txt`, `noindex` where it should be).
- **Playwright, the flows:** Coming soon before the first publish; edit → preview (click through
the site) → publish → the public site changes; discard one change; a shared preview link works
signed out and stops after revoking; restore an older version; switch template in preview and
back without losing anything; sign in from a deep admin page and land back on it (through 2FA).
- **Lighthouse (mobile):** home, an event and a message in each template: SEO 100,
accessibility 95+, performance 90+.
- **Events 3.7:** the e2e suite still passes, and its public pages show the church's fonts and the
shared footer.
- **The release checks** (ROADMAP §9) for the Website, and the **VM test**: install the Website
next to Accounts and Events through the agent, update it, uninstall it with its export.
## 14. Releasing and rolling it out
1. `contracts@1.17.0`, then `accounts@1.7.0` (the profile's brand style), then `events@3.7.0`.
2. Hub `v2.21.0` (vendored contracts 1.17.0) deployed.
3. `website@1.0.0` tagged after the e2e, Lighthouse and VM runs.
4. **Hope Family Church:** Accounts 1.7.0 and Events 3.7.0 first, then New install → Website. The
site shows Coming soon while the church builds it, and goes live with its first publish.
5. **A second test church** on a different template.
6. crosscode-site `v1.7.0`: the Website on sale.
## Decisions
Made by Joshua on 2026-11-21:
1. **Customisation within limits:** four templates, each with section variants, style settings and
custom pages from blocks (§3). No free layout, custom CSS or custom fonts. More templates later,
not instead.
2. **One Publish for the whole site,** after a fully clickable preview (§4), with a shareable preview
link and version history.
3. **Coming soon** until the first publish (§5).
4. **Contact page: details only,** no form (§6).
5. **Leaders, ministries, About, giving and messages are Website-only** for now (§2). Only the brand
style (font pairing, corners) is added to the shared profile.
6. **No address move or redirects in 1.0,** and no Hub "Change address" job yet. Moving to the
church's own domain (ROADMAP §10, §11 "Moving addresses") comes later.
7. **Messages from a YouTube channel or playlist automatically, or by hand with a YouTube or
Spotify link** (§7).
8. **The three products feel connected:** shared brand style and footer, and **Events 3.7** uses the
shared fonts and footer on its public pages (§9).
Proposed and confirmed on 2026-11-21 (12 changed):
9. **Simple events and messages publish on their own,** not with the site's Publish; YouTube messages
appear automatically (§4, §7).
10. **The Website's admin edits shared profile facts through Accounts' API,** and they go live
straight away (§2). Answers ACCOUNTS-1.0-PLAN's "Still open".
11. **Editors can publish; Ministry leaders' changes wait** for an Editor or above (§10).
12. **A full storage stops uploads** until more is bought (admins emailed at 80% and 100%; "Get more
storage" asks the Hub; §10). Changed from the proposal, which let uploads carry on and billed
afterwards.
13. **Fonts are self-hosted** (no Google Fonts requests, for POPIA and speed), from a shared list of 8
pairings (§3).
14. **Coming soon is a real page (HTTP 200) with `noindex`,** not a 503 (§5).
Confirmed on 2026-11-24:
15. **The 8 font pairings** in §3: `classic`, `scholarly`, `editorial`, `impact`, `contemporary`,
`friendly`, `warm`, `modern`, three recommended per template. A church without one keeps
the system fonts in Events and Accounts; `corners` defaults to `soft`.
## Still open
- The exact section variants per template: settled with the template designs, early in the build.
- Whether the App (phase 6) moves leaders, ministries and giving into `crosscode.church/1` or reads
them from the Website. Decide with the App plan.
+142 -7
View File
@@ -46,7 +46,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.3.0",
"version": "1.6.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -54,6 +54,7 @@
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
@@ -82,7 +83,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.3.0",
"version": "1.6.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -108,7 +109,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.2.0",
"version": "1.5.0",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*",
@@ -127,7 +128,7 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "3.3.0",
"version": "3.6.1",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
@@ -177,7 +178,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.3.0",
"version": "3.6.1",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -951,6 +952,23 @@
"keyv": "^5.6.0"
}
},
"node_modules/@capsizecss/core": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/@capsizecss/core/-/core-4.1.3.tgz",
"integrity": "sha512-d2sTTBwKuVioYxpwpU4URMp8VkFK+GI1VNGNawQcF8HBMHzCDa1FLcbeXJSzb5AJik7ZGv3aFVCTs7IS9MhvHg==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.1.1"
}
},
"node_modules/@capsizecss/metrics": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/@capsizecss/metrics/-/metrics-4.5.0.tgz",
"integrity": "sha512-BD0pz1JksZXEX9RLNtUCYYD72sQIVzOPIjaCAXPSz18lWdtPGmNbj6AVL2Q3n0trOLPOjZ9fnvtuAmSPv7yO1g==",
"dev": true,
"license": "MIT"
},
"node_modules/@cj-tech-master/excelts": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/@cj-tech-master/excelts/-/excelts-10.2.0.tgz",
@@ -1804,6 +1822,105 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@fontsource-variable/dm-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/dm-sans/-/dm-sans-5.3.0.tgz",
"integrity": "sha512-BpUG5bqePiDFMBM4ZtLSlPdAIOM990uB1dlXzIf4aw21yQR7BmykedLXXXMqGWsR18aMLOsbWccwJNh3ztTQaA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/eb-garamond": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/eb-garamond/-/eb-garamond-5.3.0.tgz",
"integrity": "sha512-656OJsA9Vv24yhqRZFEzXnzS2AYgKdEILLgHJYLzzXndgcWFKfSXFqzbRI5/6Yk1Yt7UfWrUeppE5nRQPQMwlQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/fraunces": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/fraunces/-/fraunces-5.3.0.tgz",
"integrity": "sha512-9BYGySn4AHEJdgp9Z28tQ3X+laJMEOITXkQarZXeloWQZDq5oOvXJ3kDA8c7MGIfpogIaZfjrQBqmda8POOCKA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/lora": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/lora/-/lora-5.3.0.tgz",
"integrity": "sha512-2ph8KiZ8Bn141hWuC3ErtpJ+Ui8p2MJQn8TJNRSRmLmnCIOCtHfiBM9R7WLRPeUG/q6hXyHOxWQ8DvRSX+ixvQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/nunito": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito/-/nunito-5.3.0.tgz",
"integrity": "sha512-tw0ch7evIDSwoeUy+0XzocYHfbRWLeCRPJy22KgbrLjDLAbNw/fErBiil10Ssrs3Sjr55zaZrr36a975j8cBkQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/nunito-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito-sans/-/nunito-sans-5.3.0.tgz",
"integrity": "sha512-Vk1PSfckNDwgw2yGcsvJP3o/0zEW8Rp6KzbD8Ql/6iRHQshnhhAjt+cSIfAUyp5vQuSlleGHFW2LfYaaex0diw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/oswald": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/oswald/-/oswald-5.3.0.tgz",
"integrity": "sha512-sSZzcTeaQGNyZbTVlS4tNNHElK38UktFLqKd6NQDLFCBV27320rQC3kXSZVytYm1PPjKmPxqVaGwqj7LEKUWQw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/outfit": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/outfit/-/outfit-5.3.0.tgz",
"integrity": "sha512-fPb5XnYK0k7SbR++HEmm4+ZqDszmLKQ+sPRUr8oQ/KNC0vy6r6hazJFe8iYozv4cqlHbvJ/JECkJWrfDodUMVQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/playfair-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/playfair-display/-/playfair-display-5.3.0.tgz",
"integrity": "sha512-IHdzTvE8eGIXHteZql7KXoqdc3Gfm+Zs1u4XlSC3MeplkwviT3sx/P6gI0tLwg/xIYLF4ZJYveZ5V+bl9cnDwA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/source-sans-3": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@fontsource-variable/source-sans-3/-/source-sans-3-5.3.1.tgz",
"integrity": "sha512-u0p5Z/PM2e1uxYOMiodLM6NVzxHwULcB6Oi7QSr2WU/sdoLBFP/BeOZ3YYHeJ6rHsjPZA1nZweZVaV7sf2MAyQ==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@humanfs/core": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
@@ -21275,7 +21392,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.11.0",
"version": "1.17.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
@@ -21319,7 +21436,25 @@
},
"packages/ui": {
"name": "@crosscode/ui",
"version": "0.1.0",
"version": "0.2.0",
"dependencies": {
"@fontsource-variable/dm-sans": "5.3.0",
"@fontsource-variable/eb-garamond": "5.3.0",
"@fontsource-variable/fraunces": "5.3.0",
"@fontsource-variable/inter": "5.3.0",
"@fontsource-variable/lora": "5.3.0",
"@fontsource-variable/nunito": "5.3.0",
"@fontsource-variable/nunito-sans": "5.3.0",
"@fontsource-variable/oswald": "5.3.0",
"@fontsource-variable/outfit": "5.3.0",
"@fontsource-variable/playfair-display": "5.3.0",
"@fontsource-variable/source-sans-3": "5.3.1"
},
"devDependencies": {
"@capsizecss/core": "4.1.3",
"@capsizecss/metrics": "4.5.0",
"@crosscode/contracts": "*"
},
"peerDependencies": {
"react": ">=19"
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/contracts",
"version": "1.11.0",
"version": "1.17.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",
@@ -0,0 +1,171 @@
{
"schema": "crosscode.church-export/1",
"exportedAt": "2026-12-10T12:00:00.000Z",
"product": "website",
"productVersion": "1.0.0",
"church": {
"name": "Grace Demo Church",
"timezone": "Africa/Johannesburg"
},
"people": [
{
"ref": "p1",
"name": "Thandi Example",
"email": "thandi@example.org",
"phone": null,
"role": "editor",
"createdAt": "2026-12-01T08:00:00.000Z",
"consent": {
"email": null,
"whatsapp": null,
"privacyNoticeAcceptedAt": null
}
}
],
"events": [],
"registrations": [],
"payments": [],
"checkIns": [],
"rosters": [],
"settings": {
"coming-soon.line": "Our new website is on its way"
},
"files": [
{
"path": "uploads/media/hero-sunday.jpg",
"bytes": 482113
},
{
"path": "uploads/media/carols.jpg",
"bytes": 203877
}
],
"website": {
"template": "community",
"firstPublishedAt": "2026-12-05T09:00:00.000Z",
"style": {
"sectionColour": "tinted",
"spacing": "airy",
"buttons": "pill",
"imageTreatment": "natural",
"header": "solid"
},
"pages": [
{
"ref": "g1",
"title": "Home",
"path": "/",
"kind": "home",
"inNavigation": true,
"seo": {
"title": null,
"description": "A family church in Meyerton. Join us on Sundays at 09:00."
},
"sections": [
{
"type": "hero",
"variant": "collage",
"hidden": false,
"content": {
"headline": "You belong here",
"images": [
"uploads/media/hero-sunday.jpg"
],
"button": {
"label": "Plan your visit",
"href": "/visit"
}
}
},
{
"type": "service-times",
"variant": "panel",
"hidden": false,
"content": {}
},
{
"type": "latest-message",
"variant": "card",
"hidden": true,
"content": {}
}
]
},
{
"ref": "g2",
"title": "Youth camp",
"path": "/youth-camp",
"kind": "custom",
"inNavigation": false,
"seo": {
"title": "Youth camp 2027",
"description": null
},
"sections": [
{
"type": "text",
"variant": "text",
"hidden": false,
"content": {
"heading": "Youth camp",
"body": "Three days away for grades 8 to 12."
}
}
]
}
],
"messages": [
{
"ref": "m1",
"title": "Hope that holds",
"date": "2026-12-07T07:00:00.000Z",
"speaker": "Pastor Sam Example",
"series": "Advent",
"passage": "Romans 15:13",
"notes": null,
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"source": "youtube-feed",
"hidden": false
}
],
"events": [
{
"ref": "w1",
"title": "Carols by candlelight",
"description": "Bring a blanket.",
"startsAt": "2026-12-20T17:00:00.000Z",
"endsAt": "2026-12-20T19:00:00.000Z",
"location": "The church lawn",
"link": null,
"image": "uploads/media/carols.jpg",
"published": true
}
],
"versions": [
{
"number": 1,
"publishedAt": "2026-12-05T09:00:00.000Z",
"by": "Thandi Example",
"note": "First version"
},
{
"number": 2,
"publishedAt": "2026-12-08T15:30:00.000Z",
"by": "Thandi Example",
"note": null
}
],
"media": [
{
"path": "uploads/media/hero-sunday.jpg",
"alt": "The congregation singing on a Sunday morning",
"caption": null
},
{
"path": "uploads/media/carols.jpg",
"alt": "Candles on the church lawn",
"caption": "Carols 2025"
}
]
}
}
@@ -0,0 +1,81 @@
{
"schema": "crosscode.identity-request/1",
"church": {
"schema": "crosscode.church/1",
"customerId": "c7a1e2d3-4b5c-4d6e-8f70-81a2b3c4d5e6",
"updatedAt": "2026-12-02T10:00:00.000Z",
"name": "Hope Family Church",
"shortName": "Hope Family",
"timezone": "Africa/Johannesburg",
"locale": "en-ZA",
"branding": {
"logoUrl": "https://www.hopefamily.co.za/uploads/logo.png",
"iconUrl": "https://www.hopefamily.co.za/uploads/icon-512.png",
"colours": {
"primary": "#1f4e79",
"accent": "#f2a900"
},
"style": {
"fontPairing": "warm",
"corners": "round"
}
},
"campuses": [
{
"slug": "meyerton",
"name": "Meyerton",
"address": {
"line1": "12 Church Street",
"line2": null,
"suburb": "Meyerton Central",
"city": "Meyerton",
"province": "Gauteng",
"postalCode": "1961",
"country": "ZA",
"geo": {
"lat": -26.5559,
"lng": 28.0141
}
}
}
],
"serviceTimes": [
{
"day": "sunday",
"time": "09:00",
"label": "Morning service",
"campus": "meyerton",
"note": "Kids church during the service"
},
{
"day": "wednesday",
"time": "18:30",
"label": "Prayer evening",
"campus": "meyerton",
"note": null
}
],
"contact": {
"email": "office@hopefamily.co.za",
"phone": "+27161234567",
"whatsapp": "+27821234567",
"address": null
},
"social": [
{
"network": "facebook",
"url": "https://www.facebook.com/hopefamilychurch"
},
{
"network": "youtube",
"url": "https://www.youtube.com/@hopefamilychurch"
}
],
"links": {
"website": "https://www.hopefamily.co.za",
"events": "https://events.hopefamily.co.za",
"app": null,
"accounts": "https://accounts.hopefamily.co.za"
}
}
}
@@ -0,0 +1,31 @@
{
"schema": "crosscode.identity-request/1",
"actor": "6b2c3d4e-5f6a-4b7c-9d8e-0f1a2b3c4d5e",
"requestId": "1f2e3d4c-5b6a-4978-8695-a4b3c2d1e0f9",
"type": "church.update",
"ifUpdatedAt": "2026-11-01T09:00:00.000Z",
"church": {
"branding": {
"style": {
"fontPairing": "warm",
"corners": "round"
}
},
"serviceTimes": [
{
"day": "sunday",
"time": "09:00",
"label": "Morning service",
"campus": "meyerton",
"note": "Kids church during the service"
},
{
"day": "wednesday",
"time": "18:30",
"label": "Prayer evening",
"campus": "meyerton",
"note": null
}
]
}
}
+2 -1
View File
@@ -9,7 +9,8 @@
"branding": {
"logoUrl": "https://www.hopefamily.co.za/uploads/logo.png",
"iconUrl": "https://www.hopefamily.co.za/uploads/icon-512.png",
"colours": { "primary": "#1f4e79", "accent": "#f2a900" }
"colours": { "primary": "#1f4e79", "accent": "#f2a900" },
"style": { "fontPairing": "warm", "corners": "soft" }
},
"campuses": [
{
@@ -0,0 +1,18 @@
{
"v": 1,
"licenceId": "5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e",
"installId": "6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f",
"customerId": "c7a1e2d3-4b5c-4d6e-8f70-81a2b3c4d5e6",
"product": "website",
"customer": "Hope Family Church",
"plan": "website",
"status": "active",
"licenceExpiresAt": "2027-10-31T21:59:59.000Z",
"graceDays": 14,
"issuedAt": "2026-11-03T10:15:00.000Z",
"validUntil": "2026-12-03T10:15:00.000Z",
"limits": {
"aiMonthlyCapCents": 0,
"storageBytes": 10737418240
}
}
@@ -0,0 +1,32 @@
{
"schema": "crosscode.identity-request/1",
"people": [
{
"sub": "6b2c3d4e-5f6a-4b7c-9d8e-0f1a2b3c4d5e",
"status": "active",
"profile": {
"name": "Thandi Mokoena",
"given_name": "Thandi",
"family_name": "Mokoena",
"email": "thandi@example.com",
"email_verified": true,
"phone_number": "+27821234567",
"phone_number_verified": false,
"news_consent": {
"email": true,
"whatsapp": false
}
}
},
{
"sub": "7c3d4e5f-6a7b-4c8d-8e9f-1a2b3c4d5e6f",
"status": "deleted",
"profile": null
},
{
"sub": "8d4e5f6a-7b8c-4d9e-9f0a-2b3c4d5e6f7a",
"status": "unknown",
"profile": null
}
]
}
@@ -0,0 +1,11 @@
{
"schema": "crosscode.identity-request/1",
"actor": null,
"requestId": "9e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b",
"type": "people.check",
"subs": [
"6b2c3d4e-5f6a-4b7c-9d8e-0f1a2b3c4d5e",
"7c3d4e5f-6a7b-4c8d-8e9f-1a2b3c4d5e6f",
"8d4e5f6a-7b8c-4d9e-9f0a-2b3c4d5e6f7a"
]
}
+600
View File
@@ -854,6 +854,250 @@
],
"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": "env-read"
},
"args": {
"type": "object",
"properties": {
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
}
},
"required": [
"church",
"product"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"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": "env-set"
},
"args": {
"type": "object",
"properties": {
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"product": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
},
"file": {
"type": "string",
"maxLength": 100,
"pattern": "^(backend|frontend)\\/\\.env(\\.production)?$"
},
"set": {
"type": "object",
"propertyNames": {
"type": "string",
"maxLength": 100,
"pattern": "^[A-Z][A-Z0-9_]*$"
},
"additionalProperties": {
"type": "string",
"maxLength": 4000,
"pattern": "^[^\\r\\n]*$"
}
},
"unset": {
"maxItems": 50,
"type": "array",
"items": {
"type": "string",
"maxLength": 100,
"pattern": "^[A-Z][A-Z0-9_]*$"
}
},
"restart": {
"type": "boolean"
}
},
"required": [
"church",
"product",
"file",
"set",
"unset",
"restart"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
@@ -933,6 +1177,20 @@
"exportId": {
"type": "string",
"pattern": "^exp_[A-Za-z0-9_-]{8,64}$"
},
"products": {
"minItems": 1,
"maxItems": 4,
"type": "array",
"items": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
}
}
},
"required": [
@@ -1029,6 +1287,20 @@
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"products": {
"minItems": 1,
"maxItems": 4,
"type": "array",
"items": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
}
}
},
"required": [
@@ -1124,6 +1396,20 @@
"church": {
"type": "string",
"pattern": "^[a-z][a-z0-9-]{1,30}$"
},
"products": {
"minItems": 1,
"maxItems": 4,
"type": "array",
"items": {
"type": "string",
"enum": [
"events",
"website",
"app",
"accounts"
]
}
}
},
"required": [
@@ -1431,6 +1717,320 @@
"args"
],
"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": "frp-read"
},
"args": {
"type": "object",
"properties": {
"path": {
"type": "string",
"maxLength": 255,
"allOf": [
{
"pattern": "^\\/(?!.*\\/\\.\\.?(\\/|$))[A-Za-z0-9._/-]+$"
},
{
"pattern": "\\/frp[A-Za-z0-9._-]*\\.(ini|toml)$"
}
]
}
},
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"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": "frp-write"
},
"args": {
"type": "object",
"properties": {
"path": {
"type": "string",
"maxLength": 255,
"allOf": [
{
"pattern": "^\\/(?!.*\\/\\.\\.?(\\/|$))[A-Za-z0-9._/-]+$"
},
{
"pattern": "\\/frp[A-Za-z0-9._-]*\\.(ini|toml)$"
}
]
},
"content": {
"type": "string",
"minLength": 1,
"maxLength": 64000
},
"restart": {
"type": "boolean"
}
},
"required": [
"path",
"content",
"restart"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"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": "probe-ports"
},
"args": {
"type": "object",
"properties": {
"ports": {
"minItems": 1,
"maxItems": 50,
"type": "array",
"items": {
"type": "integer",
"minimum": 1024,
"maximum": 65535
}
}
},
"required": [
"ports"
],
"additionalProperties": false
}
},
"required": [
"schema",
"id",
"serverId",
"notBefore",
"expiresAt",
"signature",
"type",
"args"
],
"additionalProperties": false
}
]
}
@@ -25,10 +25,15 @@
"adopt-undo",
"restart",
"seed-demo",
"env-read",
"env-set",
"export",
"uninstall",
"purge",
"update-agent",
"frp-read",
"frp-write",
"probe-ports",
"check-ports",
"status"
]
@@ -280,6 +280,17 @@
"type": "null"
}
]
},
"frpConfigPath": {
"anyOf": [
{
"type": "string",
"maxLength": 255
},
{
"type": "null"
}
]
}
},
"required": [
+474 -1
View File
@@ -656,6 +656,446 @@
"bytes"
]
}
},
"website": {
"type": "object",
"properties": {
"template": {
"type": "string",
"enum": [
"heritage",
"bold",
"community",
"clean"
]
},
"firstPublishedAt": {
"anyOf": [
{
"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))$"
},
{
"type": "null"
}
]
},
"style": {
"type": "object",
"propertyNames": {
"type": "string",
"maxLength": 100
},
"additionalProperties": {
"type": "string",
"maxLength": 200
}
},
"pages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"ref": {
"type": "string",
"pattern": "^g[0-9]+$"
},
"title": {
"type": "string",
"maxLength": 300
},
"path": {
"type": "string",
"maxLength": 300,
"pattern": "^\\/[a-z0-9/-]*$"
},
"kind": {
"type": "string",
"maxLength": 40
},
"inNavigation": {
"type": "boolean"
},
"seo": {
"type": "object",
"properties": {
"title": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
},
"description": {
"anyOf": [
{
"type": "string",
"maxLength": 500
},
{
"type": "null"
}
]
}
},
"required": [
"title",
"description"
]
},
"sections": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"maxLength": 60
},
"variant": {
"type": "string",
"maxLength": 60
},
"hidden": {
"type": "boolean"
},
"content": {
"type": "object",
"propertyNames": {
"type": "string",
"maxLength": 100
},
"additionalProperties": {
"$ref": "#/$defs/__schema0"
}
}
},
"required": [
"type",
"variant",
"hidden",
"content"
]
}
}
},
"required": [
"ref",
"title",
"path",
"kind",
"inNavigation",
"seo",
"sections"
]
}
},
"messages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"ref": {
"type": "string",
"pattern": "^m[0-9]+$"
},
"title": {
"type": "string",
"maxLength": 500
},
"date": {
"anyOf": [
{
"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))$"
},
{
"type": "null"
}
]
},
"speaker": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
},
"series": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
},
"passage": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
},
"notes": {
"anyOf": [
{
"type": "string",
"maxLength": 20000
},
{
"type": "null"
}
]
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
},
"source": {
"type": "string",
"enum": [
"youtube-feed",
"manual"
]
},
"hidden": {
"type": "boolean"
}
},
"required": [
"ref",
"title",
"date",
"speaker",
"series",
"passage",
"notes",
"url",
"source",
"hidden"
]
}
},
"events": {
"type": "array",
"items": {
"type": "object",
"properties": {
"ref": {
"type": "string",
"pattern": "^w[0-9]+$"
},
"title": {
"type": "string",
"maxLength": 500
},
"description": {
"anyOf": [
{
"type": "string",
"maxLength": 20000
},
{
"type": "null"
}
]
},
"startsAt": {
"anyOf": [
{
"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))$"
},
{
"type": "null"
}
]
},
"endsAt": {
"anyOf": [
{
"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))$"
},
{
"type": "null"
}
]
},
"location": {
"anyOf": [
{
"type": "string",
"maxLength": 500
},
{
"type": "null"
}
]
},
"link": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"image": {
"anyOf": [
{
"type": "string",
"pattern": "^uploads\\/[A-Za-z0-9._/-]+$"
},
{
"type": "null"
}
]
},
"published": {
"type": "boolean"
}
},
"required": [
"ref",
"title",
"description",
"startsAt",
"endsAt",
"location",
"link",
"image",
"published"
]
}
},
"versions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"number": {
"type": "integer",
"exclusiveMinimum": 0,
"maximum": 9007199254740991
},
"publishedAt": {
"anyOf": [
{
"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))$"
},
{
"type": "null"
}
]
},
"by": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
},
"note": {
"anyOf": [
{
"type": "string",
"maxLength": 1000
},
{
"type": "null"
}
]
}
},
"required": [
"number",
"publishedAt",
"by",
"note"
]
}
},
"media": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": {
"type": "string",
"pattern": "^uploads\\/[A-Za-z0-9._/-]+$"
},
"alt": {
"anyOf": [
{
"type": "string",
"maxLength": 500
},
{
"type": "null"
}
]
},
"caption": {
"anyOf": [
{
"type": "string",
"maxLength": 1000
},
{
"type": "null"
}
]
}
},
"required": [
"path",
"alt",
"caption"
]
}
}
},
"required": [
"template",
"firstPublishedAt",
"style",
"pages",
"messages",
"events",
"versions",
"media"
]
}
},
"required": [
@@ -672,5 +1112,38 @@
"rosters",
"settings",
"files"
]
],
"$defs": {
"__schema0": {
"anyOf": [
{
"type": "string"
},
{
"type": "number"
},
{
"type": "boolean"
},
{
"type": "null"
},
{
"type": "array",
"items": {
"$ref": "#/$defs/__schema0"
}
},
{
"type": "object",
"propertyNames": {
"type": "string"
},
"additionalProperties": {
"$ref": "#/$defs/__schema0"
}
}
]
}
}
}
@@ -0,0 +1,608 @@
{
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/church-update-reply.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"church": {
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.church/1"
},
"customerId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"updatedAt": {
"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))$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"shortName": {
"anyOf": [
{
"type": "string",
"maxLength": 30
},
{
"type": "null"
}
]
},
"timezone": {
"type": "string",
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
},
"locale": {
"type": "string",
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
},
"branding": {
"type": "object",
"properties": {
"logoUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"iconUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"colours": {
"type": "object",
"properties": {
"primary": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
"accent": {
"anyOf": [
{
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
{
"type": "null"
}
]
}
},
"required": [
"primary",
"accent"
]
},
"style": {
"type": "object",
"properties": {
"fontPairing": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"classic",
"scholarly",
"editorial",
"impact",
"contemporary",
"friendly",
"warm",
"modern"
]
},
{
"type": "null"
}
]
},
"corners": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"sharp",
"soft",
"round"
]
},
{
"type": "null"
}
]
}
},
"required": [
"fontPairing",
"corners"
]
}
},
"required": [
"logoUrl",
"iconUrl",
"colours"
]
},
"campuses": {
"maxItems": 50,
"type": "array",
"items": {
"type": "object",
"properties": {
"slug": {
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
]
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
]
},
{
"type": "null"
}
]
}
},
"required": [
"slug",
"name",
"address"
]
}
},
"serviceTimes": {
"maxItems": 100,
"type": "array",
"items": {
"type": "object",
"properties": {
"day": {
"type": "string",
"enum": [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
]
},
"time": {
"type": "string",
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
},
"label": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"campus": {
"anyOf": [
{
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
{
"type": "null"
}
]
},
"note": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
}
},
"required": [
"day",
"time",
"label",
"campus",
"note"
]
}
},
"contact": {
"type": "object",
"properties": {
"email": {
"anyOf": [
{
"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,}$"
},
{
"type": "null"
}
]
},
"phone": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"whatsapp": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
]
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
]
},
{
"type": "null"
}
]
}
},
"required": [
"email",
"phone",
"whatsapp",
"address"
]
},
"social": {
"maxItems": 20,
"type": "array",
"items": {
"type": "object",
"properties": {
"network": {
"type": "string",
"enum": [
"facebook",
"instagram",
"youtube",
"tiktok",
"x",
"spotify",
"whatsapp-channel",
"other"
]
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"network",
"url"
]
}
},
"links": {
"type": "object",
"properties": {
"website": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"events": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"app": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"accounts": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"website",
"events",
"app",
"accounts"
]
}
},
"required": [
"schema",
"customerId",
"updatedAt",
"name",
"shortName",
"timezone",
"locale",
"branding",
"campuses",
"serviceTimes",
"contact",
"social",
"links"
]
}
},
"required": [
"schema",
"church"
]
}
+46
View File
@@ -91,6 +91,52 @@
"primary",
"accent"
]
},
"style": {
"type": "object",
"properties": {
"fontPairing": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"classic",
"scholarly",
"editorial",
"impact",
"contemporary",
"friendly",
"warm",
"modern"
]
},
{
"type": "null"
}
]
},
"corners": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"sharp",
"soft",
"round"
]
},
{
"type": "null"
}
]
}
},
"required": [
"fontPairing",
"corners"
]
}
},
"required": [
@@ -324,6 +324,77 @@
"eventsNow",
"checkInsLastHour"
]
},
"signIn": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
]
},
"accounts": {
"anyOf": [
{
"type": "object",
"properties": {
"installId": {
"type": "string",
"maxLength": 100
},
"url": {
"type": "string",
"maxLength": 500
}
},
"required": [
"installId",
"url"
]
},
{
"type": "null"
}
]
},
"lastError": {
"anyOf": [
{
"type": "object",
"properties": {
"at": {
"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))$"
},
"code": {
"type": "string",
"maxLength": 60
},
"message": {
"type": "string",
"maxLength": 500
}
},
"required": [
"at",
"code",
"message"
]
},
{
"type": "null"
}
]
}
},
"required": [
"mode",
"accounts",
"lastError"
]
}
},
"required": [
@@ -78,6 +78,11 @@
"aiMonthlyCapCents": {
"type": "number",
"minimum": 0
},
"storageBytes": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
}
},
"required": [
@@ -856,6 +856,53 @@
"subs"
]
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"requestId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"actor": {
"anyOf": [
{
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
{
"type": "null"
}
]
},
"type": {
"type": "string",
"const": "people.check"
},
"subs": {
"minItems": 1,
"maxItems": 500,
"type": "array",
"items": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
}
},
"required": [
"schema",
"requestId",
"actor",
"type",
"subs"
]
},
{
"type": "object",
"properties": {
@@ -1261,6 +1308,548 @@
"church",
"overwrite"
]
},
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.identity-request/1"
},
"requestId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"actor": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"type": {
"type": "string",
"const": "church.update"
},
"ifUpdatedAt": {
"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))$"
},
"church": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"shortName": {
"anyOf": [
{
"type": "string",
"maxLength": 30
},
{
"type": "null"
}
]
},
"timezone": {
"type": "string",
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
},
"locale": {
"type": "string",
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
},
"branding": {
"type": "object",
"properties": {
"logoUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"iconUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"colours": {
"type": "object",
"properties": {
"primary": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
"accent": {
"anyOf": [
{
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
{
"type": "null"
}
]
}
},
"required": [
"primary",
"accent"
]
},
"style": {
"type": "object",
"properties": {
"fontPairing": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"classic",
"scholarly",
"editorial",
"impact",
"contemporary",
"friendly",
"warm",
"modern"
]
},
{
"type": "null"
}
]
},
"corners": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"sharp",
"soft",
"round"
]
},
{
"type": "null"
}
]
}
},
"required": [
"fontPairing",
"corners"
]
}
}
},
"campuses": {
"maxItems": 50,
"type": "array",
"items": {
"type": "object",
"properties": {
"slug": {
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
]
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
]
},
{
"type": "null"
}
]
}
},
"required": [
"slug",
"name",
"address"
]
}
},
"serviceTimes": {
"maxItems": 100,
"type": "array",
"items": {
"type": "object",
"properties": {
"day": {
"type": "string",
"enum": [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
]
},
"time": {
"type": "string",
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
},
"label": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"campus": {
"anyOf": [
{
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
{
"type": "null"
}
]
},
"note": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
}
},
"required": [
"day",
"time",
"label",
"campus",
"note"
]
}
},
"contact": {
"type": "object",
"properties": {
"email": {
"anyOf": [
{
"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,}$"
},
{
"type": "null"
}
]
},
"phone": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"whatsapp": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
]
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
]
},
{
"type": "null"
}
]
}
},
"required": [
"email",
"phone",
"whatsapp",
"address"
]
},
"social": {
"maxItems": 20,
"type": "array",
"items": {
"type": "object",
"properties": {
"network": {
"type": "string",
"enum": [
"facebook",
"instagram",
"youtube",
"tiktok",
"x",
"spotify",
"whatsapp-channel",
"other"
]
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"network",
"url"
]
}
}
}
}
},
"required": [
"schema",
"requestId",
"actor",
"type",
"church"
]
}
]
}

Some files were not shown because too many files have changed in this diff Show More