Compare commits

...
Author SHA1 Message Date
joshua 2a4cf7acab Merge branch 'feat/website-backups' 2026-11-27 09:50:35 +02:00
joshuaandClaude Opus 5.5 a3ac3da5a5 Website 1.4.0: nightly database backups and background jobs
As Accounts and Cross Events: a gzipped pg_dump every night (02:20) into
backend/backups/, the same website-*.sql.gz files crosscode makes before
updates, with Admin -> Backups (back up now, download, how many to keep).
The heartbeat, event feed and YouTube move from plain timers onto pg-boss
with the backup, and Admin -> Background jobs switches each on or off,
changes its schedule or runs it now. The heartbeat now reports the newest
backup (before: always none, so the Hub warned) and the real job state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:47:30 +02:00
joshua 8e52bd2d33 Merge branch 'docs/released-hub-2.25.0-website-1.3.0' 2026-11-27 09:31:08 +02:00
joshuaandClaude Opus 5.5 7b49ec2b70 docs: Hub 2.25.0, Website 1.3.0, agent 1.6.0, contracts 1.19.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:31:07 +02:00
joshua d3e04127f3 Merge branch 'feat/website-demo-seeds' 2026-11-27 09:30:15 +02:00
joshuaandClaude Opus 5.5 2fb7ac57da Website 1.3.0, agent 1.6.0, contracts 1.19.0: demo data for the Church Website
Eight demo churches, two per template (the second on the template's other
recommended variants and header), loaded from the Hub on demo sites with
`crosscode demo <church> website --profile <p>`. A profile replaces the
content only: the church's profile from Accounts, the site settings, the
site icon and the admins stay, and the copy names the church.

- contracts: WEBSITE_DEMO_PROFILES, DEMO_PRODUCTS, SEED_WEBSITE_DEMO_MIN_AGENT;
  seed-demo takes an optional product (events by default)
- agent: a Website seed-demo job runs `crosscode demo <church> website`
- crosscode script: backup, demo as the site's user, reload, health check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:20:09 +02:00
joshua 81c01d8a9f Merge branch 'docs/deployed-hub-2.24.1-website-1.2.0' 2026-11-27 08:44:56 +02:00
joshuaandClaude Opus 5.5 2335fd46e4 docs: Hub 2.24.1 deployed, Website 1.2.0 on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:44:55 +02:00
joshua f58711603a Merge branch 'docs/hub-2.24.1' 2026-11-27 08:36:19 +02:00
joshuaandClaude Opus 5.5 d1354a6a17 docs: Hub 2.24.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:36:18 +02:00
joshua 175a6b41eb Merge branch 'docs/hub-2.24.0' 2026-11-27 08:30:15 +02:00
joshuaandClaude Opus 5.5 80d8e903dd docs: Hub 2.24.0 deployed (Website 1.2.0 not on cross-demo2 yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:30:15 +02:00
joshua 35501deb0d Merge branch 'fix/website-starter-pages' 2026-11-27 08:18:53 +02:00
joshuaandClaude Opus 5.5 79e1450df6 Website 1.2.0: starter pages on a new install, and a site icon
A new install had no pages, so the home page and its live preview showed
only the header and footer (found on cross-demo2). The backend now adds the
fixed pages with starter text at startup. Settings -> Site icon sets the
favicon, with a default from the church's colour and initial. The Latest
message's Card layout has its name; the media picker's placeholder has
enough contrast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:18:47 +02:00
joshua 6905a19c8c Merge branch 'feat/admin-redesign' 2026-11-26 19:57:23 +02:00
joshuaandClaude Opus 5.5 dcc22a5c16 Accounts 1.8.0, Website 1.1.0: admins redesigned as Cross Events' dashboard and settings
- Website: an icon sidebar in groups (Your site, Content, Go live, Team), a
  dashboard with cards and a tile per part of the admin, steps to the first
  publish across the top of every admin page, and a live preview beside the
  page editor and Template and style (computer or phone width, folds away,
  reloads on save). A framed request (Sec-Fetch-Dest: iframe) with an admin
  session reads the drafts, so no preview cookie is set. /preview/start
  takes ?to=. The page editor has Content and Page details tabs.
- Accounts: /admin is an overview (cards, "Needs you", a tile per section);
  People moved to /admin/people; the sidebar shows the part you're in,
  grouped, with a count on Deletion requests; People redesigned, with a
  confirm before Deactivate; Email and WhatsApp split into two cards.
- Both: darker grey labels for contrast; lucide-react in the Website.
- e2e: the live preview shows drafts while the site stays live; axe on the
  page editor.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:57:22 +02:00
joshua e6c91c3705 Merge branch 'docs/deployed-cross-demo2' 2026-11-26 16:18:45 +02:00
joshuaandClaude Opus 5.5 925b5fbd8b docs: Accounts 1.7.1, Website 1.0.2, Events 3.7.1 deployed on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:18:44 +02:00
joshua 58cadbf472 Merge branch 'fix/link-after-install' 2026-11-26 16:14:20 +02:00
joshuaandClaude Opus 5.5 f6a536ad64 Accounts 1.7.1, Website 1.0.2, Events 3.7.1: link right after an install; Preview behind the proxy
Found installing the Website for cross-demo2.

- All three: a connect involving an install that isn't in the cached copy
  of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at
  most once a minute) instead of refusing. A new Website's admin couldn't
  sign in for up to 30 minutes.
- Accounts: a heartbeat on every start.
- Website: /admin links to Accounts on the spot (at most every 15 s), one
  connect to Accounts at a time, and the problem page says "not linked
  yet" (ACCOUNTS_NOT_LINKED). Preview redirected to the server's own
  http://localhost:<web port>: the preview routes now answer with a
  relative Location.
- Events: a new Website can connect for the event feed straight away.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:14:20 +02:00
joshua 05d808b74c Merge branch 'docs/hub-2.23.1' 2026-11-26 15:27:27 +02:00
joshuaandClaude Opus 5.5 20a23a3ba8 docs: Hub 2.23.1 deployed (Accounts version from the heartbeat)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:27:26 +02:00
joshua 9c9c96dd2c Merge branch 'docs/hub-2.23.0' 2026-11-26 15:11:58 +02:00
joshuaandClaude Opus 5.5 f73761f956 docs: Hub 2.23.0 deployed (requirements carry forward)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:11:57 +02:00
joshua 62441ad437 Merge branch 'docs/site-1.7.0' 2026-11-26 14:38:00 +02:00
joshuaandClaude Opus 5.5 7814a64cf7 docs: crosscode-site 1.7.0 released (the Website on sale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:37:59 +02:00
joshua 679f61febf Merge branch 'fix/website-1.0.1' 2026-11-26 14:36:35 +02:00
joshuaandClaude Opus 5.5 723bb15a5e website 1.0.1: thumbnails from the site, Calendar dates
- The messages' YouTube thumbnails are served from the site
  (/api/thumbnails/<id>.jpg): the backend fetches a message's thumbnail
  once and keeps it in uploads/.thumbnails (only the site's own videos,
  only a JPEG), so visitors ask nothing of YouTube before pressing play.
  The messages page preloads the first one (its LCP: Heritage 89 -> 95).
- Calendar events' dates read "Sun · November", not
  "Sun (month: November)".
- e2e: no request to YouTube or Spotify before play; the variant
  screenshots round section heights to whole pixels (a one-pixel flake);
  the e2e thumbnail is one of the demo's illustrations.
- crosscode script: a Website's export leaves out uploads/.thumbnails.
- docs: release checks on 1.0.1, VERSIONS, handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:36:34 +02:00
joshua dd0e5e17b3 Merge branch 'docs/website-release-checks' 2026-11-26 12:03:10 +02:00
joshuaandClaude Opus 5.5 7216035e49 docs: website release checks run again on the release build
Variants: axe passes everywhere, all 104 baselines taken (67 new to look
through). Lighthouse 11 of 12 (Heritage messages 89, the YouTube
thumbnail as LCP). Found: Calendar dates print "Sun (month: November)".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:03:10 +02:00
joshua 9bf1739734 Merge branch 'feat/website-release-checks' 2026-11-26 10:54:44 +02:00
joshuaandClaude Opus 5.5 0b99686ca7 website 1.0.0: release checks, contrast and map fixes
- e2e: every section variant in every template (axe and 312 screenshots
  compared with local baselines), Lighthouse on a phone (median of three,
  CPU slowdown calibrated to the machine), the whole suite on real Postgres
  with E2E_DATABASE_URL, a frozen clock, E2E_REUSE for running servers.
- Fixes found by them: contrast on Bold's service times panel and Calendar
  event dates; the OpenStreetMap embed loads only once on screen; the
  messages page's first thumbnail is eager, its host preconnected.
- The restore e2e waits for its second publish (raced on Postgres).
- docs: Hub 2.22.0 deployed; website@1.0.0 released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:54:43 +02:00
joshua 6ffad24db1 Merge branch 'docs/handover-tidy' 2026-11-25 16:29:08 +02:00
joshuaandClaude Opus 5.5 268c9cde88 docs: handover typo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:29:07 +02:00
joshua 9086b549a8 Merge branch 'docs/release-contracts-1.18-hub-2.22' 2026-11-25 16:28:43 +02:00
joshuaandClaude Opus 5.5 154bb94da7 docs: contracts 1.18.0 and Hub 2.22.0 released; Website status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:28:42 +02:00
joshua 312c32c6cb Merge branch 'feat/storage-request' 2026-11-25 16:18:48 +02:00
joshuaandClaude Opus 5.5 283e75737d contracts 1.18.0 + website: Get more storage
contracts: hub.storageRequestSchema and its reply, a sample and JSON
Schemas. Website: an Owner or Admin asks for more 5 GB steps under
Media library (signed to the Hub); the heartbeat reports the licence's
storage limit, so the Hub emails the church at 80% and when full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:18:46 +02:00
joshua 53e5de3f14 Merge branch 'feat/website-settings-seo' 2026-11-25 15:30:29 +02:00
joshuaandClaude Opus 5.5 085265392e feat(website): church details, settings, audit log, search engine data, safer editing
Church details saved through Accounts' church.update (live at once).
Settings: Search Console and Bing codes, Coming soon line, menu order.
Audit log and recent edits. A made share image, Event / VideoObject /
PodcastEpisode / BreadcrumbList structured data, permanent redirects
from old page addresses. Saves refused when someone else saved in
between; Ministry leaders' events; templates previewed with the
church's own content before choosing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:30:27 +02:00
joshua d8ed238042 Merge branch 'feat/website-event-feed' 2026-11-25 14:37:43 +02:00
joshuaandClaude Opus 5.5 b767b45e64 feat(website): the event feed both ways, and Linked products
Publish my events: the Website's simple events as crosscode.event/1
(GET /api/feed/v1/events, updatedSince, removals in deleted for 90
days) and a signed event.changed to linked siblings. Show events
from: each sibling's feed every 15 minutes and at once on its signed
event.changed; read-only copies of only that sibling's events, one
bad event skipped, the last good copy kept. Admin: Linked products.
church.changed from Accounts refreshes the profile at once. Plan:
the video hero, more blocks and more pages move to website@1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:37:42 +02:00
joshua 193a338ed2 Merge branch 'feat/website-image-sizes' 2026-11-25 14:04:44 +02:00
joshuaandClaude Opus 5.5 2ba755145d feat(website): photos upright, without metadata, in responsive sizes
Every upload is turned upright, stripped of its metadata (EXIF, GPS),
kept at most 2400 px wide and saved at 480/960/1600 px in WebP and
JPEG; the pages pick the size with <picture> and srcset. Every file
counts towards storage; a photo that can't be read is refused. sharp
0.35 (prebuilt, no build step on the servers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:04:43 +02:00
joshua 6be1a2782d Merge branch 'feat/website-people-messages-events' 2026-11-25 13:05:35 +02:00
joshuaandClaude Opus 5.5 37a1f6acf1 feat(website): people and roles, messages with the YouTube feed, simple events
People: Owners and Admins add someone by email (people.ensure through
Accounts), change roles, remove access; only Owners touch Owners,
nobody changes themselves, a lower role ends sessions at once.
Messages: from a YouTube channel or playlist every hour (public feed,
no key) or by hand with a YouTube or Spotify link; own publish, hide.
Simple events: own publish, cancel, remove. Tests and e2e with axe on
the new screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:05:33 +02:00
joshua 9b8f10e3c8 Merge branch 'feat/website-admin' 2026-11-25 12:30:29 +02:00
joshuaandClaude Opus 5.5 84c5b0c08e feat(website): the admin, with drafts, preview, publish and restore
Admin API and screens: dashboard and setup checklist, template and
style, pages and blocks, ministries, leadership, media library with
the storage limit, publish and history. Pending changes with who and
when, discard one, one Publish, restore any version (each version
keeps the working copy's rows, never sent to visitors). Preview on
the site's own addresses with a bar (widths, back, publish); shared
preview links for 7 days or until revoked. Roles checked, same-origin
changes only. Publish refreshes the public pages at once
(WEBSITE_CONTENT_CACHE_SECONDS). E2E on a production build: the
admin's flows and axe on every screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:30:29 +02:00
joshua 3caa1d1e1a Merge branch 'feat/website-templates' 2026-11-25 10:59:04 +02:00
joshuaandClaude Opus 5.5 5ed7201efa feat(website): the four templates and the public site
Heritage, Bold, Community and Clean drawing all 26 section variants
with their headers, homepage order and style settings; colours made
safe (WCAG AA) by the backend; fonts and corners from the shared brand
style. Publishing into numbered versions, the content API with live
messages and events and the church profile from Accounts, uploads,
every page kind, simple event pages, Coming soon, 404, sitemap, SEO
basics and the church's JSON-LD. The demo church (npm run demo) and
Playwright e2e: every template's pages pass axe and the SEO checks.
website.sh builds packages/seo. Decision 17 (first Owner) recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:59:03 +02:00
joshua 138c73e20c Merge branch 'feat/website-signin' 2026-11-25 09:27:08 +02:00
joshuaandClaude Opus 5.5 58960b5e93 feat(website): crosscode website.sh and signing in through Accounts
crosscode: scripts/products/website.sh (ports 5300/3300, uploads in the
export), crosscode add <church> website (needs Accounts; www.<address>
or the Cross Code address), one install_app for Accounts and the
Website, env template copy, bats tests.

Backend: Hub client (protocol v2, product website), crosscode.link/1
with automatic connect to the church's Accounts, sign-in through
@crosscode/auth-client with the Website's own session and roles, the
first Owner from HUB_ADMIN_EMAIL (verified), 2FA for Owners and Admins,
back-channel logout, Accounts' user.* calls, and the church export.
Frontend: admin sign-in/out and the sign-in problem page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:27:07 +02:00
joshua 79121bc447 Merge branch 'feat/website-skeleton' 2026-11-25 08:41:11 +02:00
joshuaandClaude Opus 5.5 36ceb358b8 feat(website): apps/website skeleton
Backend (Express + Prisma, ES modules, as Accounts): /api/health and
/api/v1/site/status (Coming soon until the first publish), the content
model and its first migration, and the confirmed section variants per
template (WEBSITE-1.0-PLAN §3, decision 16) with the template switch
rules, with tests. Frontend (Next.js 16): Coming soon page, admin
placeholder, robots.txt. env.template.json, PM2 example, CHANGELOG and
WHATS-NEW. Root workspaces and lint updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:41:11 +02:00
joshua a3a158faa8 Merge branch 'docs/website-section-variants' 2026-11-25 08:13:22 +02:00
joshuaandClaude Opus 5.5 ae604268e0 docs: Website 1.0 section variants per template (confirmed)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:13:20 +02:00
joshua ae122a664a Merge branch 'docs/hub-2.21-deployed' 2026-11-25 07:58:30 +02:00
joshuaandClaude Opus 5.5 62d9728b95 docs: Hub 2.21.0 deployed; hope-events archived, FastPanel ^~ /api/ done
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:58:30 +02:00
joshua ee129fbd87 Merge branch 'docs/hub-2.21' 2026-11-25 00:03:51 +02:00
joshuaandClaude Opus 5.5 10be55d261 docs: Hub 2.21.0 released (not deployed); website@1.0.0 next
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 00:03:51 +02:00
joshua ed97956a2f Merge branch 'docs/events-3.7-requires' 2026-11-24 23:52:54 +02:00
joshuaandClaude Opus 5.5 e79e5a11f9 docs: Events 3.7.0 requires Accounts 1.7.0
The WHATS-NEW heading now says "— requires accounts 1.7.0", so the Hub
shows the requirement and updates a church's Accounts before Events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:52:54 +02:00
206 changed files with 17644 additions and 225 deletions
+77
View File
@@ -2,6 +2,83 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## website@1.4.0 - 2026-11-27
Database backups and background jobs for the Church Website, as Accounts and Cross Events have.
Details in `apps/website/CHANGELOG.md`. No migration (pg-boss makes its own `pgboss_website`
schema on first start).
- **Backups:** a gzipped `pg_dump` every night at 02:20 into `backend/backups/`, the same
`website-*.sql.gz` files the crosscode script makes before updates; Admin → Backups.
- **Background jobs** on pg-boss: the backup, the Hub heartbeat, the event feed and YouTube (before:
plain timers); Admin → Background jobs switches each on or off, changes its schedule, runs one now.
- **The heartbeat tells the Hub the truth:** the newest backup (before: always none, so the Hub
warned "No backup reported") and the real job mode and failures.
## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27
Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job
means what it did. Details in each app's CHANGELOG.md. No migrations.
- **contracts 1.19.0:** `agent.WEBSITE_DEMO_PROFILES` (eight, two per template:
`heritage-parish`, `heritage-city`, `bold-youth`, `bold-plant`, `community-family`,
`community-town`, `clean-modern`, `clean-campus`), `DEMO_PRODUCTS`, `DEMO_PROFILES_BY_PRODUCT`,
`SEED_WEBSITE_DEMO_MIN_AGENT` (1.6.0). `seed-demo` args take an optional `product` (`events`,
the default, or `website`); the profile must be one of that product's, and a Website demo takes
no `adminEmail`.
- **agent 1.6.0:** a Website `seed-demo` job runs `crosscode demo <church> website --profile <p>`.
- **website 1.3.0:** the eight demo churches (`backend/src/demo/seeds.ts`,
`npm run demo -- --profile <p>`, `--list`). They replace the content only: the church's profile
from Accounts, the site settings, the site icon and the admins stay, and the copy names the
church. `--template` alone is still the Acacia Hill development church.
- **crosscode script:** `crosscode demo <church> website --profile <p>`: backup, the demo as the
site's user (`--force`), reload, wait for `/api/health`. Refused on a Website release without
the profiles (before 1.3.0).
## accounts@1.8.0 + website@1.1.0 - 2026-11-26
The admins of both, redesigned as Cross Events' admin dashboard and settings. Details in each app's
CHANGELOG.md. No migrations, no backend changes.
- **Accounts 1.8.0:** `/admin` is an overview (cards, "Needs you", a tile per section); People
moved to `/admin/people`; the sidebar shows the part you're in, grouped; People redesigned.
- **Website 1.1.0:** an icon sidebar in groups, a dashboard, steps to the first publish across the
top, and a live preview beside the page editor and Template and style (drafts in a frame, no
preview cookie).
## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
- **Linking right after an install** (all three): a connect involving an install that isn't in the
cached copy of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at most once a
minute) instead of refusing. Before, a new product and its siblings only learned of each other at
their 15-minute heartbeats, so a new Website's admin couldn't sign in for up to 30 minutes.
- **Accounts 1.7.1:** also a heartbeat on every start.
- **Website 1.0.2:** opening `/admin` without a link to Accounts links on the spot; the problem page
says "not linked yet" (`ACCOUNTS_NOT_LINKED`) instead of "can't reach your sign-in". Preview no
longer redirects to the server's own `http://localhost:<web port>` (relative redirects).
- **Events 3.7.1:** a new Website can connect for the event feed straight away.
## website@1.0.1 + crosscode script - 2026-11-26
Details in `apps/website/CHANGELOG.md`.
- **Website 1.0.1:** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`), so visitors ask nothing of YouTube until they press play; the
Calendar events' dates read "Sun · November", not "Sun (month: November)". No migration.
- **crosscode script:** a Website's export leaves out `uploads/.thumbnails` (the kept thumbnails).
## contracts@1.18.0 - 2026-11-25
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
Additive: products on 1.17.0 keep working.
- **`hub.storageRequestSchema` / `storageRequestResponseSchema`**: a Website asks the Hub for more
5 GB steps (`POST /api/installs/storage-request`, signed as the heartbeat), with what it uses,
its limit and who asked. `hub.STORAGE_STEP_BYTES`. New sample `hub-storage-request.json` and
JSON Schemas `hub-storage-request`, `hub-storage-request-response`.
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
+35
View File
@@ -1,5 +1,40 @@
# Changelog — Accounts
## [1.8.0] - 2026-11-26
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
dashboard and settings.
### Changed
- **`/admin` is an overview:** four cards (people with an account, deletion requests waiting,
sites that sign in here, last backup), a "Needs you" list with buttons to act, and a tile with a
line about every section. **People moved to `/admin/people`.**
- **The sidebar shows the part you're in** (your account or admin, with a link to the other), and
admin's sections are grouped: People, Church, Signing in, System. Deletion requests shows how many
are waiting. The phone menu shows both parts. Every page title has its section's icon.
- **People:** a search box, a row per person with initials, admin and status badges, two-step
sign-in and last sign-in; the person's card stays in view while scrolling. Deactivating someone
asks to confirm first.
- **Email and WhatsApp** are two cards, each with its own Save.
- Group labels are a darker grey (WCAG AA contrast).
## [1.7.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after Accounts' last heartbeat links straight away.** Accounts accepted a
connect only from installs in its cached copy of the Hub's list, which it refreshed every 15
minutes. A new Church Website (or Events) was refused ("doesn't know that install yet") and tried
again only at its own next heartbeat, so its admin couldn't sign in for up to 30 minutes after the
install (found on cross-demo2). Now, for an install it doesn't know, Accounts sends the Hub a
heartbeat to get a fresh list and looks again (at most one such heartbeat a minute, so unknown
installs can't make it call the Hub more often). The same applies when an Accounts admin connects.
- **A heartbeat on every start**, not only the first: after a restart the list of the church's
products is fresh at once.
## [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).
+12
View File
@@ -3,6 +3,18 @@
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.8.0
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
needs you (like deletion requests waiting), and a tile for every setting. The menu down the side
is grouped and shows only the part you're in. People has moved to Admin → **People**, with a
search box and a clearer list; deactivating someone now asks you to confirm.
## 1.7.1
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
for your church can be signed in to within moments, instead of after up to half an hour.
## 1.7.0
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.7.0",
"version": "1.8.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
+3 -1
View File
@@ -23,8 +23,10 @@ async function main() {
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
const stopJobs = await startJobs(ctx, url);
// 1.7.1: a heartbeat on every start, not only the first (as the Website), so the list of the
// church's products is fresh after a restart.
connectFromEnv(ctx).then((r) => {
if (r.connected) heartbeat(ctx).catch(() => {});
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
+28 -4
View File
@@ -11,6 +11,7 @@ import {
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { heartbeat } from '../hub/client.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, listedProduct } from './store.js';
@@ -24,6 +25,29 @@ export class LinkError extends Error {
/** Products that sign people in through Accounts. */
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after Accounts' last heartbeat), Accounts asks the Hub for a fresh list with a heartbeat and looks
* again, so a new Website links straight away instead of up to 30 minutes later. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make Accounts call the Hub
* more often than that.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
r = { at: now, run: heartbeat(ctx).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
return listedProduct(ctx, installId);
}
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
@@ -55,8 +79,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -86,9 +110,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(ctx, m.from.installId);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (Accounts asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -2,6 +2,8 @@
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
// church profile, Connect, and admin and setup rules.
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, beforeEach, describe, test } from 'node:test';
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
@@ -156,6 +158,44 @@ describe('Connect from a product', () => {
const client = await h.provider.Client.find(APP_ID);
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
});
test('1.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const own = await startHarness({ now: () => clock });
const appKey = generateEd25519();
const NEW_ID = '5c1d7e2f-8a3b-4c4d-9e5f-6a7b8c9d0e1f';
const listed = { product: 'website', installId: NEW_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) };
// A Hub whose list has the new Website; Accounts' cached list doesn't yet.
const hubCalls: string[] = [];
const hub = http.createServer((req, res) => {
hubCalls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: [listed] }));
});
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', () => r()));
try {
own.ctx.config.hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
await own.ctx.settings.setMany({ hub_install_secret: 'secret', hub_linked_products: '[]' });
const msg = (installId: string) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'website', installId, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: clock.toISOString(), nonce: newLinkNonce() }, appKey.privateKeyPem);
const send = (installId: string) => fetch(`${own.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(installId)) });
assert.equal((await send(NEW_ID)).status, 200, 'linked at once');
assert.deepEqual(hubCalls, ['/api/installs/heartbeat']);
assert.equal(await own.db.productLink.count({ where: { installId: NEW_ID } }), 1);
// An install the Hub doesn't list: refused, and within the minute the Hub isn't asked again.
const UNKNOWN = '7e3f9a4b-0c5d-4e6f-8a7b-9c0d1e2f3a4b';
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 1);
clock = new Date(clock.getTime() + 61_000);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 2);
} finally {
await new Promise((r) => hub.close(r));
await own.close();
}
});
});
describe('admin and setup', () => {
+4
View File
@@ -102,6 +102,10 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await page.getByRole("button", { name: "I've saved them" }).click();
// 1.8.0: /admin is the overview, with a tile for every section; People is one.
await expect(page.getByRole("heading", { name: "Admin", level: 1 })).toBeVisible();
await expect(page.getByText("People with an account")).toBeVisible();
await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "People", exact: true }).click();
await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible();
await expect(page.getByText("thandi@hope.test")).toBeVisible();
// 1.3.0: every admin section has its own address, down the side; Backups is one.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.7.0",
"version": "1.8.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
@@ -6,7 +6,7 @@ import QRCode from "qrcode";
import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { ACCOUNT_NAV, AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -62,7 +62,7 @@ export function Account({ section = "overview" }: { section?: AccountSection })
const first = me.name.split(" ")[0] || me.name;
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
<PageTitle icon={section === "overview" ? undefined : ACCOUNT_NAV.find((n) => n.href === s.path)?.icon} sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview me={me} />}
{section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>}
+180 -34
View File
@@ -2,9 +2,12 @@
import Link from "next/link";
import React, { useCallback, useState } from "react";
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
import {
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
} from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText";
import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
@@ -26,6 +29,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
const [me, setMe] = useState<ShellUser | null>(null);
const [allowed, setAllowed] = useState<boolean | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const [waiting, setWaiting] = useState(0);
useExternalEffect(() => {
let alive = true;
@@ -35,11 +39,15 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa"));
if (who.ok) setMe(who.data);
setAllowed(r.ok);
// The count beside Deletion requests.
if (r.ok) void call<{ items: Deletion[] }>("GET", "/admin/deletions").then((d) => { if (alive && d.ok) setWaiting(d.data.items.filter((x) => x.status === "waiting_approval").length); });
});
return () => { alive = false; };
}, [s.path]);
const flash: Flash = (tone, text) => setMsg({ tone, text });
const icon = ADMIN_NAV.find((n) => n.href === s.path)?.icon;
const badges = { "/admin/deletions": waiting };
if (allowed === null || !me) return <ShellLoading />;
if (!allowed) {
return (
@@ -50,16 +58,20 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
}
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub}>{s.title}</PageTitle>
<AppShell me={me} active={s.path} badges={badges}>
<PageTitle icon={section === "overview" ? undefined : icon} sub={section === "overview" ? `Welcome back, ${me.name.split(" ")[0] || me.name}. ${s.sub}` : s.sub}>{s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview />}
{section === "people" && <People flash={flash} />}
<div className="max-w-3xl">
{section === "deletions" && <Deletions flash={flash} />}
<div className="max-w-3xl space-y-6">
{section === "deletions" && <Deletions flash={flash} onChange={setWaiting} />}
{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", "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 === "signin" && <Settings flash={flash} title="Signing in" icon={<LogIn className="h-4 w-4" />} sub="For everyone with an account at the church." keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <>
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
</>}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />}
@@ -70,11 +82,118 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
);
}
// ─── Overview (1.8.0, as Cross Events' admin dashboard) ─────────────────────
type Linked = { hubConnected: boolean; items: { installId: string; name: string; listed: boolean; signsInHere: boolean }[] };
type OverviewData = { people: number | null; deletions: number | null; linked: Linked | null; licence: { connected: boolean; state: string } | null; backups: BackupList | null };
const TILE: Record<string, string> = Object.fromEntries(Object.values(ADMIN_SECTIONS).map((x) => [x.path, x.tile]));
function Stat({ icon, label, value, detail, href, warn }: { icon: React.ReactNode; label: string; value: React.ReactNode; detail?: React.ReactNode; href: string; warn?: boolean }) {
return (
<Link href={href} className="group rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<div className="flex items-center gap-3">
<span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${warn ? "bg-amber-50 text-amber-700" : "bg-brand/10 text-brand"}`} aria-hidden>{icon}</span>
<span className="min-w-0">
<span className="block text-xs text-gray-500">{label}</span>
<span className="block truncate text-xl font-semibold text-gray-900">{value}</span>
</span>
</div>
{detail && <p className="mt-2 text-xs text-gray-500">{detail}</p>}
</Link>
);
}
function Overview() {
const [d, setD] = useState<OverviewData | null>(null);
useExternalEffect(() => {
let alive = true;
Promise.all([
call<{ total: number }>("GET", "/admin/people?q="), call<{ items: Deletion[] }>("GET", "/admin/deletions"), call<Linked>("GET", "/admin/linked-products"),
call<{ connected: boolean; state: string }>("GET", "/admin/licence"), call<BackupList>("GET", "/admin/backups"),
]).then(([people, dels, linked, licence, backups]) => {
if (!alive) return;
setD({
people: people.ok ? people.data.total : null,
deletions: dels.ok ? dels.data.items.filter((x) => x.status === "waiting_approval").length : null,
linked: linked.ok ? linked.data : null,
licence: licence.ok ? licence.data : null,
backups: backups.ok ? backups.data : null,
});
});
return () => { alive = false; };
}, []);
if (!d) return <p className="text-sm text-gray-500" role="status">Loading…</p>;
const connected = d.linked?.items.filter((l) => l.signsInHere).length ?? 0;
const notConnected = d.linked?.items.filter((l) => !l.signsInHere && l.listed) ?? [];
const lastBackup = d.backups?.items[0]?.createdAt ?? null;
const todo: { text: string; href: string; action: string }[] = [
...(d.deletions ? [{ text: `${d.deletions} ${d.deletions === 1 ? "person has" : "people have"} asked to delete their account.`, href: "/admin/deletions", action: "Review" }] : []),
...(d.licence && !d.licence.connected ? [{ text: "Accounts isn't connected to Cross Code yet, so the church's sites can't find it.", href: "/admin/licence", action: "Connect" }] : []),
...(notConnected.length ? [{ text: `${notConnected.map((l) => l.name).join(", ")} ${notConnected.length === 1 ? "doesn't" : "don't"} sign people in here yet.`, href: "/admin/linked", action: "Connect" }] : []),
...(d.backups?.lastError ? [{ text: "The last backup didn't work.", href: "/admin/backups", action: "See why" }] : []),
];
return (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
<Stat icon={<Users className="h-5 w-5" />} label="People with an account" value={d.people ?? "—"} href="/admin/people" detail="Find someone" />
<Stat icon={<UserX className="h-5 w-5" />} label="Deletion requests waiting" value={d.deletions ?? "—"} warn={!!d.deletions} href="/admin/deletions" detail={d.deletions ? "They need your answer" : "None waiting"} />
<Stat icon={<Link2 className="h-5 w-5" />} label="Sites that sign in here" value={d.linked ? `${connected} of ${d.linked.items.length}` : "—"} warn={notConnected.length > 0} href="/admin/linked" detail={d.linked && !d.linked.hubConnected ? "Not connected to the Hub" : "Linked products"} />
<Stat icon={<DatabaseBackup className="h-5 w-5" />} label="Last backup" value={lastBackup ? when(lastBackup) : "None yet"} warn={!!d.backups?.lastError} href="/admin/backups" detail={d.backups ? (d.backups.nightly ? "Every night at 02:00" : "Nightly backups are off") : undefined} />
</div>
<Card>
<Heading icon={todo.length ? <AlertTriangle className="h-4 w-4" /> : <CheckCircle2 className="h-4 w-4" />}>{todo.length ? "Needs you" : "Nothing needs you right now"}</Heading>
{todo.length > 0 ? (
<ul className="divide-y">
{todo.map((t) => (
<li key={t.href} className="flex flex-wrap items-center justify-between gap-3 py-3">
<span className="text-sm text-gray-700">{t.text}</span>
<Link href={t.href} className="inline-flex items-center gap-1 rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-dark">{t.action}<ArrowRight className="h-3.5 w-3.5" aria-hidden /></Link>
</li>
))}
</ul>
) : <p className="text-sm text-gray-600">Nothing is waiting for an admin. Anything that is (a deletion request, a site to connect, a backup that failed) shows here.</p>}
</Card>
<Card>
<Heading sub="Every setting, one click away.">All settings</Heading>
<div className="space-y-5">
{ADMIN_GROUPS.filter((g) => g.title).map((g) => (
<div key={g.title}>
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{g.title}</h3>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{g.items.map((n) => {
const Icon = n.icon;
return (
<Link key={n.href} href={n.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand" aria-hidden><Icon className="h-5 w-5" /></span>
<span className="min-w-0">
<span className="block text-sm font-semibold text-gray-900">{n.label}</span>
<span className="mt-0.5 block text-xs text-gray-500">{TILE[n.href]}</span>
</span>
</Link>
);
})}
</div>
</div>
))}
</div>
</Card>
</div>
);
}
// ─── People ──────────────────────────────────────────────────────────────────
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((x) => x[0]!.toUpperCase()).join("") || "?";
const chip = "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium";
function People({ flash }: { flash: Flash }) {
const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
@@ -94,28 +213,47 @@ function People({ flash }: { flash: Flash }) {
};
return (
<div className="grid gap-6 md:grid-cols-2">
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<Card>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-3 flex gap-2">
<span className="relative flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" aria-hidden />
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="w-full rounded-lg border py-2 pl-9 pr-3" />
</span>
<Button type="submit" variant="secondary">Search</Button>
</form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
<ul className="divide-y">
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} {list?.total === 1 ? "person" : "people"}</p>
<ul className="-mx-2 divide-y">
{list?.items.map((p) => (
<li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
<span className="block text-sm text-gray-500">{p.email}</span>
<button type="button" onClick={() => show(p.id)} aria-current={open?.id === p.id ? "true" : undefined}
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left hover:bg-gray-50 ${open?.id === p.id ? "bg-brand/5" : ""}`}>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand-dark" aria-hidden>{initials(p.name)}</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-1.5 font-medium text-gray-900">
{p.name}
{p.role === "admin" && <span className={`${chip} bg-brand/10 text-brand-dark`}>admin</span>}
{p.status !== "active" && <span className={`${chip} bg-amber-50 text-amber-800`}>{p.status}</span>}
</span>
<span className="block truncate text-sm text-gray-500">{p.email}</span>
</span>
<span className="hidden shrink-0 text-right text-xs text-gray-500 sm:block">{p.twoFactor ? <span className="inline-flex items-center gap-1 text-green-700"><ShieldCheck className="h-3.5 w-3.5" aria-hidden />Two-step</span> : null}<span className="block">{p.lastSignInAt ? `Signed in ${when(p.lastSignInAt)}` : "Never signed in"}</span></span>
<ChevronRight className="h-4 w-4 shrink-0 text-gray-300" aria-hidden />
</button>
</li>
))}
</ul>
</Card>
{open && (
<Card>
<Heading sub={open.email}>{open.name}</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
{open ? (
<Card className="lg:sticky lg:top-20">
<div className="mb-4 flex items-center gap-3">
<span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-brand/10 text-sm font-semibold text-brand-dark" aria-hidden>{initials(open.name)}</span>
<div className="min-w-0">
<h2 className="text-lg font-semibold text-gray-900">{open.name}</h2>
<p className="truncate text-xs text-gray-500">{open.email}</p>
</div>
</div>
<dl className="mb-4 grid grid-cols-2 gap-y-1.5 rounded-lg bg-gray-50 p-3 text-sm">
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
@@ -126,12 +264,18 @@ function People({ flash }: { flash: Flash }) {
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => { if (open.status === "active" && !window.confirm(`Deactivate ${open.name}? They're signed out of every site straight away.`)) return; void act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated."); }}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
</div>
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((x, i) => <li key={i}>{x.type} · {when(x.at)} {x.ip && <span className="text-gray-500">· {x.ip}</span>}</li>)}</ul>
{!open.signIns.length && <p className="text-sm text-gray-500">None yet.</p>}
</Card>
) : (
<div className="hidden rounded-xl border border-dashed p-8 text-center text-sm text-gray-500 lg:block">
<Users className="mx-auto mb-2 h-6 w-6 text-gray-300" aria-hidden />
Choose someone to see their account and what you can do for them.
</div>
)}
</div>
);
@@ -141,16 +285,16 @@ function People({ flash }: { flash: Flash }) {
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
function Deletions({ flash }: { flash: Flash }) {
function Deletions({ flash, onChange }: { flash: Flash; onChange: (waiting: number) => void }) {
const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => {
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
if (r.ok) setItems(r.data.items);
}, []);
if (r.ok) { setItems(r.data.items); onChange(r.data.items.filter((x) => x.status === "waiting_approval").length); }
}, [onChange]);
useExternalEffect(() => { void load(); }, [load]);
return (
<Card>
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
<Heading icon={<UserX className="h-4 w-4" />} sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
<ul className="divide-y">
{items.map((d) => (
@@ -189,7 +333,8 @@ function Church({ flash }: { flash: Flash }) {
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return (
<Card>
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
<Heading icon={<Building2 className="h-4 w-4" />} sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="The church's logo" className="mb-4 h-12 w-auto rounded border bg-gray-50 p-1" />}
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
@@ -230,7 +375,7 @@ function Linked({ flash }: { flash: Flash }) {
if (!data) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
<Heading icon={<Link2 className="h-4 w-4" />} sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
{!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>}
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<ul className="divide-y">
@@ -260,7 +405,7 @@ const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "numb
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
};
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: string[]; title: string; icon: React.ReactNode; sub?: string }) {
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
useExternalEffect(() => {
let alive = true;
@@ -271,6 +416,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
return (
<Card>
<Heading icon={icon} sub={sub}>{title}</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
@@ -281,7 +427,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
else body[k] = String(f.get(k) ?? "");
}
const r = await call("PUT", "/admin/settings", body);
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
if (r.ok) flash("success", `${title}: saved.`); else flash("error", r.error.message);
}}>
{keys.map((k) => {
const [label, kind] = SETTING_LABELS[k]!;
@@ -318,7 +464,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
return (
<div className="space-y-6">
<Card>
<Heading sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
<Heading icon={<FileText className="h-4 w-4" />} sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
{builtIn && !isBuiltIn && (
<p className="mb-4 text-sm text-gray-600">
The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}
@@ -339,7 +485,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
</form>
</Card>
<Card>
<Heading sub="As people will see it.">Preview</Heading>
<Heading icon={<Eye className="h-4 w-4" />} sub="As people will see it.">Preview</Heading>
<h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3>
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
</Card>
@@ -357,7 +503,7 @@ function Licence({ flash }: { flash: Flash }) {
if (!s) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<Heading icon={<KeyRound className="h-4 w-4" />} sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
@@ -388,7 +534,7 @@ function Audit() {
}, []);
return (
<Card>
<Heading>Audit log</Heading>
<Heading icon={<ScrollText className="h-4 w-4" />}>Audit log</Heading>
<ul className="divide-y text-sm">
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
@@ -7,9 +7,9 @@ export async function generateMetadata({ params }: { params: Promise<{ section:
return { title: ADMIN_SECTIONS[section as AdminSection]?.title ?? "Admin" };
}
/** One section of admin (1.3.0): /admin/deletions, /church, /linked, … (/admin itself is People). */
/** One section of admin (1.3.0): /admin/people, /deletions, /church, … (1.8.0: /admin itself is the overview). */
export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) {
const { section } = await params;
if (section === "people" || !(section in ADMIN_SECTIONS)) notFound();
if (section === "overview" || !(section in ADMIN_SECTIONS)) notFound();
return <Admin section={section as AdminSection} />;
}
@@ -3,5 +3,5 @@ import { Admin } from "./Admin";
export const metadata = { title: "Admin" };
export default function AdminPage() {
return <Admin />;
return <Admin section="overview" />;
}
@@ -12,7 +12,7 @@ import { useBranding } from "@/components/BrandingProvider";
/** Who's signed in, as the shell shows them (null: a public page such as the privacy notice). */
export type ShellUser = { name: string; email: string; role: "member" | "admin" };
type NavItem = { href: string; label: string; icon: LucideIcon };
export type NavItem = { href: string; label: string; icon: LucideIcon };
export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account", label: "Overview", icon: LayoutDashboard },
@@ -22,19 +22,21 @@ export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account/activity", label: "Activity", icon: Activity },
];
export const ADMIN_NAV: NavItem[] = [
{ href: "/admin", label: "People", icon: Users },
{ href: "/admin/deletions", label: "Deletion requests", icon: UserX },
{ href: "/admin/church", label: "Church profile", icon: Building2 },
{ href: "/admin/linked", label: "Linked products", icon: Link2 },
{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn },
{ 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.0: the admin's sections in groups, as Cross Events' settings, with the overview first. */
export const ADMIN_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ title: null, items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
{ title: "People", items: [{ href: "/admin/people", label: "People", icon: Users }, { href: "/admin/deletions", label: "Deletion requests", icon: UserX }] },
{ title: "Church", items: [{ href: "/admin/church", label: "Church profile", icon: Building2 }, { href: "/admin/linked", label: "Linked products", icon: Link2 }] },
{
title: "Signing in",
items: [{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn }, { href: "/admin/messages", label: "Email and WhatsApp", icon: Mail }, { href: "/admin/notice", label: "Privacy notice", icon: FileText }],
},
{
title: "System",
items: [{ 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 }],
},
];
export const ADMIN_NAV: NavItem[] = ADMIN_GROUPS.flatMap((g) => g.items);
/** Signs out of Accounts and every site of the church (RP-initiated logout), ending on /signed-out. */
export function signOutHref() {
@@ -53,28 +55,59 @@ function RoleBadge({ role }: { role: ShellUser["role"] }) {
: <span className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600">Member</span>;
}
function NavList({ title, items, active, onNavigate }: { title: string; items: NavItem[]; active: string; onNavigate?: () => void }) {
/** Counts beside a section (deletion requests waiting, say), by its address. */
export type Badges = Record<string, number>;
function NavLinks({ items, active, badges, onNavigate }: { items: NavItem[]; active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<ul className="space-y-0.5">
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
const n = badges?.[l.href] ?? 0;
return (
<li key={l.href}>
<Link href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
<span className="flex-1">{l.label}</span>
{n > 0 && <span className="rounded-full bg-amber-100 px-1.5 text-xs font-semibold text-amber-900">{n}<span className="sr-only"> waiting</span></span>}
</Link>
</li>
);
})}
</ul>
);
}
function AccountNav({ active, onNavigate }: { active: string; onNavigate?: () => void }) {
return (
<div className="mb-6">
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-400">{title}</p>
<nav className="space-y-1" aria-label={title}>
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
return (
<Link key={l.href} href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
{l.label}
</Link>
);
})}
</nav>
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Your account</p>
<nav aria-label="Your account"><NavLinks items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /></nav>
</div>
);
}
function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: string; onNavigate?: () => void }) {
function AdminNav({ active, badges, onNavigate }: { active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<nav aria-label="Admin" className="mb-6 space-y-5">
{ADMIN_GROUPS.map((g, i) => (
<div key={g.title ?? i}>
<p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title ?? "Admin"}</p>
<NavLinks items={g.items} active={active} badges={badges} onNavigate={onNavigate} />
</div>
))}
</nav>
);
}
/**
* The sidebar: who's signed in, then the sections of the part you're in (1.8.0: your account or
* admin, not both at once; the bar across the top switches). In the phone menu, both.
*/
function SidebarContent({ me, active, badges, both, onNavigate }: { me: ShellUser; active: string; badges?: Badges; both?: boolean; onNavigate?: () => void }) {
const inAdmin = me.role === "admin" && active.startsWith("/admin");
return (
<>
<div className="mb-6 flex items-center gap-3 px-1">
@@ -84,8 +117,14 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
<RoleBadge role={me.role} />
</div>
</div>
<NavList title="Your account" items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} />
{me.role === "admin" && <NavList title="Admin" items={ADMIN_NAV} active={active} onNavigate={onNavigate} />}
{(both || !inAdmin) && <AccountNav active={active} onNavigate={onNavigate} />}
{me.role === "admin" && (both || inAdmin) && <AdminNav active={active} badges={badges} onNavigate={onNavigate} />}
{!both && me.role === "admin" && (
<Link href={inAdmin ? "/account" : "/admin"} className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-2 text-sm text-gray-600 hover:border-brand/40 hover:text-brand-dark">
{inAdmin ? <User className="h-4 w-4" aria-hidden /> : <ShieldCheck className="h-4 w-4" aria-hidden />}
{inAdmin ? "Go to your account" : "Go to admin"}
</Link>
)}
</>
);
}
@@ -95,7 +134,7 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
* and name across the top, a sidebar of sections, the page on a light grey, and a dark footer.
* Without `me` (a public page) there's no sidebar. `active` is the current section's address.
*/
export function AppShell({ me, active = "", children }: { me: ShellUser | null; active?: string; children: React.ReactNode }) {
export function AppShell({ me, active = "", badges, children }: { me: ShellUser | null; active?: string; badges?: Badges; children: React.ReactNode }) {
const b = useBranding();
const [open, setOpen] = useState(false);
const top = "text-sm border-b-2 pb-0.5 transition-colors";
@@ -131,7 +170,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
<div className="absolute inset-y-0 left-0 flex w-72 max-w-[85vw] flex-col overflow-y-auto bg-white p-4 shadow-xl">
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="mb-2 self-end rounded-md p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
<SidebarContent me={me} active={active} onNavigate={() => setOpen(false)} />
<SidebarContent me={me} active={active} badges={badges} both onNavigate={() => setOpen(false)} />
<a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className="mt-auto flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50">
<LogOut className="h-4 w-4" aria-hidden /> Sign out
</a>
@@ -142,7 +181,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<div className="mx-auto flex w-full max-w-7xl flex-1">
{me && (
<aside className="hidden w-64 shrink-0 border-r bg-white p-4 md:block">
<div className="sticky top-20"><SidebarContent me={me} active={active} /></div>
<div className="sticky top-20"><SidebarContent me={me} active={active} badges={badges} /></div>
</aside>
)}
<main id="main" className="min-w-0 flex-1 p-4 sm:p-6">{children}</main>
@@ -159,12 +198,15 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
);
}
/** A page's title and a line under it, at the top of the main column. */
export function PageTitle({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
/** A page's title and a line under it, at the top of the main column; with the section's icon. */
export function PageTitle({ children, sub, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: LucideIcon }) {
return (
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
<div className="mb-6 flex items-start gap-3">
{Icon && <span className="mt-0.5 hidden h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand sm:flex" aria-hidden><Icon className="h-5 w-5" /></span>}
<div className="min-w-0">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
</div>
</div>
);
}
+17 -12
View File
@@ -1,15 +1,20 @@
/** The admin's sections (1.3.0): one address each, in the sidebar (components/AppShell.tsx). */
/**
* The admin's sections: one address each, in groups down the side (components/AppShell.tsx), and a
* tile each on the overview. 1.8.0: /admin is the overview (as Cross Events' admin dashboard);
* People moved to /admin/people.
*/
export const ADMIN_SECTIONS = {
people: { path: "/admin", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site." },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account." },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites." },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here." },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in." },
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." },
overview: { path: "/admin", title: "Admin", sub: "How Accounts stands, what needs you, and every setting.", tile: "" },
people: { path: "/admin/people", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site.", tile: "Find someone, reset their two-step sign-in, make an admin" },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account.", tile: "Approve or cancel people's requests to delete their account" },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites.", tile: "Name, logo, colours and contact details for every site" },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here.", tile: "The sites and apps that sign people in here" },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in.", tile: "Who can make an account, two-step sign-in, staying signed in" },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices.", tile: "How sign-in codes and password links are sent" },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes.", tile: "What people read before they first sign in" },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server.", tile: "Back up now, download a copy, how many to keep" },
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.", tile: "What runs on a schedule, and when" },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code.", tile: "The connection to Cross Code" },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here.", tile: "Who changed what, and when" },
} as const;
export type AdminSection = keyof typeof ADMIN_SECTIONS;
+6
View File
@@ -13,6 +13,12 @@ Write for the person updating servers: what the agent can now do from the Hub, a
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.6.0
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
eight demo churches on a demo site, as it already could for Cross Events. Needs Website 1.3.0 on
the site. Cross Events' demo data works as before.
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.6.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",
+3 -1
View File
@@ -59,7 +59,9 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
return ["demo", job.args.church, ...(job.args.product === "website" ? ["website"] : []), "--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, ...(job.args.products ?? []), "--out", opts.exportFile];
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.5.0";
export const AGENT_VERSION = "1.6.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+3
View File
@@ -47,6 +47,9 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
// 1.6.0: the Website's demo.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
+16 -3
View File
@@ -5,11 +5,24 @@ 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.7.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after this site's last heartbeat can connect straight away.** A connect
(in either direction) was refused while the other install wasn't in the cached copy of the Hub's
list, refreshed every 15 minutes. So a new Church Website couldn't connect for the event feed
until then. Now, for an install it doesn't know, the site sends the Hub a heartbeat to get a fresh
list and looks again (at most one such heartbeat a minute, so unknown installs can't make it call
the Hub more often). Same change as Accounts 1.7.1 and Website 1.0.2.
## [3.7.0] - 2026-11-24
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). Works with any Accounts: the
brand style needs Accounts 1.7.0 (with an older one the pages keep their fonts and only the footer
changes). No migrations, no new settings.
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
(WHATS-NEW.md says so, and the Hub updates Accounts first) for the brand style. No migrations, no
new settings.
### Added
+6 -1
View File
@@ -12,7 +12,12 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.7.0
## 3.7.1
- **Connecting to your new Church Website works straight away**, so its events page can show your
Cross Events events as soon as it's installed, instead of after up to 15 minutes.
## 3.7.0 — requires accounts 1.7.0
- **Your public pages look like the rest of your church's sites.** With sign-in through your
church's Accounts, the event pages use the fonts and corner style picked under Accounts → Admin →
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.0",
"version": "3.7.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+32 -4
View File
@@ -35,6 +35,34 @@ export class LinkError extends Error {
}
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
let refresh: { at: number; run: Promise<unknown> } | null = null;
/** For tests. */
export function forgetRefresh(): void {
refresh = null;
}
/**
* 3.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat, like a new Church Website), the site asks the Hub for a fresh
* list with a heartbeat and looks again, instead of refusing for up to 15 minutes. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make this site call the
* Hub more often than that.
*/
async function listedOrRefreshed(installId: string, now: Date) {
const found = await listedProduct(installId);
if (found) return found;
if (!refresh || now.getTime() - refresh.at >= REFRESH_EVERY_MS) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS, and hub/client.js needs this module's siblings
const run = Promise.resolve().then(() => require('../hub/client').heartbeat())
.catch((e: Error) => console.warn('[links] Asking the Hub for a fresh list failed:', e?.message || e));
refresh = { at: now.getTime(), run };
}
await refresh.run;
return listedProduct(installId);
}
type Self = { installId: string; url: string; privateKeyPem: string };
@@ -81,8 +109,8 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(installId, now);
if (!sibling) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -123,9 +151,9 @@ export async function acceptConnect(body: unknown, ip: string | null, now = new
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(m.from.installId);
const sibling = await listedOrRefreshed(m.from.installId, now);
if (!sibling || sibling.product !== m.from.product) {
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (this site asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -87,6 +87,7 @@ const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
async function setUpSite({ linked = true } = {}) {
db.reset();
store.forgetKeyPair();
connect.forgetRefresh();
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
@@ -286,6 +287,29 @@ describe('Connect from a linked product', () => {
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
});
test('3.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
await store.saveLinkedProducts([]);
const hubClient = require('../src/hub/client');
let listed = [{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }];
const spy = jest.spyOn(hubClient, 'heartbeat').mockImplementation(async () => { await store.saveLinkedProducts(listed); return { ok: true }; });
try {
await connect.acceptConnect(connectMessage(), null, new Date());
expect(spy).toHaveBeenCalledTimes(1);
expect(db.t.productLink.get(WEBSITE_ID)).toMatchObject({ product: 'website' });
// An install the Hub doesn't list: refused, and the Hub isn't asked again within the minute.
listed = [];
await store.saveLinkedProducts([]);
const t = new Date();
await expect(connect.acceptConnect(connectMessage(), null, t)).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(1);
await expect(connect.acceptConnect(connectMessage(), null, new Date(t.getTime() + 61_000))).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(2);
} finally {
spy.mockRestore();
}
});
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
await connect.acceptConnect(connectMessage(), null);
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.0",
"version": "3.7.1",
"private": true,
"scripts": {
"dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.7.0",
"version": "3.7.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+2
View File
@@ -0,0 +1,2 @@
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
/ecosystem.config.cjs
+281
View File
@@ -0,0 +1,281 @@
# Changelog — Church Website
## [1.4.0] — 2026-11-27
No migration: pg-boss makes its own schema (`pgboss_website`) on first start, as in Accounts. New
dependencies `pg-boss` and `cron-parser`. Needs `pg_dump` on the server (it's there: the
crosscode script uses it for the backups before updates).
### Added
- **Database backups** (`src/backups/backups.ts`, as Accounts 1.3.0): a gzipped `pg_dump` into
`backend/backups/` every night at 02:20 (after Accounts' at 02:00 on the same server) and when an
admin asks; the newest 14 kept (`backup_retain_count`), nightly on by default
(`backup_nightly`), the last failure in `backup_last_error`. Same names as the crosscode
script's backups before updates (`website-YYYYMMDD-HHMMSS.sql.gz`), so the list shows both. A
dump that fails part-way leaves no file. The database only: the uploads aren't in it (as Events).
- **Admin → Backups** (Owners and Admins): back up now, download one (audited, never cached), turn
nightly backups off, how many to keep. `GET /api/v1/admin/backups`, `POST …/backups/run`,
`PUT …/backups/settings`, `GET …/backups/:file/download`.
- **Background jobs on pg-boss** (`src/jobs.ts`, as Accounts 1.4.0): `backup`, `hub-heartbeat`
(every 15 minutes), `event-feed` (every 15 minutes) and `youtube` (hourly). One run per
schedule however many processes run; timers in the process if the queue can't start;
`JOBS_ENABLED=false` turns them all off. Per job: its .env flag (`BACKUP_ENABLED`,
`HUB_HEARTBEAT_ENABLED`, `FEED_JOB_ENABLED`, `YOUTUBE_JOB_ENABLED`) and `JOB_SCHEDULE_<NAME>`.
- **Admin → Background jobs** (Owners and Admins): each job's schedule, next run and last runs;
switch it on or off, change its schedule (kept in `job_overrides`, winning over the .env, live
at once), or run it now. Audited (`job_settings_changed`, `job_run`).
### Changed
- **The heartbeat reports the newest backup** (`lastBackupAt`; before always null, so the Hub
showed "No backup reported" on every Website) **and the real job mode and failed runs in the
last 24 hours** (before always "queue" and 0).
- The heartbeat, the event feed and YouTube were plain timers (`startHeartbeats`,
`startFeedSync`, `startYoutubeSync`, removed); they're jobs now. The first event-feed and
YouTube runs are on their schedule rather than 20 and 30 seconds after a start.
## [1.3.0] — 2026-11-27
No migration, no new environment settings. Needs contracts 1.19.0 (in this checkout).
### Added
- **Eight demo churches**, two per template, for the Hub's demo sites (Hub 2.25.0, agent 1.6.0,
`crosscode demo <church> website --profile <p>`): `heritage-parish`, `heritage-city`,
`bold-youth`, `bold-plant`, `community-family`, `community-town`, `clean-modern`,
`clean-campus` (`src/demo/seeds.ts`, ids from contracts `agent.WEBSITE_DEMO_PROFILES`). Each is
its own kind of church: home page, Plan your visit, About, Give, four ministries, four leaders, a
message series with three messages, and three upcoming events. The second of each template starts
on the template's second recommended variant of every homepage section and its second header, so
the eight show every recommended look.
- **They keep the organisation settings:** a profile replaces the content only. The church's
profile (from Accounts, else `church_profile_local`) stays, the copy names the church
(`{name}`, `{short}`, `{city}`) and the illustrations use its colours. The site settings, the
site icon (`favicon_media_id` and its picture) and the admins stay. Acacia Hill's profile is
saved only on a site with no profile at all, so it still has a name. Slug history and preview
links go with the old content.
- `npm run demo -- --profile <p> [--force]` and `--list`. `--template <t>` alone still loads the
Acacia Hill development church exactly as before (its profile too), so the e2e suite and its
screenshots are unchanged.
## [1.2.0] — 2026-11-27
No migration, no new environment settings. Its first start on an existing site adds the missing
fixed pages (below).
### Fixed
- **A new install had no pages**, so its home page (and the live preview of it) showed only the
header and footer whatever was chosen under Template and style, and Plan your visit, About, Give,
Contact and the rest didn't exist. Only `npm run demo` made pages. Now the backend adds the fixed
pages at startup (`src/site/starter.ts`) with starter text: Home with every homepage section,
Plan your visit, About us, Ministries, Leadership, Events, Messages, Give, Contact, and Terms and
Safeguarding (footer links, not in the menu; WEBSITE-1.0-PLAN §2). All of them while a site has
none of them (pages it made itself move after them; an address already taken is skipped), else
only a missing home page. A removed page isn't brought back. They're drafts, published with the
site; the audit log says "Added the starter pages". Found on cross-demo2.
- **Template and style → Home page layout:** the Latest message's Card layout had no name.
- **Media picker:** the "No image" placeholder had too little contrast (WCAG AA).
### Added
- **Site icon** (Settings): a picture from the media library as the favicon, live at once
(setting `favicon_media_id`; `favicon` in the site content). Without one the site uses the
church's icon from its profile, else a default: the church's initial on its brand colour (a cross
before the church is known). Every page links `/site-icon?v=…`, which redirects to the icon or
serves the default SVG; the version changes with the icon.
## [1.1.0] — 2026-11-26
No migration, no new settings, no backend changes. The admin redesigned as Cross Events' admin
dashboard and settings. Adds `lucide-react` (the version Accounts uses).
### Added
- **Steps to the first publish** across the top of every admin page until the site is live (from
the setup checklist): each step is a link, done ones are ticked, "Next" goes to the first one to
do, and it folds to one line (remembered in the browser). It updates after every save.
- **A live preview beside the page editor** (home and custom pages) and Template and style: the
page at computer or phone width, scaled to fit, reloaded on each save at the same scroll position.
It folds to a tab on the right (remembered); on phones it's a Preview button that opens it full
screen. It shows drafts without the preview cookie: a request from a frame
(`Sec-Fetch-Dest: iframe`) with an admin session reads the drafts, so the live site in another
tab stays live. Links inside it load in full so they stay on drafts. `/preview/start` takes
`?to=` (a site path only) to open the full preview on that page.
### Changed
- **The admin's frame:** a sidebar with icons in groups (Your site, Content, Go live, Team), a
drawer on phones, and a bar across the top with the changes not published, Preview and who's
signed in. Publish shows the number of changes waiting.
- **The dashboard** as Cross Events': a welcome, four cards (site, changes waiting, storage, last
edit), a tile for every part of the admin, and recent edits.
- **The page editor** has tabs, Content and Page details (title, address, menu, search and
sharing); blocks are cards with a summary, icon buttons to move, hide and remove (asks first), and
"Add a block" is a grid of tiles. **Template and style** has tabs: Template, Home page layout,
Style. Every admin page has its icon.
## [1.0.2] — 2026-11-26
No migration, no new settings. Works with Accounts 1.7.0; with Accounts 1.7.1 the first sign-in
after an install links at once.
### Fixed
- **Preview sent admins to the server's own address** (`http://localhost:<web port>`, found on
cross-demo2). `/preview/start`, `/preview/exit` and shared preview links redirected to
`new URL(path, request.url)`, and behind the proxy `request.url` is the address Next.js is reached
on. They now answer with a relative `Location` (`src/lib/localRedirect.ts`), so the browser stays
on the site's address.
- **The admin couldn't be signed in to for up to 30 minutes after an install.** The Website links
itself to the church's Accounts, but only at a heartbeat, and Accounts refused it until Accounts'
own next heartbeat. Now opening `/admin` without a link links on the spot (asking the Hub for a
fresh list first when it has no Accounts in it; tried at most every 15 seconds). A connect
involving an install that isn't in the cached list yet (Accounts, or Events for the event feed)
also asks the Hub for a fresh list (at most once a minute) instead of refusing. Only one connect to
Accounts runs at a time, so a heartbeat and a sign-in can't leave the two sides with different
secrets.
- **The sign-in problem page says when the site isn't linked yet** (`ACCOUNTS_NOT_LINKED`: "This
website isn't linked to your church's sign-in yet"), instead of "can't reach your church's
sign-in", which read like an outage.
## [1.0.1] — 2026-11-26
### Fixed
- **The messages' thumbnails come from the site** (WEBSITE-1.0-PLAN §7): they loaded from YouTube
(`i.ytimg.com`) with the page, so every visitor was in touch with YouTube before pressing play.
The backend now fetches a message's thumbnail once and keeps it (`/api/thumbnails/<id>.jpg`,
kept in `uploads/.thumbnails/`, not counted as storage and left out of the export); only the
site's own messages' videos are fetched, and only a JPEG is kept. The messages page asks for the
first one from the `<head>` (it's the largest thing on screen), and the e2e checks that nothing
is asked of YouTube or Spotify until play is clicked.
- **Calendar events' dates** read "Sun (month: November)": a weekday and month without a day is
printed that way by `Intl`. Now "Sun · November".
- **The variant screenshots no longer flake** (e2e only): a section starting at a fractional
position came out a pixel taller or shorter from run to run. The header's and each section's
height is rounded up before the screenshot; the baselines were taken again with it.
## [1.0.0] — 2026-11-26
### Added
- The app's skeleton (WEBSITE-1.0-PLAN §1): an Express + Prisma backend with `/api/health` and
`/api/v1/site/status` (Coming soon until the first publish), the content model and its first
migration, the section variants per template (§3, decision 16) with the template switch rules, and
a Next.js frontend with the Coming soon page, an admin placeholder and `robots.txt`.
- **Signing in to the admin through the church's Accounts** (§10), as Cross Events 3.x: the Hub
client (protocol v2, product `website`, registers from `HUB_LICENCE_KEY`, heartbeats with
aggregate counts), links (`crosscode.link/1`; the Website connects itself to the church's Accounts
once the Hub lists it), `/api/auth/signin`, `/callback`, `/me`, `/signout` (then Accounts'
sign-out), back-channel logout and Accounts' calls (`user.updated`, `user.export`,
`user.deleted`). The Website keeps its own session (`ccw_session`, only a hash stored) and its own
roles; the **first Owner** is whoever signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`,
verified in Accounts) while the site has none. Owners and Admins sign in with a second step
(`two_factor_required_for_admins`, on by default); asked of Accounts once, then explained.
- **The four templates and the public site** (§3, §5, §6): Heritage, Bold, Community and Clean,
each drawing all 26 section variants its own way, with its headers, homepage order and style
settings (section colour, spacing, buttons, image treatment). The church's colours are made safe
by the backend (`site/palette.ts`: tints, shades and text colours checked against WCAG AA, with a
note for the admin when one is changed); fonts and corners come from its shared brand style, else
the template's suggestion. Pages: home, every page kind (visit, about, ministries, leadership,
events, messages, give, contact, custom) with its blocks, simple event pages, a real 404,
Coming soon from the church profile, `sitemap.xml` and `robots.txt`. Every page has a title,
description, canonical, Open Graph and one `<h1>`; home and contact have the church's JSON-LD.
Messages load YouTube (youtube-nocookie) or Spotify only when clicked; maps are OpenStreetMap.
- **Publishing** (`site/snapshot.ts`): Publish copies the working copy into a numbered version;
visitors see the latest (`GET /api/v1/site/content`, with live messages and events and the church
profile from Accounts, kept 10 minutes). Section data is checked per type (`site/sections.ts`); a
section that doesn't fit is left out, never shown broken. Uploads are served from
`/api/uploads/` (SVGs sandboxed).
- **The demo church** (`npm run demo -- --template <id>`): Acacia Hill Church, fictional, with
illustrated images; refuses to replace a site its admins published unless `--force`.
- **End to end** (`npx playwright test` in apps/website, no database, a production build): every
template's pages pass axe (WCAG 2.2 AA) and the SEO basics, with screenshots at phone and desktop in
`e2e/screens/`; the admin's flows (edit, preview, publish; discard; a shared link, revoked;
restore; a template switch; a Viewer; signing in from a deep admin page) and axe on every admin
screen.
- **The release checks** (§13): **every section variant in every template** (`e2e/variants.spec.ts`:
26 × 4, axe on each, and 312 screenshots at phone, tablet and desktop compared with the last
baselines, kept on the machine that runs them, not in git); **Lighthouse on a phone**
(`e2e/lighthouse.spec.ts`: home, an event and the messages in each template, the median of three
runs with the CPU slowdown calibrated to the machine: SEO 100, accessibility 95+, performance
90+); and **the same suite on real Postgres**
(`E2E_DATABASE_URL=postgresql://…/<name>_e2e`: the database made again, the migrations applied with
`prisma migrate deploy`). The e2e server's clock is frozen, so the demo's dates are the same every
run.
- **The map loads only once it's on screen** (the With map service times): until then, a link to
it. The iframe's own lazy loading fetched OpenStreetMap's 300 KB script with the page on a phone,
and told OpenStreetMap about every visitor. **The messages page's first thumbnail isn't lazy**
(it's the largest thing on screen), and the page connects to its host at once.
- **Contrast on Bold** (found by the variant checks): the service times' notes on Bold's dark panel
(Panel and With map), and the dates of the Calendar events on a dark band, are light now
(`cc-dark` on the panel; `cc-brand-text`, which the dark rules can override, for the dates).
- **The admin** (§4, §10): a dashboard with the setup checklist, pending changes, storage and notes
about the church's colours; Template and style (the template, each homepage section's layout with
the recommended ones first, the homepage order, the style settings); Pages (details, search
engine title and description with a search result preview, the home page's sections, other pages'
blocks: add, move, hide, remove; custom pages); Ministries and Leadership; the media library
(uploads checked by their bytes, alt text, storage; **uploads stop when storage is full**); and
Publish and history. Roles: a Viewer reads, an Editor and above changes and publishes, a Ministry
leader edits only their own ministry. Every change comes from the site itself (same origin).
- **Drafts, preview and publish** (§4): every change is a draft; the pending list says what changed,
who and when, and any one can be **discarded**; one **Publish** for the whole site, with a note;
every version is kept and any can be **restored** into the working copy (each version keeps the
working copy's rows, never sent to visitors). The **preview** shows the working copy on the site's
own addresses, fully clickable, with a bar above the page (phone / tablet / desktop width, Back to
editing, Publish); a **shared preview link** works signed out for 7 days or until revoked, and
can't change anything. Publish refreshes the public pages at once (`WEBSITE_CONTENT_CACHE_SECONDS`,
30 by default, is how long they're kept otherwise).
- **People** (§10): Owners and Admins add someone by email (their account comes from the church's
Accounts through `people.ensure`, with a "choose your password" email when it's new), change
roles and remove access. Only an Owner touches Owners; nobody changes themselves; a lower role or
removal ends that person's sessions at once. A Ministry leader is tied to their ministry.
- **Messages** (§7): from the church's YouTube channel or playlist automatically (YouTube's public
feed, every hour, no API key; each new video goes live by itself), or by hand with a YouTube or
Spotify link; speaker, series, passage and notes; publish, unpublish, hide. A video is never
added twice; one from the feed can only be hidden (deleting it would bring it back).
- **Simple events** (§8): date and time or all day, place, description, photo and an optional
link; publish, cancel, remove. Both publish on their own, not with the site (decision 9).
- **Photos made safe and fast** (§3): every upload is turned upright, **stripped of its metadata**
(a phone photo can carry where it was taken), kept at most 2400 px wide, and saved at 480, 960
and 1600 px in WebP and JPEG; the pages pick the size the screen needs (`<picture>`, `srcset`).
Every file counts towards storage; a photo the library can't read is refused. (sharp 0.35:
prebuilt binaries, no build step on the servers.)
- **The event feed** (§8, roadmap §4), both ways, as Cross Events 2.4: **Publish my events** serves
the Website's published simple events as `crosscode.event/1` (`GET /api/feed/v1/events`,
`?updatedSince=`; unpublished and removed ones in `deleted` for 90 days) and tells linked siblings
with a signed `event.changed`; **Show events from** fetches each linked sibling's feed every 15
minutes and at once on its signed `event.changed`, keeping read-only copies that link back to the
origin (for registering), only of events that really come from that sibling, one bad event
skipped, and the last good copy kept when a fetch fails. Admin → **Linked products**: Connect,
Disconnect, Show events from, Publish my events, Check now. Accounts' signed `church.changed` now
fetches the church profile again at once.
- **Church details** (§2, decision 10): the church's name, colours, fonts and corners, logo,
service times, contact and social links, saved through Accounts' `church.update` as the signed-in
admin; live at once on all the church's sites (not drafts), refused when someone changed them in
between.
- **Settings** (§10): Google Search Console and Bing verification codes (shown on the home page),
the Coming soon line, and the menu's order. **Audit log** for Owners and Admins; **recent edits**
on the dashboard.
- **Search engines** (§11): a share image made from the church's colours and name for pages without
their own; `Event` structured data on the Website's own event pages, `VideoObject` /
`PodcastEpisode` for messages, `BreadcrumbList` on every page but home; a page's old address
sends people on to the new one (permanent redirect) once published.
- **Two editors at once** (§4): a save that someone else's save overtook is refused, saying who, and
nothing is overwritten. **A Ministry leader's events**: an event can belong to a ministry; its
Ministry leader adds and changes it, an Editor publishes it. **Choose your template** with the
church's own content: each template can be previewed on the real site before it's chosen.
- A simple event with an outside link still has its own page here, with a "More information"
button (its address in the event feed).
- **Get more storage** (§10, decision 12; contracts 1.18.0, Hub 2.22.0): an Owner or Admin asks
under Media library (5 GB steps); the request goes to the Hub, which emails Cross Code, and the
new limit arrives with a heartbeat. The heartbeat now reports the licence's storage limit, so the
Hub emails the church at 80% and when it's full.
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
- **The church's export** (`scripts/export-church.ts`): `export.json` in
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
- **`crosscode`:** `scripts/products/website.sh` (the same hooks as Accounts, ports 5300 / 3300,
uploads in the export), `crosscode add <church> website` (needs the church's Accounts; served on
`www.<address>`, or the Cross Code address itself), and the installer shared by Accounts and the
Website (`install_app`).
+28 -1
View File
@@ -1,3 +1,30 @@
# Church Website
Placeholder: the church's public website and its admin. Built in phase 5 of ROADMAP-v3 (see §6 there).
The church's public website and its admin (ROADMAP-v3 §6, phase 5; plan and decisions in
[docs/WEBSITE-1.0-PLAN.md](../../docs/WEBSITE-1.0-PLAN.md)). Served at `www.<church's address>` (or
`<church>.crosscode.co.za`), with the admin at `/admin`, signed in through the church's Accounts.
The church picks one of four templates (Heritage, Bold, Community, Clean) and makes it its own with
section variants and style settings. Changes are drafts until an editor previews the whole site and
presses Publish; until the first publish visitors see Coming soon.
**State:** being built (2026-11-25): signing in through Accounts, the four templates and the public
site, the admin (editing, preview, publish, discard, restore, shared previews, media), and the demo
church, people and roles, messages (with the YouTube feed), simple events and the event feed with
Cross Events. Still to come: the Hub's "Get more storage", Lighthouse and the VM test. Not released;
`website@1.0.0` is tagged when the plan is built.
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
client id at Accounts), links itself to the church's Accounts once the Hub lists it, and signs
admins in through `@crosscode/auth-client`. Roles are the Website's own; the first Owner is whoever
signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`), verified in Accounts. Locally, set
`LINKS_ALLOW_PRIVATE=true` to link to an Accounts on http://localhost.
- `backend/`: Express + Prisma (ES modules), as Accounts. `npm run dev`, `npm test` (Node's test
runner through tsx), `npm run build`. The content model is in `prisma/schema.prisma`; the section
variants per template (plan §3, decision 16) in `src/site/variants.ts`.
- `frontend/`: Next.js 16. The public site (server-rendered from the latest published version) and
the admin.
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `WEBSITE_URL=http://localhost:3300`),
`npx prisma migrate deploy`, then `npm run dev` in both folders (the frontend runs on 3300 and sends
/api to the backend on 5300).
+72
View File
@@ -0,0 +1,72 @@
# What's new in the Church Website
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.4.0
- **Your website is backed up every night.** A copy of your site's content is kept on the server
every night, and before every update. Owners and Admins find them under **Backups**: make one
now, download one, or choose how many to keep. Your photos and files aren't in them.
- **Background jobs:** under **Background jobs**, see what your site does on a schedule (backups,
your events from Cross Events, new videos from YouTube), and switch each one on or off.
## 1.3.0
- Nothing changes on your site. Behind the scenes, Cross Code can now load demo content on the
websites it uses for demonstrations.
## 1.2.0
- **Your home page and the other pages are there from the start:** a new website now comes with
its home page, Plan your visit, About us, Give, Contact and the rest, with some starter text to
change. Before, a new website had no pages, so the home page and its preview were empty apart
from the header and footer.
- **Your own site icon:** under **Settings → Site icon**, choose the little picture that shows in
the browser tab and bookmarks. Until you do, your site shows your church's initial in its colour.
## 1.1.0
- **An easier admin.** A menu with icons down the side, and a dashboard with a tile for every part
of your site.
- **Steps to get your site live:** until your site is published, the top of every admin page shows
what's left to do. Click a step to go there, or **Next** for the next one.
- **See your page as you edit it:** a live preview beside the editor, at computer or phone size.
It updates every time you save, and you can fold it away to the right.
## 1.0.2
- **Preview works:** pressing Preview in the admin shows your site with your changes, instead of
an error page.
- **Signing in right after your website is installed** works straight away, instead of after up to
half an hour. If it isn't connected to your church's sign-in yet, the page now says so.
## 1.0.1
- **Your visitors' privacy:** the pictures on your messages now come from your own website, so
nothing is loaded from YouTube until someone presses play. The Messages page also shows a little
sooner.
- **Event dates in the Calendar layout** read properly ("Sun · November").
## 1.0.0 — requires accounts 1.7.0
- **Your church's own website**, managed by you. Choose one of four templates (Heritage, Bold,
Community or Clean), then make it yours: each homepage section has two or three layouts, and you
pick the fonts, corners, colours and spacing. Your logo, colours and details come from your
church profile, so the website, Cross Events and your sign-in pages look like one church.
- **Nothing goes live until you say so.** Every change is a draft. Preview the whole site at phone,
tablet and desktop size (and share a preview link), then press **Publish** once. Every published
version is kept, and you can go back to any of them. Until your first Publish, visitors see a
"Coming soon" page.
- **Pages for everything a visitor looks for:** Plan your visit, About, Ministries, Leadership,
Events, Messages, Give and Contact, plus your own pages built from blocks.
- **Messages straight from YouTube:** link your channel or playlist and each new video appears by
itself, or add messages by hand with a YouTube or Spotify link.
- **Events:** add simple events here, and show the events from your Cross Events (with a link to
register there).
- **People and roles:** Owners, Admins, Editors, Ministry leaders (only their own ministry) and
Viewers, all signing in with their church account. An audit log shows who changed what.
- **Found by search engines:** titles and descriptions you can edit, share images, your church on
maps and in local search, and your Google and Bing verification codes.
- **Photos made safe and fast:** location details removed from every photo, and the right size
sent to each screen. 5 GB of uploads included; ask for more under Media library.
+7
View File
@@ -0,0 +1,7 @@
node_modules/
dist/
src/generated/
.env
uploads/
exports/
/backups/
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@crosscode/website-backend",
"version": "1.4.0",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status",
"demo": "tsx scripts/demo.ts"
},
"dependencies": {
"@crosscode/auth-client": "*",
"@crosscode/contracts": "*",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"pg-boss": "^11.1.2",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
"@types/supertest": "^7.2.1",
"prisma": "^7.10.1",
"supertest": "^7.3.1",
"tsx": "^4.23.15",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22"
}
}
+10
View File
@@ -0,0 +1,10 @@
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
import 'dotenv/config';
import { defineConfig } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
datasource: { url: process.env.DATABASE_URL ?? '' },
});
@@ -0,0 +1,365 @@
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §6, §8, §10).
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
-- CreateEnum
CREATE TYPE "WebsiteRole" AS ENUM ('owner', 'admin', 'editor', 'ministry_leader', 'viewer');
-- CreateEnum
CREATE TYPE "PageKind" AS ENUM ('home', 'visit', 'about', 'leadership', 'ministries', 'events', 'messages', 'give', 'contact', 'terms', 'safeguarding', 'custom');
-- CreateEnum
CREATE TYPE "MessageSource" AS ENUM ('youtube_feed', 'youtube', 'spotify');
-- CreateTable
CREATE TABLE "SiteDesign" (
"id" INTEGER NOT NULL DEFAULT 1,
"template" TEXT NOT NULL,
"variants" JSONB NOT NULL,
"home" JSONB NOT NULL,
"style" JSONB NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "SiteDesign_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Page" (
"id" TEXT NOT NULL,
"kind" "PageKind" NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"seoTitle" TEXT,
"description" TEXT,
"navLabel" TEXT,
"inNav" BOOLEAN NOT NULL DEFAULT true,
"position" INTEGER NOT NULL DEFAULT 0,
"imageId" TEXT,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Section" (
"id" TEXT NOT NULL,
"pageId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"variant" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"hidden" BOOLEAN NOT NULL DEFAULT false,
"data" JSONB NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Ministry" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"name" TEXT NOT NULL,
"summary" TEXT,
"body" TEXT,
"imageId" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Leader" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"role" TEXT,
"bio" TEXT,
"photoId" TEXT,
"position" INTEGER NOT NULL DEFAULT 0,
"archivedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Leader_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MessageSeries" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"summary" TEXT,
"imageId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MessageSeries_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Message" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"source" "MessageSource" NOT NULL,
"mediaUrl" TEXT NOT NULL,
"externalId" TEXT,
"thumbnailUrl" TEXT,
"speaker" TEXT,
"passage" TEXT,
"notes" TEXT,
"seriesId" TEXT,
"hidden" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SimpleEvent" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3),
"allDay" BOOLEAN NOT NULL DEFAULT false,
"timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg',
"location" TEXT,
"description" TEXT,
"imageId" TEXT,
"link" TEXT,
"ministryId" TEXT,
"cancelled" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
"updatedBy" TEXT,
CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ImportedEvent" (
"id" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"originProduct" TEXT NOT NULL,
"originId" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3) NOT NULL,
"data" JSONB NOT NULL,
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedRemoval" (
"eventId" TEXT NOT NULL,
"removedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FeedRemoval_pkey" PRIMARY KEY ("eventId")
);
-- CreateTable
CREATE TABLE "MediaAsset" (
"id" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"mime" TEXT NOT NULL,
"bytes" INTEGER NOT NULL,
"width" INTEGER,
"height" INTEGER,
"alt" TEXT NOT NULL DEFAULT '',
"sizes" JSONB,
"uploadedBy" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SiteVersion" (
"id" TEXT NOT NULL,
"number" INTEGER NOT NULL,
"snapshot" JSONB NOT NULL,
"note" TEXT,
"publishedBy" TEXT NOT NULL,
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SlugHistory" (
"slug" TEXT NOT NULL,
"pageId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SlugHistory_pkey" PRIMARY KEY ("slug")
);
-- CreateTable
CREATE TABLE "PreviewLink" (
"id" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
"revokedAt" TIMESTAMP(3),
CONSTRAINT "PreviewLink_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "WebsiteUser" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"role" "WebsiteRole" NOT NULL,
"ministryId" TEXT,
"lastSignInAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WebsiteUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Session" (
"id" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"sid" TEXT,
"mfa" BOOLEAN NOT NULL DEFAULT false,
"idToken" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ProductLink" (
"installId" TEXT NOT NULL,
"product" TEXT NOT NULL,
"url" TEXT NOT NULL,
"publicKey" TEXT NOT NULL,
"secret" TEXT NOT NULL,
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"connectedById" TEXT,
"showEvents" BOOLEAN NOT NULL DEFAULT true,
"lastSyncAt" TIMESTAMP(3),
"lastGoodAt" TIMESTAMP(3),
"lastSyncError" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
);
-- CreateTable
CREATE TABLE "LinkNonce" (
"nonce" TEXT NOT NULL,
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
);
-- CreateTable
CREATE TABLE "AuditLog" (
"id" TEXT NOT NULL,
"actorId" TEXT,
"actorRole" TEXT NOT NULL,
"action" TEXT NOT NULL,
"targetType" TEXT NOT NULL,
"targetId" TEXT,
"metadata" JSONB,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AppSetting" (
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
);
-- CreateIndex
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
-- CreateIndex
CREATE INDEX "Page_kind_idx" ON "Page"("kind");
-- CreateIndex
CREATE INDEX "Section_pageId_position_idx" ON "Section"("pageId", "position");
-- CreateIndex
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "MessageSeries_slug_key" ON "MessageSeries"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "Message_slug_key" ON "Message"("slug");
-- CreateIndex
CREATE UNIQUE INDEX "Message_externalId_key" ON "Message"("externalId");
-- CreateIndex
CREATE INDEX "Message_date_idx" ON "Message"("date");
-- CreateIndex
CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug");
-- CreateIndex
CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId");
-- CreateIndex
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
-- CreateIndex
CREATE UNIQUE INDEX "SiteVersion_number_key" ON "SiteVersion"("number");
-- CreateIndex
CREATE UNIQUE INDEX "PreviewLink_tokenHash_key" ON "PreviewLink"("tokenHash");
-- CreateIndex
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
-- CreateIndex
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
-- CreateIndex
CREATE INDEX "Session_sid_idx" ON "Session"("sid");
-- CreateIndex
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
-- AddForeignKey
ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+329
View File
@@ -0,0 +1,329 @@
// Church Website 1.0.0 (docs/WEBSITE-1.0-PLAN.md). One database per church.
//
// The content tables are the **working copy** the admin edits (§4). Publishing writes an immutable
// snapshot of them to SiteVersion; visitors always see the latest SiteVersion, the preview sees the
// working copy. Shared facts (name, logo, colours, service times, contact, the brand style) are the
// church profile's, in Accounts (§2), and are never stored here.
generator client {
provider = "prisma-client"
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
output = "../src/generated/prisma"
moduleFormat = "esm"
importFileExtension = "js"
}
datasource db {
provider = "postgresql"
}
/// Website roles (§10). Held here, per product: an Events role gives nothing in the Website.
enum WebsiteRole {
owner
admin
editor
ministry_leader
viewer
}
enum PageKind {
home
visit
about
leadership
ministries
events
messages
give
contact
terms
safeguarding
custom
}
enum MessageSource {
youtube_feed
youtube
spotify
}
/// The site's design in the working copy (one row, id 1): template, section variants, homepage
/// order and the Website-only style settings (src/site/variants.ts). Fonts and corners are shared.
model SiteDesign {
id Int @id @default(1)
template String
variants Json
home Json
style Json
updatedAt DateTime @updatedAt
updatedBy String?
}
/// A page: the fixed ones (§6) and custom pages built from blocks.
model Page {
id String @id @default(uuid())
kind PageKind
slug String @unique
title String
/// Per-page SEO (ROADMAP-v3 §11); null uses the generated one.
seoTitle String?
description String?
navLabel String?
inNav Boolean @default(true)
position Int @default(0)
imageId String?
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
sections Section[]
@@index([kind])
}
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
/// is one of that type's ids. Content is never tied to a template (§2).
model Section {
id String @id @default(uuid())
pageId String
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
type String
variant String?
position Int @default(0)
hidden Boolean @default(false)
data Json
updatedAt DateTime @updatedAt
updatedBy String?
@@index([pageId, position])
}
model Ministry {
id String @id @default(uuid())
slug String @unique
name String
summary String?
body String?
imageId String?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
leaders WebsiteUser[]
}
model Leader {
id String @id @default(uuid())
name String
role String?
bio String?
photoId String?
position Int @default(0)
archivedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
}
model MessageSeries {
id String @id @default(uuid())
slug String @unique
title String
summary String?
imageId String?
createdAt DateTime @default(now())
messages Message[]
}
/// A message (sermon), from the YouTube feed or added by hand (§7). Published on its own, not with
/// the site's Publish (decision 9). Audio and video are linked, never uploaded.
model Message {
id String @id @default(uuid())
slug String @unique
title String
date DateTime
source MessageSource
mediaUrl String
/// The YouTube video id or Spotify episode id: one message per video, whichever way it came in.
externalId String? @unique
thumbnailUrl String?
speaker String?
passage String?
notes String?
seriesId String?
series MessageSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
hidden Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
@@index([date])
}
/// A simple event made in the Website (§8). Registrations and payments are only Cross Events'.
model SimpleEvent {
id String @id @default(uuid())
slug String @unique
title String
startsAt DateTime
endsAt DateTime?
allDay Boolean @default(false)
timezone String @default("Africa/Johannesburg")
location String?
description String?
imageId String?
link String?
/// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10).
ministryId String?
cancelled Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
updatedBy String?
@@index([startsAt])
}
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4). It goes
/// with its link (a disconnect, or "Show events" switched off).
model ImportedEvent {
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
originProduct String
originId String
startsAt DateTime
endsAt DateTime
data Json
syncedAt DateTime @default(now())
@@unique([originProduct, originId])
@@index([startsAt])
@@index([linkId])
}
/// A simple event that left the feed (unpublished or removed), listed in `deleted` for 90 days so
/// siblings drop their copy (ROADMAP-v3 §4).
model FeedRemoval {
eventId String @id
removedAt DateTime @default(now())
}
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
/// published versions use it.
model MediaAsset {
id String @id @default(uuid())
filename String
mime String
bytes Int
width Int?
height Int?
alt String @default("")
/// The resized files (WebP and JPEG per width) and their sizes, counted with `bytes`.
sizes Json?
uploadedBy String?
createdAt DateTime @default(now())
}
/// A published version: an immutable snapshot of the working copy (§4). Restore copies one back.
model SiteVersion {
id String @id @default(uuid())
number Int @unique
snapshot Json
note String?
publishedBy String
publishedAt DateTime @default(now())
}
/// A page's earlier address (§6: "Slug changes get a 301 to the new slug"). Published versions
/// send it to wherever the page is now.
model SlugHistory {
slug String @id
pageId String
createdAt DateTime @default(now())
}
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
model PreviewLink {
id String @id @default(uuid())
tokenHash String @unique
createdBy String
createdAt DateTime @default(now())
expiresAt DateTime
revokedAt DateTime?
}
/// Someone who can use the admin: keyed by their account's `sub` from Accounts.
model WebsiteUser {
id String @id
email String
name String
role WebsiteRole
/// A Ministry leader edits only their own ministry.
ministryId String?
ministry Ministry? @relation(fields: [ministryId], references: [id], onDelete: SetNull)
lastSignInAt DateTime?
createdAt DateTime @default(now())
}
/// A signed-in admin session (the `ccw_session` cookie holds the token; only its SHA-256 is kept).
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
model Session {
id String @id @default(uuid())
tokenHash String @unique
userId String
sid String?
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`).
mfa Boolean @default(false)
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
idToken String?
createdAt DateTime @default(now())
lastSeenAt DateTime @default(now())
expiresAt DateTime
@@index([userId])
@@index([sid])
}
/// A link to another of the church's products (`crosscode.link/1`, as Events 2.4): Accounts, for
/// signing in, and Events / the App for the event feed. The secret is encrypted.
model ProductLink {
installId String @id
product String
url String
publicKey String
secret String
connectedAt DateTime @default(now())
connectedById String?
/// Show this sibling's events here (the event feed, §8). Accounts has none.
showEvents Boolean @default(true)
lastSyncAt DateTime?
/// The `generatedAt` of the last feed taken: the next fetch asks for what changed since.
lastGoodAt DateTime?
lastSyncError String?
updatedAt DateTime @updatedAt
imported ImportedEvent[]
}
/// Nonces of link messages seen in the last hour (replays are refused).
model LinkNonce {
nonce String @id
seenAt DateTime @default(now())
}
model AuditLog {
id String @id @default(uuid())
actorId String?
actorRole String
action String
targetType String
targetId String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model AppSetting {
key String @id
value String
updatedAt DateTime @updatedAt
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Loads a demo into the site and publishes it.
*
* npm run demo -- --template heritage|bold|community|clean [--force] the Acacia Hill church (development)
* npm run demo -- --profile <profile> [--force] one of the eight demo churches (1.3.0),
* keeping the church's profile and settings
* npm run demo -- --list the profiles
*
* It replaces the site's content, so a site that has been published needs --force. On a server,
* `crosscode demo <church> website --profile …` runs it (backup first), for the Hub's demo sites.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { agent, websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadDemo } from '../src/demo/demoChurch.js';
import { demoSeeds } from '../src/demo/seeds.js';
import { loadConfig } from '../src/lib/config.js';
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
};
const usage = 'Usage: npm run demo -- --template heritage|bold|community|clean | --profile <profile> [--force] | --list';
if (process.argv.includes('--list')) {
for (const s of demoSeeds()) console.log(`${s.id.padEnd(18)} ${s.label}`);
process.exit(0);
}
const profileArg = arg('profile');
const what = profileArg !== undefined ? agent.websiteDemoProfileSchema.safeParse(profileArg) : websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!what.success) {
console.error(profileArg !== undefined ? `Unknown profile "${profileArg}" (npm run demo -- --list).` : usage);
process.exit(2);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const ctx = createCtx(loadConfig(), db);
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
if (published && !process.argv.includes('--force')) {
console.error('This site has been published by its admins: loading the demo would replace their content. Add --force to do it anyway.');
await db.$disconnect();
process.exit(1);
}
const version = await loadDemo(ctx, what.data);
console.log(`Demo ${what.data} loaded and published (version ${version.number}).`);
await db.$disconnect();
@@ -0,0 +1,28 @@
/**
* The Website's part of a church's export (`crosscode export` / uninstall): `export.json` in
* --out-dir (src/export/churchExport.ts). The crosscode script adds the uploads next to it.
*
* npx tsx scripts/export-church.ts --out-dir <dir>
*/
import 'dotenv/config';
import fs from 'node:fs';
import path from 'node:path';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { buildExport } from '../src/export/churchExport.js';
import { loadConfig } from '../src/lib/config.js';
const i = process.argv.indexOf('--out-dir');
const out = i > 0 ? process.argv[i + 1] : null;
if (!out) {
console.error('Usage: export-church.ts --out-dir <dir>');
process.exit(2);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const data = await buildExport(createCtx(loadConfig(), db));
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'export.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
console.log(` export.json: ${data.website!.pages.length} pages, ${data.website!.messages.length} messages, ${data.files.length} files`);
await db.$disconnect();
+52
View File
@@ -0,0 +1,52 @@
/**
* The church's shared details from the Website's admin (WEBSITE-1.0-PLAN §2, decision 10): name,
* colours, brand style (fonts, corners), logo, service times, contact and social links. Accounts
* owns them; the Website saves them through Accounts' `church.update` with the admin as `actor`.
* They aren't drafts: they go live at once on every one of the church's sites, and the screens
* say so. `ifUpdatedAt` refuses a save when someone changed the profile in between.
*/
import { churchEditableSchema, type Church } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { accounts } from '../auth/accounts.js';
import { churchChanged, churchProfile } from '../church/profile.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: string };
const patchSchema = churchEditableSchema.extend({ branding: churchEditableSchema.shape.branding.partial() }).partial();
export async function getChurch(ctx: Ctx) {
churchChanged(ctx);
const church = await churchProfile(ctx);
const linked = !!(await ctx.db.productLink.findFirst({ where: { product: 'accounts' } }));
return { church, linked };
}
export async function saveChurch(ctx: Ctx, body: unknown, by: Who): Promise<Church> {
const b = (body ?? {}) as { church?: unknown; ifUpdatedAt?: unknown };
const parsed = patchSchema.safeParse(b.church);
if (!parsed.success) {
const fields: Record<string, string> = {};
for (const i of parsed.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some details need another look.', fields);
}
if (!Object.keys(parsed.data).length) throw new ApiError(400, 'VALIDATION', 'Nothing to change.');
type Reply = { church: Church };
let reply: Reply;
try {
reply = await (await accounts(ctx)).request<Reply>({
type: 'church.update', actor: by.id, church: parsed.data as never,
...(typeof b.ifUpdatedAt === 'string' ? { ifUpdatedAt: b.ifUpdatedAt } : {}),
});
} catch (e) {
const err = e as { code?: string; message?: string; status?: number };
if (err.code === 'PROFILE_CHANGED') throw new ApiError(409, 'PROFILE_CHANGED', 'Someone changed your church\'s details while you were editing. Your changes weren\'t saved: reload to see theirs, then make yours again.');
if (err.code === 'NOT_ALLOWED') throw new ApiError(403, 'NOT_ALLOWED', 'Accounts doesn\'t know you as someone who signs in to this website yet. Sign out and in again, then try once more.');
if (err instanceof ApiError) throw err;
throw new ApiError(err.status && err.status < 500 ? 400 : 502, err.code ?? 'ACCOUNTS_ERROR', err.message ?? 'Accounts didn\'t take the change.');
}
churchChanged(ctx);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'church_details_changed', targetType: 'church', targetId: null, metadata: { fields: Object.keys(parsed.data) } });
return reply.church;
}
+290
View File
@@ -0,0 +1,290 @@
/**
* Editing the working copy (WEBSITE-1.0-PLAN §4, §10): the site's design (template, section
* variants, homepage order, style), pages and their sections or blocks, ministries and leaders.
* Every change is a draft until Publish; each row records who changed it last (`updatedBy`).
*
* Shared facts (name, logo, colours, service times, contact) aren't here: they're the church
* profile's, saved through Accounts (§2), and go live at once.
*/
import { z } from 'zod';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.js';
import { cleanDesign } from '../site/snapshot.js';
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
type Who = { id: string; role: string };
/** zod issues as `{ field: message }`, for the form. */
function fieldsOf(e: z.ZodError): Record<string, string> {
const out: Record<string, string> = {};
for (const i of e.issues) out[i.path.join('.') || '_'] ??= i.message;
return out;
}
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fieldsOf(r.error));
return r.data;
}
/**
* Two editors at once (§4): a save says when its form was loaded (`ifUpdatedAt`). If someone else
* saved the same thing since, nothing is overwritten and the editor is told who.
*/
export async function notChangedSince(ctx: Ctx, row: { updatedAt: Date; updatedBy: string | null }, body: unknown, by: Who) {
const given = (body as { ifUpdatedAt?: unknown } | null)?.ifUpdatedAt;
if (typeof given !== 'string') return;
const since = new Date(given);
if (!Number.isFinite(since.getTime()) || row.updatedAt.getTime() <= since.getTime() || row.updatedBy === by.id) return;
const other = row.updatedBy ? await ctx.db.websiteUser.findUnique({ where: { id: row.updatedBy } }) : null;
throw new ApiError(409, 'CHANGED_SINCE', `${other?.name ?? 'Someone else'} changed this while you were editing, so your changes weren't saved. Reload to see theirs, then make yours again.`);
}
// ─── Design ───────────────────────────────────────────────────────────────────
export async function getDesign(ctx: Ctx) {
return cleanDesign(await ctx.db.siteDesign.findUnique({ where: { id: 1 } }));
}
const designPatch = z.object({
template: websiteTemplateSchema.optional(),
variants: z.record(z.string(), z.string()).optional(),
home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(),
style: z.object({
sectionColour: z.enum(SECTION_COLOURS).optional(),
spacing: z.enum(SPACINGS).optional(),
buttons: z.enum(BUTTONS).optional(),
images: z.enum(IMAGE_TREATMENTS).optional(),
header: z.string().max(40).optional(),
}).optional(),
});
/**
* Changes the design. A template switch first moves everything still on the old template's
* defaults to the new one's and keeps the church's own choices (§3); the rest of the patch then
* applies. Returns what the switch moved, for the screen.
*/
export async function saveDesign(ctx: Ctx, body: unknown, by: Who) {
const patch = check(designPatch, body);
let design = await getDesign(ctx);
let moved: { what: string; from: string; to: string }[] = [];
if (patch.template && patch.template !== design.template) ({ design, changes: moved } = switchTemplate(design, patch.template));
for (const [section, variant] of Object.entries(patch.variants ?? {})) {
if (!SECTION_TYPES.includes(section as SectionType) || !isVariant(section as SectionType, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
(design.variants as Record<string, string>)[section] = variant;
}
if (patch.home) {
if (new Set(patch.home.map((e) => e.section)).size !== patch.home.length) throw new ApiError(400, 'VALIDATION', 'Each homepage section can be listed once.');
design.home = [...patch.home, ...design.home.filter((e) => !patch.home!.some((p) => p.section === e.section)).map((e) => ({ ...e, hidden: true }))];
}
if (patch.style) {
const { header, ...rest } = patch.style;
if (header && !(TEMPLATE_HEADERS[design.template] as readonly string[]).includes(header)) throw new ApiError(400, 'VALIDATION', `"${header}" isn't a header for ${design.template}.`);
design.style = { ...design.style, ...rest, ...(header ? { header } : {}) };
}
const data = { template: design.template, variants: design.variants as never, home: design.home as never, style: design.style as never, updatedBy: by.id };
await ctx.db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
return { design, moved };
}
// ─── Pages and sections ─────────────────────────────────────────────────────────
const slugSchema = z.string().trim().toLowerCase().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Lower-case letters, numbers and dashes').max(80);
const RESERVED = new Set(['admin', 'api', 'auth', 'preview', 'events', 'home', 'sitemap.xml', 'robots.txt', 'uploads']);
const pagePatch = z.object({
title: z.string().trim().min(1).max(120).optional(),
slug: slugSchema.optional(),
seoTitle: z.string().trim().max(70).nullable().optional(),
description: z.string().trim().max(300).nullable().optional(),
navLabel: z.string().trim().max(40).nullable().optional(),
inNav: z.boolean().optional(),
position: z.int().min(0).max(1000).optional(),
imageId: z.string().uuid().nullable().optional(),
});
export async function listPages(ctx: Ctx) {
const pages = await ctx.db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }] });
return pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, inNav: p.inNav, position: p.position, path: p.kind === 'home' ? '/' : `/${p.slug}` }));
}
export async function getPage(ctx: Ctx, id: string) {
const page = await ctx.db.page.findUnique({ where: { id } });
if (!page || page.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That page doesn\'t exist.');
const sections = await ctx.db.section.findMany({ where: { pageId: id }, orderBy: { position: 'asc' } });
return { ...page, sections };
}
async function slugFree(ctx: Ctx, slug: string, except?: string) {
if (RESERVED.has(slug)) throw new ApiError(400, 'VALIDATION', `"${slug}" is used by the site itself. Choose another address.`, { slug: 'Used by the site itself' });
const other = await ctx.db.page.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (other && !other.archivedAt) throw new ApiError(409, 'SLUG_TAKEN', 'Another page already has that address.', { slug: 'Another page has it' });
if (other) await ctx.db.page.update({ where: { id: other.id }, data: { slug: `${other.slug}-${other.id.slice(0, 6)}` } });
}
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
const page = await getPage(ctx, id);
const patch = check(pagePatch, body);
await notChangedSince(ctx, page, body, by);
if (page.kind === 'home') delete patch.slug;
if (patch.slug && patch.slug !== page.slug) {
await slugFree(ctx, patch.slug, id);
// The old address keeps working: it sends people on to the new one once published.
await ctx.db.slugHistory.upsert({ where: { slug: page.slug }, create: { slug: page.slug, pageId: id }, update: { pageId: id } });
await ctx.db.slugHistory.deleteMany({ where: { slug: patch.slug } });
}
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
return getPage(ctx, id);
}
/** A custom page (§3, "Pages from blocks"), starting with one text block. */
export async function createPage(ctx: Ctx, body: unknown, by: Who) {
const p = check(z.object({ title: z.string().trim().min(1).max(120), slug: slugSchema }), body);
await slugFree(ctx, p.slug);
const last = await ctx.db.page.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
const page = await ctx.db.page.create({ data: { kind: 'custom', slug: p.slug, title: p.title, position: (last?.position ?? 0) + 1, updatedBy: by.id } });
await ctx.db.section.create({ data: { pageId: page.id, type: 'text', position: 0, data: { heading: null, body: '' }, updatedBy: by.id } });
return getPage(ctx, page.id);
}
/** Archive, never delete (§4): restored by Discard or by restoring a version. The home page stays. */
export async function archivePage(ctx: Ctx, id: string, by: Who) {
const page = await getPage(ctx, id);
if (page.kind === 'home') throw new ApiError(400, 'HOME', 'The home page can\'t be removed.');
await ctx.db.page.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
function schemaFor(type: string): z.ZodType {
const s = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
if (!s) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a section or block.`);
return s;
}
/**
* The home page's section of `type` (one each; its layout is the design's, §3), created the first
* time it's saved.
*/
export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
if (page.kind !== 'home' || !SECTION_TYPES.includes(type as SectionType)) throw new ApiError(400, 'VALIDATION', 'That isn\'t a homepage section.');
const data = check(schemaFor(type), (body as { data?: unknown })?.data);
const existing = page.sections.find((s) => s.type === type);
if (existing) await notChangedSince(ctx, existing, body, by);
if (existing) await ctx.db.section.update({ where: { id: existing.id }, data: { data: data as never, updatedBy: by.id } });
else await ctx.db.section.create({ data: { pageId, type, position: SECTION_TYPES.indexOf(type as SectionType), data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
/** The blocks of any other page: add, change, move, remove. */
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
if (page.kind === 'home') throw new ApiError(400, 'VALIDATION', 'The home page has its sections; blocks are for the other pages.');
const { type } = check(z.object({ type: z.string() }), body);
if (!isBlockType(type)) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a block.`);
const data = check(schemaFor(type), type === 'quote' ? { quote: 'Your quote here' } : type === 'cta' ? { heading: 'Your heading here' } : {});
await ctx.db.section.create({ data: { pageId, type, position: page.sections.length, data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, body: unknown, by: Who) {
const page = await getPage(ctx, pageId);
const s = page.sections.find((x) => x.id === sectionId);
if (!s) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
const patch = check(blockPatch, body);
await notChangedSince(ctx, s, body, by);
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function moveBlock(ctx: Ctx, pageId: string, sectionId: string, direction: 'up' | 'down', by: Who) {
const page = await getPage(ctx, pageId);
const list = [...page.sections];
const i = list.findIndex((x) => x.id === sectionId);
const j = direction === 'up' ? i - 1 : i + 1;
if (i < 0 || j < 0 || j >= list.length) return page;
[list[i], list[j]] = [list[j]!, list[i]!];
for (const [n, s] of list.entries()) await ctx.db.section.update({ where: { id: s.id }, data: { position: n, updatedBy: by.id } });
return getPage(ctx, pageId);
}
export async function removeBlock(ctx: Ctx, pageId: string, sectionId: string, by: Who) {
const page = await getPage(ctx, pageId);
if (!page.sections.some((x) => x.id === sectionId)) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
await ctx.db.section.delete({ where: { id: sectionId } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
return getPage(ctx, pageId);
}
// ─── Ministries and leaders ─────────────────────────────────────────────────────
const ministrySchema = z.object({
name: z.string().trim().min(1).max(120),
slug: slugSchema.optional(),
summary: z.string().trim().max(300).nullable().default(null),
body: z.string().trim().max(8000).nullable().default(null),
imageId: z.string().uuid().nullable().default(null),
position: z.int().min(0).max(1000).optional(),
});
const leaderSchema = z.object({
name: z.string().trim().min(1).max(120),
role: z.string().trim().max(120).nullable().default(null),
bio: z.string().trim().max(4000).nullable().default(null),
photoId: z.string().uuid().nullable().default(null),
position: z.int().min(0).max(1000).optional(),
});
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'ministry';
export async function listMinistries(ctx: Ctx) {
return ctx.db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
}
export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const m = check(ministrySchema, body);
const slug = m.slug ?? slugify(m.name);
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.ministry.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
await notChangedSince(ctx, row, body, by);
return ctx.db.ministry.update({ where: { id }, data });
}
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
return ctx.db.ministry.create({ data: { ...data, position: m.position ?? (last?.position ?? -1) + 1 } });
}
export async function archiveMinistry(ctx: Ctx, id: string, by: Who) {
await ctx.db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
export async function listLeaders(ctx: Ctx) {
return ctx.db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
}
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const l = check(leaderSchema, body);
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
if (id) {
const row = await ctx.db.leader.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
await notChangedSince(ctx, row, body, by);
return ctx.db.leader.update({ where: { id }, data });
}
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
return ctx.db.leader.create({ data: { ...data, position: l.position ?? (last?.position ?? -1) + 1 } });
}
export async function archiveLeader(ctx: Ctx, id: string, by: Who) {
await ctx.db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
}
@@ -0,0 +1,185 @@
/**
* Messages and simple events in the admin (WEBSITE-1.0-PLAN §7, §8). They're things that happen
* rather than the site's design, so each has its own Publish (decision 9) and doesn't wait for the
* site's. Registrations and payments are only Cross Events' (roadmap decision 4): a simple event has
* at most a link.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { youtubeId, spotifyEmbed, messageThumbnail } from '../site/content.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
import { notChangedSince } from './content.js';
type Who = { id: string; role: string };
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
const optional = (max: number) => z.string().trim().max(max).nullable().default(null).transform((v) => v || null);
// ─── Messages ──────────────────────────────────────────────────────────────────
const messageSchema = z.object({
title: z.string().trim().min(1).max(500),
date: z.iso.date().or(z.iso.datetime()),
mediaUrl: z.string().trim().max(500).refine((u) => !!youtubeId(u) || !!spotifyEmbed(u), 'A YouTube video or Spotify episode link'),
speaker: optional(300),
passage: optional(300),
notes: optional(8000),
series: optional(300),
hidden: z.boolean().default(false),
});
async function seriesId(ctx: Ctx, title: string | null) {
if (!title) return null;
const found = await ctx.db.messageSeries.findFirst({ where: { title } });
if (found) return found.id;
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'series';
return (await ctx.db.messageSeries.create({ data: { title, slug: `${slug}-${Date.now().toString(36)}` } })).id;
}
export async function listMessages(ctx: Ctx) {
const [rows, source, lastSync, lastError] = await Promise.all([
ctx.db.message.findMany({ orderBy: { date: 'desc' }, take: 200, include: { series: true } }),
getSource(ctx), ctx.settings.get('youtube_last_sync_at'), ctx.settings.get('youtube_last_error'),
]);
return {
youtube: { source, lastSync, lastError },
items: rows.map((m) => ({
id: m.id, title: m.title, date: m.date.toISOString(), mediaUrl: m.mediaUrl, source: m.source, speaker: m.speaker, passage: m.passage, notes: m.notes,
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: messageThumbnail(m),
})),
};
}
export async function saveMessage(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const m = check(messageSchema, body);
const yt = youtubeId(m.mediaUrl);
const externalId = yt ?? /\/episode\/([A-Za-z0-9]+)/.exec(m.mediaUrl)?.[1] ?? null;
if (externalId) {
const dup = await ctx.db.message.findFirst({ where: { externalId, ...(id ? { NOT: { id } } : {}) } });
if (dup) throw new ApiError(409, 'DUPLICATE', `That video is already a message (“${dup.title}”).`, { mediaUrl: 'Already a message' });
}
const data = {
title: m.title, date: new Date(m.date), mediaUrl: m.mediaUrl, externalId, speaker: m.speaker, passage: m.passage, notes: m.notes,
seriesId: await seriesId(ctx, m.series), hidden: m.hidden, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// A video from the feed keeps its address and source; its details can be filled in.
const keep = row.source === 'youtube_feed' ? { mediaUrl: row.mediaUrl, externalId: row.externalId } : {};
return ctx.db.message.update({ where: { id }, data: { ...data, ...keep } });
}
return ctx.db.message.create({
data: { ...data, slug: await uniqueSlug(ctx, m.title, 'message'), source: yt ? 'youtube' : 'spotify', thumbnailUrl: yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null },
});
}
/** A message's own Publish (decision 9): live, or back off the site. */
export async function publishMessage(ctx: Ctx, id: string, live: boolean, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
await ctx.db.message.update({ where: { id }, data: { publishedAt: live ? ctx.now() : null, updatedBy: by.id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: live ? 'message_published' : 'message_unpublished', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function deleteMessage(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// One from the feed would just come back at the next sync: hide it instead.
if (row.source === 'youtube_feed') throw new ApiError(400, 'FROM_FEED', 'That one comes from YouTube and would come back: hide it instead.');
await ctx.db.message.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'message_deleted', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function saveYoutube(ctx: Ctx, body: unknown, by: Who) {
const { youtube } = check(z.object({ youtube: z.string().max(300).nullable() }), body);
const source = await setSource(ctx, youtube);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'youtube_source_set', targetType: 'setting', targetId: 'youtube_source', metadata: { source } });
return { source, sync: source ? await syncYoutube(ctx) : null };
}
// ─── Simple events ─────────────────────────────────────────────────────────────
const eventSchema = z.object({
title: z.string().trim().min(1).max(300),
startsAt: z.iso.datetime({ offset: true }),
endsAt: z.iso.datetime({ offset: true }).nullable().default(null),
allDay: z.boolean().default(false),
location: optional(500),
description: optional(8000),
imageId: z.string().uuid().nullable().default(null),
ministryId: z.string().uuid().nullable().default(null),
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
export async function listEvents(ctx: Ctx) {
const [rows, media] = await Promise.all([ctx.db.simpleEvent.findMany({ orderBy: { startsAt: 'desc' }, take: 300 }), ctx.db.mediaAsset.findMany()]);
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
return rows.map((e) => ({
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId,
cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(),
}));
}
const OWN_ONLY = "You can add and change your own ministry's events only.";
export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const e = check(eventSchema, body);
// A Ministry leader's events are their ministry's (§10); an Editor publishes them.
const leader = by.role === 'ministry_leader' ? await ctx.db.websiteUser.findUnique({ where: { id: by.id } }) : null;
if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
const data = {
title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description,
imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
if (leader && row.ministryId !== leader.ministryId) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
await notChangedSince(ctx, row, body, by);
const saved = await ctx.db.simpleEvent.update({ where: { id }, data });
// A live event changed: the church's other sites fetch it now.
if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {});
return saved;
}
return ctx.db.simpleEvent.create({ data: { ...data, slug: await uniqueSlug(ctx, e.title, 'simpleEvent') } });
}
export async function setEventState(ctx: Ctx, id: string, change: { published?: boolean; cancelled?: boolean }, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.update({ where: { id }, data: {
...(change.published !== undefined ? { publishedAt: change.published ? ctx.now() : null } : {}),
...(change.cancelled !== undefined ? { cancelled: change.cancelled } : {}),
updatedBy: by.id,
} });
// In or out of the feed (ROADMAP-v3 §4: an unpublished event goes in `deleted`), and siblings told.
if (change.published !== undefined) await markRemoved(ctx, id, !change.published);
if (row.publishedAt || change.published) void notifyLinks(ctx, [id]).catch(() => {});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_changed', targetType: 'simple_event', targetId: id, metadata: { title: row.title, ...change } });
}
export async function deleteEvent(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.delete({ where: { id } });
if (row.publishedAt) {
await markRemoved(ctx, id, true);
void notifyLinks(ctx, [id]).catch(() => {});
}
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } });
}
@@ -0,0 +1,93 @@
/**
* Settings → Backups and Settings → Background jobs (1.4.0, as Accounts and Cross Events). Admins
* only: a backup holds the whole site, and a job switched off stops the heartbeat or the backups.
*/
import fs from 'node:fs';
import express from 'express';
import type { Ctx } from '../context.js';
import { requireRole } from '../auth/sessions.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { ApiError, handle, sendError } from '../http.js';
import { audit } from '../lib/audit.js';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
type Who = { id: string; role: string };
export function maintenanceRouter(ctx: Ctx, who: (req: express.Request) => Who) {
const r = express.Router();
const json = express.json({ limit: '16kb' });
// On each route, not r.use: this router is mounted on the admin API's root.
const admin = requireRole(ctx, 'admin');
const jobError = (e: unknown) => {
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
throw e;
};
// ─── Backups ───
r.get('/backups', admin, handle(async () => ({
items: (await listBackups(ctx)).map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })),
nightly: await ctx.settings.bool('backup_nightly', true),
retain: await retainCount(ctx),
lastError: await ctx.settings.get('backup_last_error'),
})));
r.post('/backups/run', admin, handle(async (req) => {
let b;
try {
b = await runBackup(ctx);
} catch (e) {
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
}
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_made', targetType: 'backup', targetId: b.filename });
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
}));
r.put('/backups/settings', admin, json, handle(async (req) => {
const retain = Number(req.body?.retain);
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
const nightly = req.body?.nightly !== false;
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: nightly ? 'true' : 'false' });
const deleted = await rotate(ctx);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly, deleted } });
return { retain, nightly, deleted };
}));
// A download holds the whole site's content and its editors: audited, never cached.
r.get('/backups/:file/download', admin, async (req, res) => {
try {
const file = backupPath(ctx, String(req.params.file));
if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.');
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file) });
res.setHeader('Content-Type', 'application/gzip');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`);
fs.createReadStream(file).pipe(res);
} catch (e) {
sendError(res, e);
}
});
// ─── Background jobs ───
r.get('/jobs', admin, handle(() => jobStatus(ctx)));
r.put('/jobs/:name', admin, json, handle(async (req) => {
const name = String(req.params.name);
const out = await setOverride(ctx, name, { enabled: req.body?.enabled, cron: req.body?.cron }).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: out });
return { name, override: out };
}));
r.post('/jobs/:name/run', admin, handle(async (req) => {
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
const me = who(req);
await audit(ctx, { actorId: me.id, actorRole: me.role, action: 'job_run', targetType: 'job', targetId: name, metadata: { queued: out.queued } });
return out;
}));
return r;
}
+174
View File
@@ -0,0 +1,174 @@
/**
* The media library and storage (WEBSITE-1.0-PLAN §10, ROADMAP-v3 §10): uploads of photos (JPEG,
* PNG, WebP), checked by their bytes, not their name. 5 GB included; the licence's
* `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop**
* (decision 12) until more is bought; what's already uploaded keeps showing.
*
* Every photo is turned upright and **stripped of its metadata** (a phone photo can carry the place
* it was taken), kept at most 2400 px wide, and saved in responsive sizes (WebP and JPEG at 480,
* 960 and 1600 px wide, each smaller than the photo), all counted towards storage (§3).
*/
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import sharp, { type Metadata, type Sharp } from 'sharp';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { INCLUDED_STORAGE_BYTES } from '../hub/client.js';
import { hubPublicKey, verifyToken } from '../hub/licence.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
type Kind = { ext: string; mime: string };
/** What the bytes are, whatever the name says. */
export function sniff(b: Buffer): Kind | null {
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
return null;
}
/** Width and height from the file's header (PNG, JPEG, WebP), or nulls. */
export function dimensions(b: Buffer, kind: Kind): { width: number | null; height: number | null } {
try {
if (kind.ext === 'png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
if (kind.ext === 'webp') {
const chunk = b.toString('ascii', 12, 16);
if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
if (chunk === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
if (chunk === 'VP8L') {
const bits = b.readUInt32LE(21);
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
}
}
if (kind.ext === 'jpg') {
let i = 2;
while (i < b.length) {
if (b[i] !== 0xff) break;
const marker = b[i + 1]!;
const len = b.readUInt16BE(i + 2);
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) };
i += 2 + len;
}
}
} catch {
// A header we can't read: no dimensions, the image still shows.
}
return { width: null, height: null };
}
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
const [sum, token, installId] = await Promise.all([
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
ctx.settings.get('hub_licence'),
ctx.settings.get('hub_install_id'),
]);
const claims = verifyToken(token, hubPublicKey(ctx)) as { installId?: string; limits?: { storageBytes?: number } } | null;
const fromLicence = claims && claims.installId === installId ? claims.limits?.storageBytes : undefined;
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
const usedBytes = sum._sum.bytes ?? 0;
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
}
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
const kind = sniff(body);
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
const s = await storage(ctx);
if (s.usedBytes + body.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
}
const now = ctx.now();
const base = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}`;
const dir = uploadDir(ctx);
await fs.mkdir(path.join(dir, path.dirname(base)), { recursive: true });
const made = await processImage(body, kind, path.join(dir, base));
const bytes = made.files.reduce((t, f) => t + f.bytes, 0);
if (s.usedBytes + bytes > s.limitBytes) {
await Promise.all(made.files.map((f) => fs.rm(path.join(dir, path.dirname(base), f.name), { force: true })));
throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. An Owner or Admin can get more under Media library.');
}
const filename = `${base}.${made.main.ext}`;
const row = await ctx.db.mediaAsset.create({
data: { filename, mime: made.main.mime, bytes, width: made.width, height: made.height, alt: alt.trim().slice(0, 500), sizes: made.sizes as never, uploadedBy: by },
});
return { ...row, url: mediaUrl(row.filename) };
}
export const MAX_WIDTH = 2400;
export const WIDTHS = [480, 960, 1600] as const;
export type Sizes = { w: number; webp: string; jpg: string }[];
/**
* The photo as kept (upright, no metadata, at most MAX_WIDTH wide, in its own format) and its
* responsive sizes, written next to `basePath` (`<base>.<ext>`, `<base>-<w>.webp`, `<base>-<w>.jpg`).
* A photo the library can't read is refused rather than kept as uploaded.
*/
export async function processImage(body: Buffer, kind: Kind, basePath: string) {
let img: Sharp;
let meta: Metadata;
try {
img = sharp(body, { failOn: 'error' }).rotate();
meta = await img.metadata();
} catch {
throw new ApiError(415, 'NOT_AN_IMAGE', 'That photo can\'t be read. Save it again as JPEG, PNG or WebP and try again.');
}
// After rotate(), width and height follow the EXIF orientation.
const swap = (meta.orientation ?? 1) >= 5;
const fullW = (swap ? meta.height : meta.width) ?? dimensions(body, kind).width ?? MAX_WIDTH;
const fullH = (swap ? meta.width : meta.height) ?? dimensions(body, kind).height ?? null;
const width = Math.min(fullW, MAX_WIDTH);
const height = fullH ? Math.round((fullH * width) / fullW) : null;
const name = path.basename(basePath);
const files: { name: string; bytes: number }[] = [];
const write = async (pipeline: Sharp, file: string) => {
const info = await pipeline.toFile(path.join(path.dirname(basePath), file));
files.push({ name: file, bytes: info.size });
};
// sharp writes no metadata unless asked (withMetadata), so EXIF, GPS and XMP are gone.
const main = kind.ext === 'png' ? { ext: 'png', mime: 'image/png' } : kind.ext === 'webp' ? { ext: 'webp', mime: 'image/webp' } : { ext: 'jpg', mime: 'image/jpeg' };
const resized = () => img.clone().resize({ width, withoutEnlargement: true });
await write(main.ext === 'png' ? resized().png({ compressionLevel: 9 }) : main.ext === 'webp' ? resized().webp({ quality: 82 }) : resized().jpeg({ quality: 82, mozjpeg: true }), `${name}.${main.ext}`);
const sizes: Sizes = [];
for (const w of WIDTHS) {
if (w >= width) continue;
await write(img.clone().resize({ width: w }).webp({ quality: 78 }), `${name}-${w}.webp`);
await write(img.clone().resize({ width: w }).flatten({ background: '#ffffff' }).jpeg({ quality: 80, mozjpeg: true }), `${name}-${w}.jpg`);
sizes.push({ w, webp: `${name}-${w}.webp`, jpg: `${name}-${w}.jpg` });
}
return { main, width, height, sizes, files };
}
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
/** The open "Get more storage" request, if any: open until the limit goes up. */
export async function storageRequestStatus(ctx: Ctx, limitBytes: number): Promise<StorageAsk | null> {
const ask = await ctx.settings.json<StorageAsk | null>('storage_request', null);
return ask && limitBytes <= ask.limitAtRequest ? ask : null;
}
/** "Get more storage": asks the Hub (Cross Code adds it to the licence and is paid R20 a month per step). */
export async function requestMoreStorage(ctx: Ctx, steps: number, by: { id: string; role: string }) {
if (!Number.isInteger(steps) || steps < 1 || steps > 10) throw new ApiError(400, 'VALIDATION', 'Ask for 1 to 10 steps of 5 GB.', { steps: '1 to 10' });
const s = await storage(ctx);
const user = await ctx.db.websiteUser.findUnique({ where: { id: by.id } });
const { requestStorage } = await import('../hub/client.js');
let reply;
try {
reply = await requestStorage(ctx, steps, user?.name ?? null, { usedBytes: s.usedBytes, limitBytes: s.limitBytes });
} catch (e) {
const err = e as { message?: string; code?: string; status?: number };
throw new ApiError(err.status && err.status < 500 ? err.status : 502, err.code ?? 'HUB_ERROR', err.message ?? 'The Hub could not take the request. Try again later.');
}
await ctx.settings.set('storage_request', JSON.stringify({ at: reply.requestedAt, steps: reply.steps, limitAtRequest: s.limitBytes } satisfies StorageAsk));
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'storage_requested', targetType: 'storage', targetId: null, metadata: { steps } });
return { ...reply, request: await storageRequestStatus(ctx, s.limitBytes) };
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Who can use the admin, and as what (WEBSITE-1.0-PLAN §10). Roles are the Website's own, keyed by
* the account's `sub` in the church's Accounts: adding someone by email asks Accounts for their
* account (`people.ensure`), which makes one, with a "choose your password" email, if they have none.
*
* Owner everything, including who is Owner
* Admin everything but Owners (can't add, change or remove one, or make one)
* Others can't manage people
*
* Nobody changes or removes themselves, so a site is never left without an Owner by accident.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import type { WebsiteRole } from '../generated/prisma/client.js';
import { accounts } from '../auth/accounts.js';
import { atLeast, ROLES } from '../auth/sessions.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: WebsiteRole };
const roleSchema = z.enum(ROLES as [WebsiteRole, ...WebsiteRole[]]);
const addSchema = z.object({
name: z.string().trim().min(1).max(200),
email: z.email().trim().toLowerCase().max(254),
role: roleSchema,
ministryId: z.string().uuid().nullable().default(null),
});
const changeSchema = z.object({ role: roleSchema, ministryId: z.string().uuid().nullable().default(null) });
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
/** May `by` give (or take) `role`? */
function mayManage(by: Who, role: WebsiteRole) {
if (!atLeast(by.role, 'admin')) throw new ApiError(403, 'FORBIDDEN', 'Only an Owner or Admin can manage who has access.');
if (role === 'owner' && by.role !== 'owner') throw new ApiError(403, 'OWNERS_ONLY', 'Only an Owner can add, change or remove an Owner.');
}
async function ministryFor(ctx: Ctx, role: WebsiteRole, ministryId: string | null) {
if (role !== 'ministry_leader') return null;
if (!ministryId) throw new ApiError(400, 'VALIDATION', 'Choose the ministry they lead.', { ministryId: 'Choose their ministry' });
const m = await ctx.db.ministry.findUnique({ where: { id: ministryId } });
if (!m || m.archivedAt) throw new ApiError(400, 'VALIDATION', 'That ministry doesn\'t exist.', { ministryId: 'Not a ministry' });
return ministryId;
}
export async function listPeople(ctx: Ctx) {
const [users, ministries] = await Promise.all([ctx.db.websiteUser.findMany({ orderBy: { name: 'asc' } }), ctx.db.ministry.findMany()]);
const names = new Map(ministries.map((m) => [m.id, m.name]));
return users.map((u) => ({
id: u.id, name: u.name, email: u.email, role: u.role, ministryId: u.ministryId, ministry: u.ministryId ? names.get(u.ministryId) ?? null : null,
lastSignInAt: u.lastSignInAt?.toISOString() ?? null,
}));
}
export async function addPerson(ctx: Ctx, body: unknown, by: Who) {
const p = check(addSchema, body);
mayManage(by, p.role);
const ministryId = await ministryFor(ctx, p.role, p.ministryId);
const reply = await (await accounts(ctx)).request<{ sub: string; created: boolean; emailSent?: boolean }>({
type: 'people.ensure', actor: by.id, name: p.name, email: p.email, phone: null, returnUrl: `${ctx.config.publicUrl}/admin`,
});
if (await ctx.db.websiteUser.findUnique({ where: { id: reply.sub } })) throw new ApiError(409, 'ALREADY_ADDED', 'They already have access. Change their role instead.');
const user = await ctx.db.websiteUser.create({ data: { id: reply.sub, name: p.name, email: p.email, role: p.role, ministryId } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_added', targetType: 'website_user', targetId: user.id, metadata: { role: p.role, newAccount: reply.created } });
return { id: user.id, newAccount: reply.created, emailSent: reply.emailSent ?? null };
}
async function target(ctx: Ctx, id: string, by: Who) {
if (id === by.id) throw new ApiError(400, 'SELF', 'You can\'t change or remove your own access. Ask another Owner or Admin.');
const user = await ctx.db.websiteUser.findUnique({ where: { id } });
if (!user) throw new ApiError(404, 'NOT_FOUND', 'That person doesn\'t have access.');
mayManage(by, user.role);
return user;
}
export async function changePerson(ctx: Ctx, id: string, body: unknown, by: Who) {
const user = await target(ctx, id, by);
const c = check(changeSchema, body);
mayManage(by, c.role);
const ministryId = await ministryFor(ctx, c.role, c.ministryId);
await ctx.db.websiteUser.update({ where: { id }, data: { role: c.role, ministryId } });
// A lower role takes effect at once: their sessions end, and they sign in again.
if (ROLES.indexOf(c.role) < ROLES.indexOf(user.role)) await ctx.db.session.deleteMany({ where: { userId: id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_role_changed', targetType: 'website_user', targetId: id, metadata: { from: user.role, to: c.role } });
return { ok: true };
}
export async function removePerson(ctx: Ctx, id: string, by: Who) {
const user = await target(ctx, id, by);
await ctx.db.session.deleteMany({ where: { userId: id } });
await ctx.db.websiteUser.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_removed', targetType: 'website_user', targetId: id, metadata: { role: user.role } });
return { ok: true };
}
@@ -0,0 +1,42 @@
/**
* Shared previews (WEBSITE-1.0-PLAN §4): a link for someone without an account (the pastor), that
* shows the working copy as it is when opened, for 7 days or until revoked. It can't edit or
* publish, and its pages are `noindex`. Only the token's hash is stored; the link is shown once.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { hashToken, randomToken } from '../lib/crypto.js';
export const PREVIEW_DAYS = 7;
export async function createPreviewLink(ctx: Ctx, by: { id: string; role: string }) {
const token = randomToken();
const now = ctx.now();
const row = await ctx.db.previewLink.create({ data: { tokenHash: hashToken(token), createdBy: by.id, createdAt: now, expiresAt: new Date(now.getTime() + PREVIEW_DAYS * 864e5) } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_created', targetType: 'preview_link', targetId: row.id });
return { id: row.id, url: `${ctx.config.publicUrl}/preview/${token}`, expiresAt: row.expiresAt.toISOString() };
}
export async function listPreviewLinks(ctx: Ctx) {
const now = ctx.now();
const rows = await ctx.db.previewLink.findMany({ orderBy: { createdAt: 'desc' } });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((r) => ({
id: r.id, createdAt: r.createdAt.toISOString(), expiresAt: r.expiresAt.toISOString(), by: names.get(r.createdBy) ?? null,
active: !r.revokedAt && r.expiresAt > now, revokedAt: r.revokedAt?.toISOString() ?? null,
}));
}
export async function revokePreviewLink(ctx: Ctx, id: string, by: { id: string; role: string }) {
const row = await ctx.db.previewLink.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That preview link doesn\'t exist.');
await ctx.db.previewLink.update({ where: { id }, data: { revokedAt: ctx.now() } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_revoked', targetType: 'preview_link', targetId: id });
}
export async function previewTokenValid(ctx: Ctx, token: string | undefined): Promise<boolean> {
if (!token || token.length > 200) return false;
const row = await ctx.db.previewLink.findUnique({ where: { tokenHash: hashToken(token) } });
return !!row && !row.revokedAt && row.expiresAt > ctx.now();
}
+221
View File
@@ -0,0 +1,221 @@
/**
* The admin API (WEBSITE-1.0-PLAN §4, §10), under /api/v1/admin, signed in through Accounts.
* Roles: a Viewer reads; an Editor (and Admin, Owner) changes anything, publishes and shares
* previews; a Ministry leader changes only their own ministry, and their changes wait for an
* Editor or above to publish (decision 11). Every change comes from the site itself (sameOrigin).
*/
import express, { type Request } from 'express';
import type { Ctx } from '../context.js';
import { atLeast, requireRole } from '../auth/sessions.js';
import { churchProfile } from '../church/profile.js';
import { ApiError, handle, sameOrigin } from '../http.js';
import { buildPalette } from '../site/palette.js';
import { mediaUrl, publish } from '../site/snapshot.js';
import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../site/variants.js';
import { changes, discard, restore } from '../site/workingCopy.js';
import * as content from './content.js';
import * as people from './people.js';
import * as church from './church.js';
import * as settings from './settings.js';
import * as happenings from './happenings.js';
import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
import { maintenanceRouter } from './maintenance.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
const param = (req: Request, name: string) => String(req.params[name] ?? '');
export function adminRouter(ctx: Ctx) {
const r = express.Router();
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
r.use(requireRole(ctx, 'viewer'));
const json = express.json({ limit: '256kb' });
const editor = requireRole(ctx, 'editor');
r.get('/me', handle((req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
/** The dashboard: pending changes, the last publish, storage, and the setup checklist (§10). */
r.get('/overview', handle(async () => {
const [pending, last, s, profile, design, pages, ministries, recent] = await Promise.all([
changes(ctx), ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } }), storage(ctx), churchProfile(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx), settings.auditLog(ctx, { take: 12 }),
]);
const palette = profile ? buildPalette(profile.branding.colours.primary, profile.branding.colours.accent) : null;
return {
pending: pending.length,
/** Recent edits (§10): the audit log without sign-ins. */
recent: recent.filter((e) => !/^(Signed|Was refused)/.test(e.action)).slice(0, 5),
lastPublished: last ? { number: last.number, at: last.publishedAt.toISOString() } : null,
storage: s,
colourNotes: palette?.notes ?? [],
checklist: [
{ key: 'template', label: 'Choose your template', done: !!design, href: '/admin/template' },
{ key: 'profile', label: 'Add your service times and address', done: !!profile && profile.serviceTimes.length > 0 && !!profile.contact.address, href: '/admin/church' },
{ key: 'pages', label: 'Write your home page and Plan your visit', done: pages.some((p) => p.kind === 'visit'), href: '/admin/pages' },
{ key: 'ministries', label: 'Add your ministries', done: ministries.length > 0, href: '/admin/ministries' },
{ key: 'publish', label: 'Preview and publish', done: !!last, href: '/admin/publish' },
],
};
}));
// ─── Design ───
r.get('/design', handle(async () => ({ design: await content.getDesign(ctx), options: { variants: TEMPLATE_VARIANTS, headers: TEMPLATE_HEADERS, home: TEMPLATE_HOME_ORDER } })));
r.put('/design', editor, json, handle((req) => content.saveDesign(ctx, req.body, who(req))));
// ─── Pages ───
r.get('/pages', handle(() => content.listPages(ctx)));
r.post('/pages', editor, json, handle((req) => content.createPage(ctx, req.body, who(req))));
r.get('/pages/:id', handle((req) => content.getPage(ctx, param(req, 'id'))));
r.put('/pages/:id', editor, json, handle((req) => content.savePage(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/pages/:id', editor, handle(async (req) => { await content.archivePage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.put('/pages/:id/home/:type', editor, json, handle((req) => content.saveHomeSection(ctx, param(req, 'id'), param(req, 'type'), req.body, who(req))));
r.post('/pages/:id/blocks', editor, json, handle((req) => content.addBlock(ctx, param(req, 'id'), req.body, who(req))));
r.put('/pages/:id/blocks/:sid', editor, json, handle((req) => content.saveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body, who(req))));
r.post('/pages/:id/blocks/:sid/move', editor, json, handle((req) => content.moveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body?.direction === 'up' ? 'up' : 'down', who(req))));
r.delete('/pages/:id/blocks/:sid', editor, handle((req) => content.removeBlock(ctx, param(req, 'id'), param(req, 'sid'), who(req))));
// ─── Ministries (a Ministry leader: their own only) and leaders ───
r.get('/ministries', handle(() => content.listMinistries(ctx)));
r.post('/ministries', editor, json, handle((req) => content.saveMinistry(ctx, null, req.body, who(req))));
r.put('/ministries/:id', json, handle((req) => {
const s = req.signed!;
if (!atLeast(s.user.role, 'editor') && !(s.user.role === 'ministry_leader' && s.user.ministryId === param(req, 'id'))) {
throw new ApiError(403, 'FORBIDDEN', 'You can change your own ministry only.');
}
return content.saveMinistry(ctx, param(req, 'id'), req.body, who(req));
}));
r.delete('/ministries/:id', editor, handle(async (req) => { await content.archiveMinistry(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.get('/leaders', handle(() => content.listLeaders(ctx)));
r.post('/leaders', editor, json, handle((req) => content.saveLeader(ctx, null, req.body, who(req))));
r.put('/leaders/:id', editor, json, handle((req) => content.saveLeader(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/leaders/:id', editor, handle(async (req) => { await content.archiveLeader(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
const s = await storage(ctx);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
}));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req))));
r.put('/media/:id', editor, json, handle(async (req) => {
const alt = String(req.body?.alt ?? '').trim().slice(0, 500);
const m = await ctx.db.mediaAsset.update({ where: { id: param(req, 'id') }, data: { alt } }).catch(() => null);
if (!m) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
return { id: m.id, alt: m.alt };
}));
// ─── Messages and simple events: each publishes on its own (decision 9) ───
r.get('/messages', handle(() => happenings.listMessages(ctx)));
r.post('/messages', editor, json, handle((req) => happenings.saveMessage(ctx, null, req.body, who(req))));
r.put('/messages/:id', editor, json, handle((req) => happenings.saveMessage(ctx, param(req, 'id'), req.body, who(req))));
r.post('/messages/:id/publish', editor, json, handle(async (req) => { await happenings.publishMessage(ctx, param(req, 'id'), req.body?.live !== false, who(req)); return { ok: true }; }));
r.delete('/messages/:id', editor, handle(async (req) => { await happenings.deleteMessage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.put('/messages-youtube', editor, json, handle((req) => happenings.saveYoutube(ctx, req.body, who(req))));
r.post('/messages-youtube/sync', editor, handle(() => syncYoutube(ctx)));
r.get('/events', handle(() => happenings.listEvents(ctx)));
// An Editor, or a Ministry leader for their own ministry's events (checked in saveEvent).
const eventWriter = requireRole(ctx, 'ministry_leader');
r.post('/events', eventWriter, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req))));
r.put('/events/:id', eventWriter, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req))));
r.post('/events/:id/state', editor, json, handle(async (req) => {
const b = req.body ?? {};
await happenings.setEventState(ctx, param(req, 'id'), { ...(typeof b.published === 'boolean' ? { published: b.published } : {}), ...(typeof b.cancelled === 'boolean' ? { cancelled: b.cancelled } : {}) }, who(req));
return { ok: true };
}));
r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── The church's shared details (through Accounts, live at once), settings, audit log ───
r.get('/church', handle(() => church.getChurch(ctx)));
r.put('/church', editor, json, handle((req) => church.saveChurch(ctx, req.body, who(req))));
r.get('/settings', handle(() => settings.getSettings(ctx)));
r.put('/settings', editor, json, handle((req) => settings.saveSettings(ctx, req.body, who(req))));
r.put('/pages-order', editor, json, handle((req) => settings.orderPages(ctx, req.body, who(req))));
r.get('/audit', requireRole(ctx, 'admin'), handle((req) => settings.auditLog(ctx, { before: typeof req.query.before === 'string' ? req.query.before : undefined })));
// ─── Linked products and the event feed (§8, §9) ───
r.get('/links', handle(async () => {
const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]);
const counts = new Map<string, number>();
for (const l of links) counts.set(l.installId, await ctx.db.importedEvent.count({ where: { linkId: l.installId } }));
const ids = new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)]);
return {
publishMyEvents: publishing,
products: [...ids].map((id) => {
const l = listed.find((x) => x.installId === id);
const link = links.find((x) => x.installId === id);
return {
installId: id, product: link?.product ?? l!.product, url: link?.url ?? l!.url, connected: !!link, listed: !!l,
showEvents: link?.showEvents ?? null, events: counts.get(id) ?? 0,
lastSyncAt: link?.lastSyncAt?.toISOString() ?? null, lastSyncError: link?.lastSyncError ?? null,
};
}),
};
}));
const linkAdmin = requireRole(ctx, 'admin');
r.post('/links/:id/connect', linkAdmin, handle(async (req) => {
const link = await connectTo(ctx, param(req, 'id'), who(req), req);
if (link.product !== 'accounts') await syncLink(ctx, link);
return { ok: true };
}));
r.delete('/links/:id', linkAdmin, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (link?.product === 'accounts') throw new ApiError(400, 'ACCOUNTS', 'The Website signs in through Accounts, so that link stays.');
return disconnectFrom(ctx, param(req, 'id'), who(req), req);
}));
r.put('/links/:id', editor, json, handle(async (req) => {
const id = param(req, 'id');
const link = await ctx.db.productLink.findUnique({ where: { installId: id } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
const updated = await ctx.db.productLink.update({ where: { installId: id }, data: { showEvents: !!req.body?.showEvents } });
return syncLink(ctx, updated);
}));
r.post('/links/:id/sync', editor, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
return syncLink(ctx, link);
}));
r.put('/feed', editor, json, handle(async (req) => {
await ctx.settings.set('feed_publish', req.body?.publish === false ? 'false' : 'true');
return { publishMyEvents: await publishOn(ctx) };
}));
// ─── People: who can use the admin, as what (Owner and Admin) ───
const admin = requireRole(ctx, 'admin');
r.get('/people', admin, handle(() => people.listPeople(ctx)));
r.post('/people', admin, json, handle((req) => people.addPerson(ctx, req.body, who(req))));
r.put('/people/:id', admin, json, handle((req) => people.changePerson(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/people/:id', admin, handle((req) => people.removePerson(ctx, param(req, 'id'), who(req))));
// ─── Publish, discard, restore, versions, shared previews (§4) ───
r.get('/changes', handle(() => changes(ctx)));
r.post('/publish', editor, json, handle(async (req) => {
const pending = await changes(ctx);
const first = !(await ctx.db.siteVersion.findFirst());
if (!pending.length && !first) throw new ApiError(409, 'NOTHING_TO_PUBLISH', 'There are no changes to publish.');
const note = typeof req.body?.note === 'string' && req.body.note.trim() ? req.body.note.trim().slice(0, 500) : null;
const v = await publish(ctx, who(req), note);
return { number: v.number, publishedAt: v.publishedAt.toISOString(), changes: pending.length };
}));
r.post('/discard', editor, json, handle((req) => discard(ctx, String(req.body?.key ?? ''), who(req))));
r.get('/versions', handle(async () => {
const rows = await ctx.db.siteVersion.findMany({ orderBy: { number: 'desc' }, take: 100, select: { number: true, publishedAt: true, publishedBy: true, note: true } });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((v) => ({ number: v.number, publishedAt: v.publishedAt.toISOString(), by: names.get(v.publishedBy) ?? null, note: v.note }));
}));
r.post('/versions/:n/restore', editor, handle((req) => restore(ctx, Number(param(req, 'n')), who(req))));
r.get('/preview-links', editor, handle(() => listPreviewLinks(ctx)));
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── Backups and background jobs (1.4.0, admins only) ───
r.use(maintenanceRouter(ctx, who));
return r;
}
+100
View File
@@ -0,0 +1,100 @@
/**
* The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's
* design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11:
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page, and the
* site's icon (1.2.0: the favicon, a picture from the media library; without one the site uses the
* church's icon from its profile, else one made from its colour and initial). Also the
* menu's order, and the audit log.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
/** What the search engines give: the content of their meta tag, or the whole tag pasted in. */
const code = z.string().trim().max(300)
.transform((v) => (/content="([^"]+)"/.exec(v)?.[1] ?? v).trim())
.refine((v) => v === '' || /^[\w-]{6,100}$/.test(v), 'The code from the search engine (letters, numbers, - and _)');
const schema = z.object({
comingSoonText: z.string().trim().max(300).optional(),
googleVerification: code.optional(),
bingVerification: code.optional(),
faviconId: z.string().uuid().nullable().optional(),
});
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null; faviconId: string | null };
export async function getSettings(ctx: Ctx): Promise<SiteSettings> {
const [coming, google, bing, favicon] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null, faviconId: favicon || null };
}
export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields);
}
const s = r.data;
if (s.faviconId && !(await ctx.db.mediaAsset.findUnique({ where: { id: s.faviconId } }))) {
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', { faviconId: 'That picture isn\'t in the media library' });
}
await ctx.settings.setMany({
...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}),
...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}),
...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}),
...(s.faviconId !== undefined ? { favicon_media_id: s.faviconId || null } : {}),
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } });
return getSettings(ctx);
}
/** The menu's order: pages in the order given (§10, "Navigation"). A draft, like any page change. */
export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) {
const ids = z.array(z.string().uuid()).max(200).safeParse((body as { ids?: unknown } | null)?.ids);
if (!ids.success) throw new ApiError(400, 'VALIDATION', 'Give the pages in order.');
const pages = await ctx.db.page.findMany({ where: { archivedAt: null } });
const known = new Set(pages.map((p) => p.id));
if (ids.data.some((id) => !known.has(id))) throw new ApiError(400, 'VALIDATION', "That isn't one of the site's pages.");
for (const [n, id] of ids.data.entries()) {
const p = pages.find((x) => x.id === id)!;
if (p.position !== n + 1) await ctx.db.page.update({ where: { id }, data: { position: n + 1, updatedBy: by.id } });
}
return { ok: true };
}
const ACTIONS: Record<string, string> = {
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version', starter_pages_added: 'Added the starter pages',
preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link',
first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out',
admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access',
website_user_role_changed: "Changed someone's role", website_user_removed: "Removed someone's access",
website_user_deleted: 'An account was deleted in Accounts', message_published: 'Published a message',
message_unpublished: 'Took a message off the site', message_deleted: 'Removed a message',
youtube_source_set: 'Set the YouTube channel or playlist', event_changed: 'Changed an event', event_deleted: 'Removed an event',
church_details_changed: "Changed the church's details", settings_changed: 'Changed the settings',
product_link_connected: 'Connected a product', product_link_disconnected: 'Disconnected a product', storage_requested: 'Asked for more storage',
};
const ROLE_ACTORS: Record<string, string> = { system: 'The site itself', linked_product: 'A linked product', accounts: 'Accounts' };
/** The audit log (§4: "an audit log of who changed what"), newest first. */
export async function auditLog(ctx: Ctx, opts: { before?: string; take?: number } = {}) {
const take = Math.min(200, Math.max(1, opts.take ?? 100));
const before = opts.before ? new Date(opts.before) : null;
const where = before && Number.isFinite(before.getTime()) ? { createdAt: { lt: before } } : {};
const rows = await ctx.db.auditLog.findMany({ where, orderBy: { createdAt: 'desc' }, take });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((r) => {
const meta = (r.metadata ?? {}) as Record<string, unknown>;
const detail = [meta.title, meta.label, meta.note].find((x) => typeof x === 'string') as string | undefined;
return {
at: r.createdAt.toISOString(),
who: (r.actorId && names.get(r.actorId)) || ROLE_ACTORS[r.actorRole] || 'Someone',
action: ACTIONS[r.action] ?? r.action.replace(/_/g, ' '),
detail: detail ?? null,
};
});
}
+116
View File
@@ -0,0 +1,116 @@
/**
* The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API
* share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js.
*
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
* /api/v1/site/… the public site (what visitors see: the latest published version)
* /api/uploads/… the church's uploaded images
* /api/thumbnails/<id>.jpg its messages' YouTube thumbnails, kept here (visitors never ask YouTube)
* /api/auth/… signing in to the admin through the church's Accounts
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
* /api/links/v1/… Connect and Disconnect with the church's other products
* /api/v1/admin/… the admin (signed in, by role)
*
* To come (§1): the admin's content, publish and preview links, uploading, the event feed.
*/
import path from 'node:path';
import express from 'express';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from './context.js';
import { authRouter } from './auth/routes.js';
import { adminRouter } from './admin/routes.js';
import { previewTokenValid } from './admin/previewLinks.js';
import { atLeast, currentSession } from './auth/sessions.js';
import { dbUp } from './hub/client.js';
import { ApiError, handle, sendError } from './http.js';
import { appVersion } from './lib/version.js';
import { linksRouter } from './links/routes.js';
import { defaultUploadDir } from './demo/demoChurch.js';
import { previewContent, siteContent } from './site/content.js';
import { siteStatus } from './site/status.js';
import { thumbnail } from './site/thumbnails.js';
export function createApp(ctx: Ctx) {
const app = express();
app.disable('x-powered-by');
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
res.setHeader('X-Robots-Tag', 'noindex');
next();
});
app.get('/api/health', async (_req, res) => {
const db = await dbUp(ctx);
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db });
});
const site = express.Router();
site.get('/status', handle(() => siteStatus(ctx)));
// The preview (§4): the working copy, for a signed-in admin or a shared preview link. Never cached.
site.get('/preview', handle(async (req, res) => {
const signed = await currentSession(ctx, req);
if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.');
res.set('Cache-Control', 'no-store');
res.set('X-Robots-Tag', 'noindex, nofollow');
// An admin trying a template on (Template and style): the content in it, nothing saved.
const t = websiteTemplateSchema.safeParse(req.get('x-preview-template'));
const asTemplate = signed && t.success ? t.data : undefined;
return { ...(await previewContent(ctx, { asTemplate })), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') && !asTemplate, template: asTemplate ?? null } };
}));
site.get('/content', handle(async (_req, res) => {
// Short: Publish shows within a minute even where a proxy caches.
res.set('Cache-Control', 'public, max-age=30');
return siteContent(ctx);
}));
app.use('/api/v1/site', site);
// Uploaded files: never a directory listing, never outside the folder (express.static checks).
app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), {
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d',
setHeaders: (res) => {
// An uploaded SVG is shown as an image, never run as a page.
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
},
}));
// A message's YouTube thumbnail, fetched once by the backend and kept (site/thumbnails.ts).
app.get('/api/thumbnails/:file', async (req, res, next) => {
try {
const id = /^([A-Za-z0-9_-]+)\.jpg$/.exec(req.params.file)?.[1];
const body = id ? await thumbnail(ctx, id) : null;
if (!body) {
res.set('Cache-Control', 'no-store');
return sendError(res, new ApiError(404, 'NOT_FOUND', 'There is no such file.'));
}
res.set('Content-Type', 'image/jpeg');
res.set('Cache-Control', 'public, max-age=604800');
res.send(body);
} catch (err) {
next(err);
}
});
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
app.use('/api/v1/admin', adminRouter(ctx));
app.use('/api', (_req, res) => {
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
});
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
if (res.headersSent) return next(err);
if (err instanceof ApiError) return sendError(res, err);
const e = err as { type?: string; status?: number };
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
// A missing upload (express.static), or another known client error.
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
return sendError(res, err);
});
return app;
}
+62
View File
@@ -0,0 +1,62 @@
/**
* The church's Accounts, as this site's OIDC client (WEBSITE-1.0-PLAN §1, §10), built on
* `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the
* Hub listed; the client id is this site's Hub install id and the client secret comes from the
* link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x).
*/
import type * as AuthClient from '@crosscode/auth-client';
import type { AccountsClient } from '@crosscode/auth-client';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { linkAccountsNow } from '../links/connect.js';
export type AuthClientModule = typeof AuthClient;
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
export class AccountsUnavailable extends ApiError {
/** 1.0.2: `not_linked` (no link to Accounts yet) or `unreachable` (linked, but it didn't answer). */
constructor(message: string, public reason: 'not_linked' | 'unreachable' = 'unreachable') {
super(503, 'ACCOUNTS_UNAVAILABLE', message);
}
}
/** The Accounts link, or null while the Website isn't linked to Accounts. */
export async function accountsLink(ctx: Ctx) {
return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
}
const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>();
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
let link = await accountsLink(ctx);
if (!link) {
// 1.0.2: link now rather than wait for the next heartbeat.
await linkAccountsNow(ctx);
link = await accountsLink(ctx);
}
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet.', 'not_linked');
const clientId = await ctx.settings.get('hub_install_id');
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.', 'not_linked');
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
let hit = cache.get(ctx);
if (!hit || hit.key !== key) {
const client = ctx.authClient().then((m) => m.accountsClient({
accountsUrl: link.url,
productUrl: ctx.config.publicUrl,
clientId,
linkSecret: ctx.secrets.decrypt(link.secret),
allowInsecure: !ctx.config.production && link.url.startsWith('http:'),
}));
// A failed discovery (Accounts down for a moment) is tried again next time.
client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); });
hit = { key, client };
cache.set(ctx, hit);
}
try {
return await hit.client;
} catch (e) {
throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
}
}
+206
View File
@@ -0,0 +1,206 @@
/**
* Signing in to the Website's admin through the church's Accounts (WEBSITE-1.0-PLAN §10, as Cross
* Events 3.x), under /api:
*
* GET /auth/signin?returnTo=…[&mfa=1] PKCE + state in a short-lived cookie, then off to Accounts
* GET /auth/callback back from Accounts: the Website's own session, then returnTo
* GET /auth/me who's signed in (the admin pages ask)
* POST /auth/signout ends this session, then Accounts' sign-out (all the church's sites)
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
*
* Who may use the admin is the Website's own business (roles are never in the claims). The first
* Owner is whoever signs in with the church's admin email from the Hub (HUB_ADMIN_EMAIL), verified
* in Accounts, while the site has no Owner; everyone else is added by an Owner or Admin.
*/
import express, { type Request, type Response } from 'express';
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import type { WebsiteRole } from '../generated/prisma/client.js';
import { handle, sendError } from '../http.js';
import { audit, clientIp } from '../lib/audit.js';
import { accounts, AccountsUnavailable } from './accounts.js';
import { cookieOptions, currentSession, needsTwoFactor, readCookies, SESSION_COOKIE, startSession } from './sessions.js';
const PENDING_COOKIE = 'ccw_signin';
const MFA_COOKIE = 'ccw_signin_mfa';
const COOKIE_PATH = '/api/auth';
const PENDING_MINUTES = 10;
/** A page of this site, absolute (in development the API and the pages are on different ports). */
const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
/** The problem page: a short reason and "Try again" with the same return path. */
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/admin') =>
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** 1.0.2: the problem page says which it is: not linked to Accounts yet, or Accounts not answering. */
const unavailableCode = (e: AccountsUnavailable) => (e.reason === 'not_linked' ? 'ACCOUNTS_NOT_LINKED' : 'ACCOUNTS_UNAVAILABLE');
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
/**
* The Website user for a sign-in: by `sub`; else the first Owner, when the site has none and this is
* the Hub's admin email (verified); else nobody (no access to this admin).
*/
export async function userForClaims(ctx: Ctx, claims: IdentityClaims): Promise<{ user: UserRow | null; created?: boolean }> {
const known = await ctx.db.websiteUser.findUnique({ where: { id: claims.sub } });
if (known) {
const user = await ctx.db.websiteUser.update({ where: { id: known.id }, data: { name: claims.name, email: claims.email.toLowerCase(), lastSignInAt: ctx.now() } });
return { user };
}
const adminEmail = ctx.config.hubAdminEmail;
if (!adminEmail || !claims.email_verified || claims.email.toLowerCase() !== adminEmail) return { user: null };
if (await ctx.db.websiteUser.findFirst({ where: { role: 'owner' } })) return { user: null };
const user = await ctx.db.websiteUser.create({
data: { id: claims.sub, name: claims.name, email: claims.email.toLowerCase(), role: 'owner', lastSignInAt: ctx.now() },
});
return { user, created: true };
}
export function authRouter(ctx: Ctx) {
const r = express.Router();
r.get('/auth/signin', async (req, res) => {
const returnTo = safeReturnPath(req.query.returnTo);
try {
const auth = await accounts(ctx);
const requireTwoFactor = req.query.mfa === '1';
const { url, cookie } = await auth.startSignIn(returnTo, { requireTwoFactor });
const opts = { ...cookieOptions(ctx, COOKIE_PATH), maxAge: PENDING_MINUTES * 60e3 };
res.cookie(PENDING_COOKIE, cookie, opts);
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', opts);
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
return res.redirect(303, url);
} catch (e) {
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e), returnTo);
console.error('[auth] Starting a sign-in failed:', e);
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
}
});
r.get(OIDC_CLIENT_PATHS.callback.replace(/^\/api/, ''), async (req, res) => {
const cookies = readCookies(req);
const askedForTwoFactor = cookies[MFA_COOKIE] === '1';
res.clearCookie(PENDING_COOKIE, cookieOptions(ctx, COOKIE_PATH));
res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
let result: Awaited<ReturnType<Awaited<ReturnType<typeof accounts>>['finishSignIn']>>;
try {
const auth = await accounts(ctx);
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
} catch (e) {
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e));
const code = (e as { code?: string }).code;
// The person pressed Cancel at Accounts, or the pending cookie expired.
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
return problem(ctx, res, code === 'NO_PENDING' ? 'EXPIRED' : 'SIGNIN_FAILED');
}
const { claims, returnTo, idToken } = result;
const { user, created } = await userForClaims(ctx, claims);
if (!user) {
await audit(ctx, { actorId: claims.sub, actorRole: 'none', action: 'admin_sign_in_refused', targetType: 'website_user', targetId: claims.sub, ip: clientIp(req) });
return problem(ctx, res, 'NO_ACCESS', returnTo);
}
const mfa = claims.amr.includes('mfa');
if (!mfa && (await needsTwoFactor(ctx, user.role))) {
// Once: ask Accounts again with a second step. If it still comes back without one, say why.
if (askedForTwoFactor) return problem(ctx, res, 'TWO_FACTOR_NEEDED', returnTo);
return res.redirect(303, page(ctx, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`));
}
// Accounts' session id, when its token carries one (not part of crosscode.identity/1's claims).
const sid = (claims as unknown as { sid?: string }).sid ?? null;
await startSession(ctx, res, { userId: user.id, sid, mfa, idToken });
await audit(ctx, { actorId: user.id, actorRole: user.role, action: created ? 'first_owner_signed_in' : 'admin_signed_in', targetType: 'website_user', targetId: user.id, ip: clientIp(req) });
return res.redirect(303, page(ctx, returnTo));
});
r.get('/auth/me', handle(async (req, res) => {
const s = await currentSession(ctx, req);
if (!s) {
res.status(401).json({ error: { code: 'SIGNED_OUT', message: 'Please sign in.' } });
return undefined;
}
return { user: s.user, mfa: s.mfa };
}));
r.post('/auth/signout', async (req, res) => {
const s = await currentSession(ctx, req).catch(() => null);
res.clearCookie(SESSION_COOKIE, cookieOptions(ctx));
if (s) {
await ctx.db.session.delete({ where: { id: s.sessionId } }).catch(() => {});
await audit(ctx, { actorId: s.user.id, actorRole: s.user.role, action: 'admin_signed_out', targetType: 'website_user', targetId: s.user.id, ip: clientIp(req) });
}
// Then Accounts, so the person is signed out of all the church's sites and comes back here.
try {
const auth = await accounts(ctx);
return res.redirect(303, auth.signOutUrl(s?.idToken ?? undefined));
} catch {
return res.redirect(303, page(ctx, '/'));
}
});
r.post(OIDC_CLIENT_PATHS.backchannelLogout.replace(/^\/api/, ''), express.urlencoded({ extended: false, limit: '16kb' }), async (req, res) => {
try {
const auth = await accounts(ctx);
const { sub, sid } = await auth.verifyLogoutToken(String(req.body?.logout_token ?? ''));
// That Accounts session's sign-ins here, and any whose session id wasn't known.
await ctx.db.session.deleteMany({ where: sid ? { userId: sub, OR: [{ sid }, { sid: null }] } : { userId: sub } });
res.set('Cache-Control', 'no-store').status(200).end();
} catch (e) {
const code = (e as { code?: string }).code;
res.status(code === 'BAD_TOKEN' ? 400 : 503).json({ error: 'invalid_request' });
}
});
r.post(ACCOUNTS_CALL_PATH.replace(/^\/api/, ''), express.raw({ type: '*/*', limit: '256kb' }), async (req, res) => {
let call: AccountsCall;
try {
const auth = await accounts(ctx);
call = auth.verifyAccountsCall(req.body as Buffer, req.headers);
} catch (e) {
if (e instanceof AccountsUnavailable) return sendError(res, e);
return res.status(401).json({ error: { code: (e as { code?: string }).code ?? 'BAD_SIGNATURE', message: (e as Error).message } });
}
try {
return res.json(await handleAccountsCall(ctx, call, req));
} catch (e) {
return sendError(res, e);
}
});
return r;
}
/**
* Accounts' signed calls. The Website only keeps an admin's name, email and role, so: update the
* copy, export it, or remove the person (and their sessions). Someone the Website doesn't know is
* answered as done.
*/
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
const user = await ctx.db.websiteUser.findUnique({ where: { id: call.sub } });
switch (call.type) {
case 'user.updated': {
if (user) await ctx.db.websiteUser.update({ where: { id: user.id }, data: { name: call.profile.name, email: call.profile.email.toLowerCase() } });
return { schema: IDENTITY_SCHEMA, ok: true };
}
case 'user.export': {
const reply: UserExportReply = {
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'website', generatedAt: ctx.now().toISOString(),
sections: user ? [{
key: 'website_admin',
title: 'Your access to the church\'s website admin',
records: [{ name: user.name, email: user.email, role: user.role, since: user.createdAt.toISOString(), lastSignIn: user.lastSignInAt?.toISOString() ?? null }],
}] : [],
};
return reply;
}
case 'user.deleted': {
if (user) {
await ctx.db.session.deleteMany({ where: { userId: user.id } });
await ctx.db.websiteUser.delete({ where: { id: user.id } });
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'website_user_deleted', targetType: 'website_user', targetId: user.id, metadata: { role: user.role }, ip: clientIp(req) });
}
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
/**
* Admin sessions and roles (WEBSITE-1.0-PLAN §10). The Website keeps its own session after a
* sign-in through Accounts: an HttpOnly cookie with a random token, of which only the SHA-256 is
* stored. Roles are the Website's own (keyed by the account's `sub`); Accounts never says them.
*/
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import type { Ctx } from '../context.js';
import type { WebsiteRole } from '../generated/prisma/client.js';
import { ApiError } from '../http.js';
import { hashToken, randomToken } from '../lib/crypto.js';
export const SESSION_COOKIE = 'ccw_session';
/** Lowest to highest. A role can do what every role before it can. */
export const ROLES: readonly WebsiteRole[] = ['viewer', 'ministry_leader', 'editor', 'admin', 'owner'];
export const atLeast = (role: WebsiteRole, min: WebsiteRole) => ROLES.indexOf(role) >= ROLES.indexOf(min);
/** Roles that need a second step at sign-in (on by default, §10; AppSetting `two_factor_required_for_admins`). */
export async function needsTwoFactor(ctx: Ctx, role: WebsiteRole): Promise<boolean> {
return atLeast(role, 'admin') && (await ctx.settings.bool('two_factor_required_for_admins', true));
}
export function readCookies(req: Request): Record<string, string> {
const out: Record<string, string> = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const i = part.indexOf('=');
if (i > 0) {
try {
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
} catch {
// A cookie this site didn't write: ignored.
}
}
}
return out;
}
export const cookieOptions = (ctx: Ctx, path = '/') => ({ httpOnly: true, sameSite: 'lax' as const, secure: ctx.config.production, path });
export async function startSession(ctx: Ctx, res: Response, s: { userId: string; sid: string | null; mfa: boolean; idToken: string }) {
const token = randomToken();
const now = ctx.now();
const expiresAt = new Date(now.getTime() + ctx.config.sessionDays * 24 * 3600e3);
await ctx.db.session.create({
data: { tokenHash: hashToken(token), userId: s.userId, sid: s.sid, mfa: s.mfa, idToken: ctx.secrets.encrypt(s.idToken), createdAt: now, lastSeenAt: now, expiresAt },
});
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
}
export type Signed = {
sessionId: string;
idToken: string | null;
mfa: boolean;
user: { id: string; name: string; email: string; role: WebsiteRole; ministryId: string | null };
};
/** The signed-in admin for this request, or null. */
export async function currentSession(ctx: Ctx, req: Request): Promise<Signed | null> {
const token = readCookies(req)[SESSION_COOKIE];
if (!token) return null;
const session = await ctx.db.session.findUnique({ where: { tokenHash: hashToken(token) } });
if (!session) return null;
const now = ctx.now();
if (session.expiresAt <= now) {
await ctx.db.session.delete({ where: { id: session.id } }).catch(() => {});
return null;
}
const user = await ctx.db.websiteUser.findUnique({ where: { id: session.userId } });
if (!user) return null;
// Seen at most once a minute, so reading pages doesn't write on every request.
if (now.getTime() - session.lastSeenAt.getTime() > 60_000) {
await ctx.db.session.update({ where: { id: session.id }, data: { lastSeenAt: now } }).catch(() => {});
}
let idToken: string | null;
try {
idToken = session.idToken ? ctx.secrets.decrypt(session.idToken) : null;
} catch {
idToken = null;
}
return {
sessionId: session.id,
idToken,
mfa: session.mfa,
user: { id: user.id, name: user.name, email: user.email, role: user.role, ministryId: user.ministryId },
};
}
declare module 'express-serve-static-core' {
interface Request {
signed?: Signed;
}
}
/** Only signed-in admins with at least `min`. 401 when signed out, 403 when the role is too low. */
export function requireRole(ctx: Ctx, min: WebsiteRole = 'viewer'): RequestHandler {
return (req: Request, res: Response, next: NextFunction) => {
currentSession(ctx, req).then((s) => {
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
if (!atLeast(s.user.role, min)) return next(new ApiError(403, 'FORBIDDEN', 'Your role on this website can\'t do that.'));
req.signed = s;
return next();
}).catch(next);
};
}
+130
View File
@@ -0,0 +1,130 @@
/**
* Database backups (1.4.0, as Accounts' and Cross Events' Settings → Backups): a gzipped
* `pg_dump` into backend/backups/ every night (02:20, after Accounts' at 02:00) and whenever an
* admin asks, kept on this server only. The `crosscode` script makes the same files before every
* deploy and uninstall (scripts/products/website.sh), so the admin's list shows both, newest first.
* The database only: the uploads (backend/uploads) aren't in it, as in Events.
*
* Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last
* run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client).
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import type { Ctx } from '../context.js';
/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */
export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups');
/** The names this module and the crosscode script give a backup: website-YYYYMMDD-HHMMSS.sql.gz. */
export const BACKUP_FILE = /^website-\d{8}-\d{6}\.sql\.gz$/;
export const DEFAULT_RETAIN = 14;
const MAX_RETAIN = 365;
export type Backup = { filename: string; size: number; createdAt: Date };
/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */
export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise<void> };
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */
export const pgDump: Dumper = (databaseUrl) => {
const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stderr.on('data', (d) => { stderr += String(d); });
const done = new Promise<void>((resolve, reject) => {
child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`)));
child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`))));
});
return { stdout: child.stdout, done };
};
const pad = (n: number) => String(n).padStart(2, '0');
/** website-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */
export function backupName(at: Date): string {
return `website-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`;
}
export async function retainCount(ctx: Ctx): Promise<number> {
const n = Number(await ctx.settings.get('backup_retain_count'));
return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN;
}
/** Every backup in the folder, newest first. */
export async function listBackups(ctx: Ctx): Promise<Backup[]> {
let names: string[];
try {
names = await fs.promises.readdir(dir(ctx));
} catch {
return [];
}
const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => {
const st = await fs.promises.stat(path.join(dir(ctx), filename));
return { filename, size: st.size, createdAt: st.mtime };
}));
return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename));
}
/** The newest backup's time, for the Hub heartbeat. */
export async function lastBackupAt(ctx: Ctx): Promise<Date | null> {
return (await listBackups(ctx))[0]?.createdAt ?? null;
}
/** The full path of a backup to download, or null if there's no such backup (or a bad name). */
export function backupPath(ctx: Ctx, filename: string): string | null {
if (!BACKUP_FILE.test(filename)) return null;
const p = path.join(dir(ctx), filename);
return fs.existsSync(p) ? p : null;
}
/** Deletes the oldest backups beyond the number kept. */
export async function rotate(ctx: Ctx): Promise<number> {
const old = (await listBackups(ctx)).slice(await retainCount(ctx));
await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {})));
return old.length;
}
/**
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
* look like a real backup). Records the outcome for the admin page.
*/
export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise<Backup> {
const url = ctx.config.databaseUrl;
try {
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
// Two in the same second (the button pressed twice): the next free second's name.
const at = ctx.now().getTime();
let filename = backupName(new Date(at));
for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000));
const file = path.join(dir(ctx), filename);
const { stdout, done } = dumper(url);
// Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way,
// so a failed one's file is deleted after the last write, not before it.
const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]);
const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected');
if (failed) {
await fs.promises.unlink(file).catch(() => {});
throw failed.reason;
}
await rotate(ctx);
await ctx.settings.set('backup_last_error', null);
const st = await fs.promises.stat(file);
return { filename, size: st.size, createdAt: st.mtime };
} catch (e) {
await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
throw e;
}
}
/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */
export async function runBackupJob(ctx: Ctx) {
if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true };
const b = await runBackup(ctx);
return { filename: b.filename, size: b.size };
}
@@ -0,0 +1,71 @@
/**
* The church profile (`crosscode.church/1`) from the church's Accounts (WEBSITE-1.0-PLAN §2): name,
* logo, colours, brand style, service times, contact, social, the church's other sites. Accounts
* owns it; the Website shows it and never stores it (§2: shared facts aren't drafts). As Events
* 3.7's accounts/church.ts: kept in memory for 10 minutes, the last copy kept while Accounts can't
* be reached (tried again after a minute).
*
* Before the Website is linked to Accounts (and in local development) the profile saved in
* AppSetting `church_profile_local` is used, if any (`npm run demo` saves the demo church's).
*/
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { accountsLink } from '../auth/accounts.js';
const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000;
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
async function fetchProfile(accountsUrl: string): Promise<Church> {
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
const parsed = churchSchema.safeParse(await res.json());
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
return parsed.data;
}
async function localProfile(ctx: Ctx): Promise<Church | null> {
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
const parsed = raw ? churchSchema.safeParse(raw) : null;
return parsed?.success ? parsed.data : null;
}
/** The church's profile, or null when there's none yet. Never throws. */
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
let link;
try {
link = await accountsLink(ctx);
} catch {
link = null;
}
if (!link) return localProfile(ctx).catch(() => null);
let state = caches.get(ctx);
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
const { cached } = state;
const url = link.url;
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
if (!state.pending) {
const last = cached?.url === url ? cached.church : null;
const s = state;
s.pending = fetchProfile(url)
.then((church) => {
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
return church;
}, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message);
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
return last;
})
.finally(() => { s.pending = null; });
}
return state.pending;
}
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
export function churchChanged(ctx: Ctx): void {
const state = caches.get(ctx);
if (state?.cached) state.cached = { ...state.cached, at: 0 };
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
* whole app against an in-memory database and a stand-in Accounts (tests/support/).
*/
import type { PrismaClient } from './generated/prisma/client.js';
import type { Config } from './lib/config.js';
import { Secrets } from './lib/crypto.js';
import { Settings } from './lib/settings.js';
import { loadAuthClient, type AuthClientModule } from './auth/accounts.js';
export type Db = PrismaClient;
export type Ctx = {
config: Config;
db: Db;
secrets: Secrets;
settings: Settings;
/** `@crosscode/auth-client` (tests give a stand-in). */
authClient: () => Promise<AuthClientModule>;
now: () => Date;
/** Fetches what visitors are shown from outside (YouTube's thumbnails); tests give a stand-in. */
fetch?: (url: string) => Promise<Response>;
};
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule>; fetch?: (url: string) => Promise<Response> } = {}): Ctx {
const secrets = new Secrets(config.secret);
const partial = { config, db, secrets } as Ctx;
partial.settings = new Settings(partial);
partial.authClient = opts.authClient ?? loadAuthClient;
partial.now = opts.now ?? (() => new Date());
if (opts.fetch) partial.fetch = opts.fetch;
return partial;
}
+270
View File
@@ -0,0 +1,270 @@
/**
* The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
*
* 1.3.0: also the eight demo profiles (seeds.ts, `npm run demo -- --profile bold-plant`), which
* keep the church's own profile (Accounts' organisation settings), the site settings, the site
* icon and the admins, and name the church in the copy. A template alone (development, e2e) is
* still Acacia Hill, profile and all, exactly as before.
*
* It replaces the Website's content (never the admins), so the script refuses on a site that has
* been published unless told otherwise.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { CHURCH_SCHEMA, WEBSITE_TEMPLATES, type agent, type Church, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import type { SectionData } from '../site/sections.js';
import { publish } from '../site/snapshot.js';
import { TEMPLATE_HEADERS, TEMPLATE_VARIANTS, SECTION_TYPES, defaultDesign, type SiteDesign } from '../site/variants.js';
import { DEMO_SEEDS, type DemoSeed } from './seeds.js';
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
export function demoProfile(publicUrl: string): Church {
return {
schema: CHURCH_SCHEMA,
customerId: '00000000-0000-4000-8000-000000000001',
updatedAt: '2026-11-25T08:00:00.000Z',
name: 'Acacia Hill Church',
shortName: 'Acacia Hill',
timezone: 'Africa/Johannesburg',
locale: 'en-ZA',
branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } },
campuses: [],
serviceTimes: [
{ day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null },
{ day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' },
{ day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null },
],
contact: {
email: 'hello@acaciahill.example',
phone: '+27125550123',
whatsapp: '+27825550123',
address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } },
},
social: [
{ network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' },
{ network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' },
],
links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' },
} as Church;
}
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
export function illustration(seed: number, w = 1600, h = 1000, colours: { primary: string; accent: string } = DEMO_COLOURS): string {
const hues = [colours.primary, colours.accent, '#7fb7be', '#f3e3c3', '#284b52'];
const c = (i: number) => hues[(seed + i) % hues.length];
const y = (f: number) => Math.round(h * f);
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c(3)}"/><stop offset="1" stop-color="#fffaf0"/></linearGradient></defs>
<rect width="${w}" height="${h}" fill="url(#sky)"/>
<circle cx="${Math.round(w * (0.2 + (seed % 5) * 0.15))}" cy="${y(0.3)}" r="${Math.round(h * 0.12)}" fill="${c(1)}" opacity="0.85"/>
<path d="M0 ${y(0.62)} Q ${w * 0.25} ${y(0.45)} ${w * 0.5} ${y(0.6)} T ${w} ${y(0.55)} V ${h} H 0 Z" fill="${c(2)}"/>
<path d="M0 ${y(0.75)} Q ${w * 0.35} ${y(0.6)} ${w * 0.7} ${y(0.74)} T ${w} ${y(0.7)} V ${h} H 0 Z" fill="${c(0)}"/>
<path d="M${w * 0.45} ${h} C ${w * 0.5} ${y(0.85)} ${w * 0.6} ${y(0.8)} ${w * 0.62} ${y(0.72)}" stroke="${c(3)}" stroke-width="${Math.round(h * 0.03)}" fill="none" stroke-linecap="round"/>
</svg>`;
}
type Ids = Record<string, string>;
const HEX = /^#[0-9a-f]{6}$/i;
async function demoMedia(ctx: Ctx, uploadDir: string, alts: Record<string, string>, colours: { primary: string; accent: string }): Promise<Ids> {
const items: [string, number][] = [['hero', 0], ['collage2', 1], ['collage3', 2], ['welcome', 3], ['pastor', 4], ['invite', 5], ['kids', 6], ['youth', 7], ['care', 8], ['music', 9]];
const ids: Ids = {};
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
for (const [key, seed] of items) {
const filename = `demo/${key}.svg`;
const svg = illustration(seed, 1600, 1000, colours);
fs.writeFileSync(path.join(uploadDir, filename), svg);
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt: alts[key]! } });
ids[key] = row.id;
}
return ids;
}
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
/** The development demo church (Acacia Hill), on any template: what a template alone loads. */
const CLASSIC: Omit<DemoSeed, 'template'> & { pastorName: string; ctaText: string; descriptions: Record<string, string>; alts: Record<string, string> } = {
id: 'classic', label: 'Acacia Hill (development)', alternate: false,
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', button: { label: 'Plan your visit', href: '/visit' } },
serviceNote: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.',
welcome: {
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
quote: 'We would love to meet you. Come and say hello at the welcome table.',
},
ministriesIntro: 'There is something for every age and stage.',
teamIntro: null,
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' } },
visit: {
expect: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.',
kids: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.',
cta: 'Questions before you come?',
},
ctaText: 'Send us a WhatsApp and we will get back to you.',
about: { story: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.', quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' },
give: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.'],
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.'],
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.'],
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.'],
],
leaders: [['Thandi Mokoena', 'Lead pastor'], ['Pieter van Wyk', 'Associate pastor'], ['Lerato Dlamini', 'Kids and families'], ['Johan Botha', 'Worship']],
pastorName: 'Pastor Thandi Mokoena',
series: ['hope-for-today', 'Hope for today'],
messages: [['hope-that-holds', 'A hope that holds', 3, 'Psalm 23'], ['bread-for-the-road', 'Bread for the road', 10, 'Psalm 23'], ['the-good-shepherd', 'The good shepherd', 17, 'Psalm 23']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
],
venue: 'Acacia Hill Church',
descriptions: {
home: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.',
visit: 'What to expect on your first Sunday at Acacia Hill Church.',
about: 'Our story, what we believe and what we value.',
ministries: 'Kids, youth, worship, care and prayer at Acacia Hill.',
leadership: 'The team who lead Acacia Hill Church.',
events: 'What is coming up at Acacia Hill Church.',
messages: 'Sunday messages from Acacia Hill Church.',
give: 'How to give to Acacia Hill Church.',
contact: 'Find Acacia Hill Church in Westridge, Pretoria.',
},
alts: {
hero: 'The hills behind Acacia Hill at sunrise (illustration)', collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: 'The church garden (illustration)', pastor: 'Illustration standing in for the pastor\'s photo', invite: 'A sunny Sunday morning (illustration)',
kids: 'Illustration for Kids church', youth: 'Illustration for Youth', care: 'Illustration for Care and prayer', music: 'Illustration for Worship',
},
};
/** A demo profile's design: the template's defaults, or (alternate) its second recommendations and header. */
export function seedDesign(template: WebsiteTemplate, alternate: boolean): SiteDesign {
const design = defaultDesign(template);
if (!alternate) return design;
const variants = Object.fromEntries(SECTION_TYPES.map((s) => {
const options = TEMPLATE_VARIANTS[template][s] as readonly string[];
return [s, options[1] ?? options[0]!];
})) as SiteDesign['variants'];
const headers = TEMPLATE_HEADERS[template] as readonly string[];
return { ...design, variants, style: { ...design.style, header: headers[1] ?? headers[0]! } };
}
export const isDemoTemplate = (v: string): v is WebsiteTemplate => (WEBSITE_TEMPLATES as readonly string[]).includes(v);
/**
* Replaces the content with a demo, then publishes it. `what`: a template (the Acacia Hill church,
* its profile saved too) or a demo profile (keeps the church's profile; Acacia Hill's is saved
* only on a site that has none at all, so the site still has a name).
*/
export async function loadDemo(ctx: Ctx, what: WebsiteTemplate | agent.WebsiteDemoProfile, opts: { uploadDir?: string; publishedBy?: string } = {}) {
const db = ctx.db;
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
const classic = isDemoTemplate(what);
const seed: DemoSeed = classic ? { ...CLASSIC, template: what } : DEMO_SEEDS[what];
const extra = classic ? CLASSIC : null;
// The church: Acacia Hill for a template; else whoever the site belongs to.
let church = classic ? null : await churchProfile(ctx);
if (!church) {
church = demoProfile(ctx.config.publicUrl);
await ctx.settings.set('church_profile_local', JSON.stringify(church));
}
const name = church.name;
const short = church.shortName || church.name;
const city = church.contact?.address?.city || church.contact?.address?.suburb || 'town';
const t = (s: string) => s.replaceAll('{name}', name).replaceAll('{short}', short).replaceAll('{city}', city);
const brand = church.branding?.colours;
const colours = classic || !brand?.primary || !HEX.test(brand.primary)
? DEMO_COLOURS
: { primary: brand.primary, accent: brand.accent && HEX.test(brand.accent) ? brand.accent : DEMO_COLOURS.accent };
// The site icon is a setting, so its picture stays; every other picture goes with the content.
const faviconId = classic ? null : await ctx.settings.get('favicon_media_id');
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'siteVersion', 'siteDesign', 'slugHistory', 'previewLink'] as const) {
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
}
await db.mediaAsset.deleteMany(faviconId ? { where: { NOT: { id: faviconId } } } : undefined);
const [pastorName] = seed.leaders[0]!;
const ministryNames = seed.ministries.map(([, n]) => t(n));
const alts = extra?.alts ?? {
hero: `${t(seed.hero.headline)} (illustration)`, collage2: 'A path through the veld (illustration)', collage3: 'Evening over the valley (illustration)',
welcome: `${short} (illustration)`, pastor: `Illustration standing in for ${pastorName}'s photo`, invite: 'A sunny Sunday morning (illustration)',
kids: `Illustration for ${ministryNames[0]}`, youth: `Illustration for ${ministryNames[1]}`, music: `Illustration for ${ministryNames[2]}`, care: `Illustration for ${ministryNames[3]}`,
};
const img = await demoMedia(ctx, uploadDir, alts, colours);
const design = classic ? defaultDesign(seed.template) : seedDesign(seed.template, seed.alternate);
await db.siteDesign.create({ data: { id: 1, template: seed.template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
const speaker = extra?.pastorName ?? pastorName;
const home: SectionData = {
hero: { headline: t(seed.hero.headline), subline: t(seed.hero.subline), images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: seed.hero.button },
serviceTimes: { heading: 'Join us this Sunday', note: t(seed.serviceNote) },
welcome: {
heading: t(seed.welcome.heading), mission: t(seed.welcome.mission), body: t(seed.welcome.body),
imageId: img.welcome!, pastor: { name: speaker, role: seed.leaders[0]![1], quote: t(seed.welcome.quote), photoId: img.pastor! },
},
ministries: { heading: 'Find your place', intro: t(seed.ministriesIntro) },
team: { heading: 'Our team', intro: seed.teamIntro ? t(seed.teamIntro) : null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: t(seed.invitation.heading), text: t(seed.invitation.text), button: seed.invitation.button, imageId: img.invite! },
};
const d = (kind: string, fallback: string) => extra?.descriptions[kind] ?? t(fallback);
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: d('home', `${seed.hero.subline}`), sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: d('visit', 'What to expect on your first Sunday at {name}.'), sections: [
{ type: 'text', data: { heading: 'What to expect', body: t(seed.visit.expect) } },
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: t(seed.visit.kids), imageId: img.kids, button: null } },
{ type: 'cta', data: { heading: t(seed.visit.cta), text: extra?.ctaText ?? 'Send us a message and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{
kind: 'about', slug: 'about', title: 'About us', position: 2, description: d('about', 'Our story, what we believe and what we value.'), sections: [
{ type: 'text', data: { heading: 'Our story', body: t(seed.about.story) } },
{ type: 'quote', data: { quote: seed.about.quote, by: seed.about.by } },
],
},
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: d('ministries', `${ministryNames.join(', ')} at {short}.`), sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: d('leadership', 'The team who lead {name}.'), sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: d('events', 'What is coming up at {name}.'), sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: d('messages', 'Sunday messages from {name}.'), sections: [] },
{
kind: 'give', slug: 'give', title: 'Give', position: 7, description: d('give', 'How to give to {name}.'), sections: [
{ type: 'text', data: { heading: 'Giving', body: t(seed.give) } },
],
},
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: d('contact', 'Find {name} in {city}.'), sections: [] },
];
for (const p of pages) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
let i = 0;
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
}
const pictures = [img.kids!, img.youth!, img.music!, img.care!];
let n = 0;
for (const [slug, , summary] of seed.ministries) await db.ministry.create({ data: { slug, name: ministryNames[n]!, summary: t(summary), imageId: pictures[n]!, position: n++ } });
n = 0;
for (const [leader, role] of seed.leaders) await db.leader.create({ data: { name: leader, role, photoId: n === 0 ? img.pastor! : null, position: n++ } });
const now = ctx.now();
const day = 864e5;
const series = await db.messageSeries.create({ data: { slug: seed.series[0], title: seed.series[1] } });
for (const [slug, title, ago, passage] of seed.messages) {
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker, passage, seriesId: series.id, publishedAt: now } });
}
for (const [slug, title, inDays, description] of seed.events) {
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: t(seed.venue), description: t(description), publishedAt: now } });
}
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, classic ? `Demo church on ${seed.template}` : `Demo: ${seed.label}`);
}
+334
View File
@@ -0,0 +1,334 @@
/**
* The Website's demo profiles (1.3.0, contracts `WEBSITE_DEMO_PROFILES`): eight fictional churches,
* two per template, for the Hub's demo sites (`crosscode demo <church> website --profile …`).
*
* A demo replaces the content only. The church's profile (name, logo, colours, service times,
* contact: Accounts' organisation settings) stays, so the copy names the church with placeholders:
* `{name}` (Hope Family Church), `{short}` (Hope Family) and `{city}` (Pretoria). The second
* profile of each template starts on the template's other recommended variants and header, so the
* eight show every recommended look.
*
* Every person and place in here is made up. A profile id never changes once released.
*/
import { agent, type WebsiteTemplate } from '@crosscode/contracts';
type WebsiteDemoProfile = agent.WebsiteDemoProfile;
type Button = { label: string; href: string };
export type DemoSeed = {
id: WebsiteDemoProfile | 'classic';
template: WebsiteTemplate;
/** What the Hub shows: "Heritage: a parish church". */
label: string;
/** Start on the template's second recommended variant of every section, and its second header. */
alternate: boolean;
hero: { headline: string; subline: string; button: Button };
serviceNote: string;
welcome: { heading: string; mission: string; body: string; quote: string };
ministriesIntro: string;
teamIntro: string | null;
invitation: { heading: string; text: string; button: Button };
visit: { expect: string; kids: string; cta: string };
about: { story: string; quote: string; by: string };
give: string;
/** Four: [slug, name, summary]. Their pictures are the kids, youth, music and care illustrations, in order. */
ministries: [string, string, string][];
/** Four: [name, role]. The first is the pastor on the home page and the speaker of the messages. */
leaders: [string, string][];
series: [string, string];
/** Three: [slug, title, days ago, passage]. */
messages: [string, string, number, string][];
/** Three: [slug, title, in days, description]. */
events: [string, string, number, string][];
/** Where the events are. */
venue: string;
};
const visitButton: Button = { label: 'Plan your visit', href: '/visit' };
export const DEMO_SEEDS: Record<WebsiteDemoProfile, DemoSeed> = {
'heritage-parish': {
id: 'heritage-parish', template: 'heritage', label: 'Heritage: a parish church with a long history', alternate: false,
hero: { headline: 'Worshipping together since 1896', subline: 'An old church with a warm welcome in the heart of {city}. Traditional services, every generation together.', button: visitButton },
serviceNote: 'Holy Communion on the first Sunday of the month. Tea in the parish hall after every service.',
welcome: {
heading: 'Welcome to {name}', mission: 'Rooted in prayer, open to all, serving {city}.',
body: 'For more than a century people have gathered here to pray, to sing the old hymns and to hear God\'s word. Our services follow the prayer book, our choir sings most Sundays, and our doors are open to anyone who wants to come in out of the noise.',
quote: 'Whether this is your first time in a church or your thousandth, you are welcome here.',
},
ministriesIntro: 'Ways to belong, from the choir stalls to the Sunday school.',
teamIntro: 'The clergy and lay ministers who care for the parish.',
invitation: { heading: 'There is always a place in the pews', text: 'Join us this Sunday. Someone at the door will show you the way.', button: visitButton },
visit: {
expect: 'Our services follow a set order with readings, prayers and hymns. The words are printed in the service sheet, so you can follow along. A service lasts about an hour.',
kids: 'Sunday school meets in the hall during the sermon, and the children come back in for the blessing.',
cta: 'Would you like to talk to the rector before you come?',
},
about: { story: '{name} was founded by a handful of families in 1896, and the stone church was finished in 1912. The stained glass, the organ and the bell are all gifts from the parish over the years.', quote: 'Be still, and know that I am God.', by: 'Psalm 46:10' },
give: 'Thank you for supporting the life of the parish and the upkeep of the church building. You can give by EFT or in the plate on Sundays (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Bible stories, songs and crafts for ages 4 to 11 during the sermon.'],
['servers', 'Altar servers', 'Teenagers who help lead worship on Sunday mornings.'],
['choir', 'The parish choir', 'Choral evensong once a month and anthems every Sunday. New voices welcome.'],
['pastoral-care', 'Pastoral visiting', 'Home communion and visits for those who can\'t come to church.'],
],
leaders: [['The Revd Margaret Pillay', 'Rector'], ['The Revd Sipho Ndlovu', 'Assistant priest'], ['Anne Fourie', 'Director of music'], ['David Smith', 'Churchwarden']],
series: ['the-lords-prayer', 'The Lord\'s Prayer'],
messages: [['your-kingdom-come', 'Your kingdom come', 3, 'Matthew 6:10'], ['our-daily-bread', 'Our daily bread', 10, 'Matthew 6:11'], ['forgive-us', 'Forgive us as we forgive', 17, 'Matthew 6:12']],
events: [
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share on the rectory lawn. Games for the children.'],
['advent-carols', 'Advent carol service', 13, 'Readings and carols by candlelight, sung by the parish choir.'],
['christmas-eve', 'Christmas Eve midnight mass', 27, 'The first Communion of Christmas, with carols from 23:15.'],
],
venue: '{name}',
},
'heritage-city': {
id: 'heritage-city', template: 'heritage', label: 'Heritage: a city-centre church with weekday services', alternate: true,
hero: { headline: 'A quiet place in a busy city', subline: 'In the middle of {city}, open every weekday for prayer, lunchtime services and a cup of tea.', button: { label: 'Come in this week', href: '/visit' } },
serviceNote: 'Lunchtime service on weekdays at 13:05, twenty-five minutes, back at your desk in time.',
welcome: {
heading: 'Right in the heart of {city}', mission: 'A church for the city: for workers, students, visitors and neighbours.',
body: 'Thousands of people walk past our doors every day. Some come in to sit in the quiet, some to light a candle, some for the lunchtime service. On Sundays we worship as a congregation drawn from all over {city}.',
quote: 'The city needs places that are quiet and kind. We try to be one.',
},
ministriesIntro: 'Serving the city through the week.',
teamIntro: null,
invitation: { heading: 'The doors are open', text: 'Monday to Friday from 08:00 to 16:00. Come in for a moment, or for the service.', button: { label: 'When we are open', href: '/visit' } },
visit: {
expect: 'The weekday service is short and simple: a reading, a short talk and prayers. On Sundays the service is longer, with the choir and Communion.',
kids: 'Children are welcome at every service. There are activity bags at the back of the church.',
cta: 'Want to know more about the city ministries?',
},
about: { story: '{name} has stood on this corner since the city was young. Today our congregation is students, office workers, families and people who sleep on the streets nearby, all at the same tables.', quote: 'Seek the welfare of the city, and pray to the Lord on its behalf.', by: 'Jeremiah 29:7' },
give: 'Your gifts keep the doors open on weekdays and fund the soup kitchen (demo details only: this is not a real account).',
ministries: [
['students', 'Students', 'Supper and a Bible study for students on Tuesday evenings.'],
['young-workers', 'Young professionals', 'Breakfast before work on Thursdays at 07:00.'],
['lunchtime-music', 'Lunchtime concerts', 'Free organ and chamber music on Wednesdays.'],
['soup-kitchen', 'The soup kitchen', 'Soup and bread for anyone who needs it, every weekday at noon.'],
],
leaders: [['Canon Peter Mahlangu', 'Vicar'], ['The Revd Claire Jacobs', 'City chaplain'], ['Tom Venter', 'Organist'], ['Nomsa Khumalo', 'Soup kitchen coordinator']],
series: ['songs-of-ascent', 'Songs of Ascent'],
messages: [['unless-the-lord-builds', 'Unless the Lord builds the house', 4, 'Psalm 127'], ['i-lift-up-my-eyes', 'I lift up my eyes', 11, 'Psalm 121'], ['how-good-and-pleasant', 'How good and pleasant', 18, 'Psalm 133']],
events: [
['organ-recital', 'Lunchtime organ recital', 2, 'Bach and Buxtehude, 13:05 to 13:40. Free, with a retiring collection.'],
['blue-christmas', 'Blue Christmas', 16, 'A quiet service for anyone who finds Christmas hard.'],
['city-carols', 'Carols for the city', 23, 'Readings and carols for everyone who works in {city}.'],
],
venue: '{name}',
},
'bold-youth': {
id: 'bold-youth', template: 'bold', label: 'Bold: a young, music-led church', alternate: false,
hero: { headline: 'Loud worship. Real people. Good news.', subline: '{short} is a church for {city}: come for the music, stay for the family.', button: { label: 'Visit this Sunday', href: '/visit' } },
serviceNote: 'Doors open half an hour before. Coffee bar in the foyer, kids church at the morning service.',
welcome: {
heading: 'This is {short}', mission: 'Helping people find and follow Jesus, together.',
body: 'We are a young church with a big heart for {city}. Sundays are full of energy: a live band, a message you can use on Monday, and people who will remember your name. Wherever you are coming from, you belong here.',
quote: 'We are not a perfect church. We are a family learning to follow Jesus together.',
},
ministriesIntro: 'Get connected. There is a place for you.',
teamIntro: null,
invitation: { heading: 'Your seat is waiting', text: 'Tell us you are coming and we will have a coffee ready for you.', button: { label: 'I am coming', href: '/visit' } },
visit: {
expect: 'Expect about 30 minutes of live worship and a 30-minute message. Come as you are: jeans are fine.',
kids: 'Kids church is high energy, safe and fun. Check your kids in at the kids desk when you arrive.',
cta: 'Got questions? Our team will get back to you.',
},
about: { story: '{short} started in a living room with twelve students and a guitar. Today we are a church of every age, but we have never lost the joy of that first night.', quote: 'I have come that they may have life, and have it to the full.', by: 'John 10:10' },
give: 'Generosity is part of who we are. Give online, by EFT or at the giving station (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Ages 2 to 12, every Sunday morning.'],
['youth', 'Youth', 'Grades 8 to 12, Friday nights. Games, worship, real talk.'],
['creative', 'Worship and creative', 'Band, sound, lights and media. Auditions every term.'],
['groups', 'Connect groups', 'Meet in a home during the week and do life together.'],
],
leaders: [['Jason and Lindi Naidoo', 'Lead pastors'], ['Kagiso Molefe', 'Youth pastor'], ['Megan Steyn', 'Worship pastor'], ['Ruan Pretorius', 'Connect groups']],
series: ['unstoppable', 'Unstoppable'],
messages: [['fearless', 'Fearless', 3, 'Joshua 1:9'], ['all-in', 'All in', 10, 'Romans 12:1-2'], ['no-turning-back', 'No turning back', 17, 'Luke 9:62']],
events: [
['worship-night', 'Worship night', 5, 'Two hours of worship and prayer. Bring your friends.'],
['youth-camp', 'Summer youth camp', 19, 'Three days at the river for grades 8 to 12. Registration is open.'],
['christmas-experience', 'The Christmas experience', 26, 'Music, lights and the Christmas story for the whole family.'],
],
venue: 'The {short} auditorium',
},
'bold-plant': {
id: 'bold-plant', template: 'bold', label: 'Bold: a new church plant meeting in a school', alternate: true,
hero: { headline: 'A new church for {city}', subline: 'We are launching soon. Meet us on Sundays in the school hall and be part of something new.', button: { label: 'Find out more', href: '/about' } },
serviceNote: 'We meet in the school hall. Look for the flags at the gate; parking is on the field.',
welcome: {
heading: 'Something new is starting', mission: 'A church for people who don\'t go to church.',
body: '{short} is a brand-new church. We are a small team who moved to {city} to start a church for our neighbours. Every week we set up chairs in a school hall, and every week new people walk in. There is room for you on the team.',
quote: 'Every great church was once a few people setting out chairs.',
},
ministriesIntro: 'Small team, big vision. Find where you fit.',
teamIntro: 'The launch team.',
invitation: { heading: 'Join the launch team', text: 'Help us set up, welcome, play or pray. Every hand matters right now.', button: { label: 'Get involved', href: '/contact' } },
visit: {
expect: 'Our services are relaxed and short: songs, a talk and time to talk over coffee afterwards. Nobody will put you on the spot.',
kids: 'Kids are part of the service for the songs, then go to their own room in the classroom next door.',
cta: 'Want to meet the team first?',
},
about: { story: '{short} was planted last year by a team of eight with the support of churches across the country. We have met in lounges, a coffee shop and now the school hall.', quote: 'See, I am doing a new thing! Now it springs up; do you not perceive it?', by: 'Isaiah 43:19' },
give: 'Every gift helps us reach a new neighbourhood with the good news (demo details only: this is not a real account).',
ministries: [
['kids-room', 'Kids room', 'A safe, fun room for children during the service.'],
['set-up', 'Set-up team', 'Chairs, sound and signs from 07:30. Breakfast is on us.'],
['band', 'Band', 'Guitar, keys, drums or voice. We need you.'],
['dinner-church', 'Dinner church', 'Supper and a conversation about Jesus on Wednesdays.'],
],
leaders: [['Ben and Zanele Moore', 'Church planters'], ['Ayesha Patel', 'Kids'], ['Chris Hendricks', 'Music'], ['Grace Okafor', 'Community']],
series: ['new-beginnings', 'New beginnings'],
messages: [['why-church', 'Why church?', 4, 'Acts 2:42-47'], ['the-first-step', 'The first step', 11, 'Mark 1:16-20'], ['a-seat-at-the-table', 'A seat at the table', 18, 'Luke 14:15-24']],
events: [
['launch-sunday', 'Launch Sunday', 7, 'Our first public service. Bring everyone you know.'],
['street-braai', 'Street braai', 14, 'Food and games for the neighbourhood in the school grounds.'],
['christmas-in-the-hall', 'Christmas in the hall', 24, 'A family carol service with mince pies.'],
],
venue: 'The school hall',
},
'community-family': {
id: 'community-family', template: 'community', label: 'Community: a family church with small groups', alternate: false,
hero: { headline: 'Come as you are, bring the family', subline: 'A friendly church in {city} where kids are noisy, coffee is hot and everyone knows your name.', button: visitButton },
serviceNote: 'Kids church for every age during the service. Coffee and juice afterwards on the lawn.',
welcome: {
heading: 'Hello, we are {short}', mission: 'Families following Jesus together, every day of the week.',
body: 'We are mums, dads, grandparents, singles, teenagers and toddlers. On Sundays we worship together, and during the week we meet in homes across {city} to eat, pray and look after each other.',
quote: 'Church is not a building we go to. It is a family we belong to.',
},
ministriesIntro: 'Something for every member of the family.',
teamIntro: 'The people who look after our church family.',
invitation: { heading: 'Pop in this Sunday', text: 'Let us know you are coming and we will save you a spot (and a muffin).', button: visitButton },
visit: {
expect: 'Our services are friendly and informal and last about an hour and a quarter. You don\'t need to know the songs or the Bible to feel at home.',
kids: 'Babies to grade 7 have their own groups with trained, screened leaders. There is a parents\' room with the service on a screen.',
cta: 'Questions about the kids? Ask us anything.',
},
about: { story: '{short} began when three families started meeting for a Bible study and the kids outnumbered the grown-ups. We still think that is a good sign.', quote: 'As for me and my household, we will serve the Lord.', by: 'Joshua 24:15' },
give: 'Thank you for helping us care for families in {city} (demo details only: this is not a real account).',
ministries: [
['little-ones', 'Little ones', 'Babies and toddlers, with a play area and story time.'],
['teens', 'Teens', 'Grades 6 to 12 on Friday evenings: games, food and faith.'],
['worship-team', 'Worship team', 'Singers and musicians of all ages lead us on Sundays.'],
['home-groups', 'Home groups', 'Twelve groups across {city}, every Tuesday or Wednesday.'],
],
leaders: [['Pastor Andile Zulu', 'Senior pastor'], ['Michelle de Beer', 'Children\'s pastor'], ['Kevin and Tracy Reddy', 'Home groups'], ['Lwazi Mthembu', 'Youth']],
series: ['family-matters', 'Family matters'],
messages: [['love-at-home', 'Love at home', 3, '1 Corinthians 13'], ['raising-faith', 'Raising faith', 10, 'Deuteronomy 6:4-9'], ['better-together', 'Better together', 17, 'Ecclesiastes 4:9-12']],
events: [
['fun-day', 'Family fun day', 6, 'Jumping castles, a cake sale and a soccer match for dads.'],
['holiday-club', 'Holiday club', 15, 'Four mornings of games, crafts and stories for ages 4 to 12.'],
['christmas-family-service', 'Christmas family service', 25, 'Our nativity, sung by the kids, followed by tea.'],
],
venue: '{name}',
},
'community-town': {
id: 'community-town', template: 'community', label: 'Community: a country-town church serving its district', alternate: true,
hero: { headline: 'Neighbours, friends, family', subline: 'The church in {city} that has been part of farm and town life for generations.', button: { label: 'Meet us on Sunday', href: '/visit' } },
serviceNote: 'Combined service on the last Sunday of the month, with a bring-and-share lunch.',
welcome: {
heading: 'Welcome to {name}', mission: 'Loving God and serving our district, farm and town alike.',
body: 'In a small town everyone knows everyone, and the church is where we meet in good times and hard ones. We pray for the rain, we help with the harvest festival, and when someone is in need we turn up with a casserole.',
quote: 'A small church can have a big heart. Come and see.',
},
ministriesIntro: 'Serving town and farm through the week.',
teamIntro: null,
invitation: { heading: 'You are always welcome here', text: 'Visiting the district? Join us on Sunday morning and stay for tea.', button: { label: 'Find us', href: '/contact' } },
visit: {
expect: 'A friendly, simple service with hymns and newer songs, a Bible message and prayers for the district. About an hour.',
kids: 'Children start in the service and go to Sunday school after the first songs.',
cta: 'Need a lift to church? Let us know.',
},
about: { story: 'The first service in {city} was held under a tree in the square. The church was built by local farmers and townspeople, stone by stone, and it is still the heart of the town.', quote: 'While the earth remains, seedtime and harvest shall not cease.', by: 'Genesis 8:22' },
give: 'Your gifts help us support families in the district through hard seasons (demo details only: this is not a real account).',
ministries: [
['sunday-school', 'Sunday school', 'Every Sunday for children of the town and the farms.'],
['youth', 'Youth', 'Friday evenings for high schoolers from the district.'],
['music', 'Choir and band', 'Old hymns and new songs, rehearsing on Thursdays.'],
['outreach', 'Farm outreach', 'Visits, food parcels and prayer for farmworker families.'],
],
leaders: [['Ds. Willem Coetzee', 'Minister'], ['Elsie Maritz', 'Sunday school'], ['Bongani Sithole', 'Farm outreach'], ['Marie Louw', 'Music']],
series: ['seasons', 'Seasons'],
messages: [['a-time-to-plant', 'A time to plant', 4, 'Ecclesiastes 3:1-8'], ['waiting-for-rain', 'Waiting for rain', 11, 'James 5:7-8'], ['the-harvest-is-plentiful', 'The harvest is plentiful', 18, 'Matthew 9:35-38']],
events: [
['harvest-festival', 'Harvest festival', 8, 'Produce, baking and crafts in the church hall, for the district\'s food bank.'],
['farm-carols', 'Carols on the farm', 20, 'An evening carol service at the Botha family\'s farm. Bring a chair.'],
['new-year-prayer', 'New Year prayer breakfast', 36, 'Pray for the year ahead over breakfast in the hall.'],
],
venue: '{name}',
},
'clean-modern': {
id: 'clean-modern', template: 'clean', label: 'Clean: a contemporary church, simply put', alternate: false,
hero: { headline: 'Faith for real life', subline: 'Sundays in {city}. Honest conversations, good coffee, and Jesus at the centre.', button: visitButton },
serviceNote: 'One service, about an hour. Kids programme included.',
welcome: {
heading: 'A church without the fuss', mission: 'Clear about Jesus. Open to questions.',
body: 'We keep things simple so the important things stand out. Our Sundays are thoughtful and relaxed, and our groups are a good place to ask the questions you have been carrying around.',
quote: 'Bring your questions. We are not afraid of them.',
},
ministriesIntro: 'A few things, done well.',
teamIntro: null,
invitation: { heading: 'See you on Sunday', text: 'No pressure, no spotlight. Just come.', button: visitButton },
visit: {
expect: 'A few songs, a talk that takes the Bible and your life seriously, and time to chat afterwards.',
kids: 'Kids have their own programme during the service, in age groups up to grade 7.',
cta: 'Prefer to message first?',
},
about: { story: '{short} began in 2015 with a simple idea: a church where it is normal to doubt, to ask and to grow. We are still that church.', quote: 'Come to me, all you who are weary and burdened, and I will give you rest.', by: 'Matthew 11:28' },
give: 'Giving is simple: by EFT or with a card at the welcome desk (demo details only: this is not a real account).',
ministries: [
['kids', 'Kids', 'Age groups up to grade 7, every Sunday.'],
['students', 'Students', 'University and college students, Sunday evenings.'],
['music', 'Music', 'A small band leading simple, honest worship.'],
['alpha', 'Alpha', 'Ten weeks, a meal and a conversation about life and faith.'],
],
leaders: [['Daniel Joubert', 'Pastor'], ['Refilwe Mokoena', 'Kids'], ['Sam Abrahams', 'Music'], ['Nadia Govender', 'Alpha']],
series: ['questions', 'Questions'],
messages: [['why-suffering', 'Why is there suffering?', 3, 'Romans 8:18-28'], ['can-i-trust-the-bible', 'Can I trust the Bible?', 10, '2 Timothy 3:14-17'], ['who-is-jesus', 'Who is Jesus?', 17, 'Mark 8:27-30']],
events: [
['alpha-starts', 'Alpha starts', 9, 'Ten Thursday evenings with dinner. Ask anything.'],
['carols-and-coffee', 'Carols and coffee', 18, 'A short carol service and a coffee cart.'],
['christmas-day', 'Christmas Day', 28, 'One family service at 09:00, about 45 minutes.'],
],
venue: '{name}',
},
'clean-campus': {
id: 'clean-campus', template: 'clean', label: 'Clean: a church near the university', alternate: true,
hero: { headline: 'Students, staff and neighbours', subline: 'A church across the road from campus in {city}. Sunday evenings, with supper.', button: { label: 'First time?', href: '/visit' } },
serviceNote: 'Evening service with free supper afterwards during term.',
welcome: {
heading: 'Welcome to {short}', mission: 'Thinking hard, loving well, following Jesus.',
body: 'Most of us are students or work at the university, and plenty of us live in the streets around it. We meet on Sunday evenings, eat together, and spend the week in small groups across campus.',
quote: 'University is where you ask the big questions. Church is a good place to ask them out loud.',
},
ministriesIntro: 'Find your people.',
teamIntro: 'The staff team.',
invitation: { heading: 'Supper is on us', text: 'Every Sunday in term, after the evening service.', button: { label: 'Come for supper', href: '/visit' } },
visit: {
expect: 'The evening service has songs, a Bible talk and prayer, and ends with supper in the hall. It lasts about an hour before the food.',
kids: 'Staff and neighbours with children: there is a morning family service on the first Sunday of the month.',
cta: 'New to the city? We would love to help you settle in.',
},
about: { story: '{short} started as a student Bible study in a residence common room. It grew into a church for the whole campus community and the neighbourhood around it.', quote: 'Love the Lord your God with all your heart and with all your soul and with all your mind.', by: 'Matthew 22:37' },
give: 'If you are a student, please don\'t worry about giving. If you can, your gifts fund supper every Sunday (demo details only: this is not a real account).',
ministries: [
['families', 'Families', 'A monthly family service for staff and neighbours with children.'],
['res-groups', 'Residence groups', 'Bible studies in every residence, weeknights.'],
['music', 'Music', 'Student musicians lead the evening service.'],
['international', 'International students', 'A welcome, a meal and help settling in.'],
],
leaders: [['Dr Ian Mabaso', 'Pastor'], ['Lisa Roberts', 'Student worker'], ['Thabo Nkosi', 'Music'], ['Priya Singh', 'International students']],
series: ['big-questions', 'Big questions'],
messages: [['what-is-truth', 'What is truth?', 4, 'John 18:37-38'], ['does-god-care', 'Does God care?', 11, 'Psalm 139'], ['what-makes-a-good-life', 'What makes a good life?', 18, 'Micah 6:8']],
events: [
['exam-prayer', 'Exam prayer and pizza', 3, 'A break from studying: prayer, pizza and encouragement.'],
['end-of-term-dinner', 'End of term dinner', 12, 'A three-course dinner to celebrate the end of term.'],
['carols-on-campus', 'Carols on campus', 19, 'Carols on the library lawn for students who are still here.'],
],
venue: '{name}',
},
};
/** The profiles in the contracts' order (what the Hub offers). */
export const demoSeeds = (): DemoSeed[] => agent.WEBSITE_DEMO_PROFILES.map((id: WebsiteDemoProfile) => DEMO_SEEDS[id]);
@@ -0,0 +1,72 @@
/**
* The Website's part of a church's export when it leaves (`crosscode export` / uninstall,
* WEBSITE-1.0-PLAN §11): `crosscode.church-export/1` with its `website` part, in plain terms and
* our own field names (no table names or internal ids; records refer to each other by refs made
* for the export). The uploads are copied next to it by the crosscode script (`uploads/`).
*
* The content is the working copy, including changes not yet published, as the admins left it.
*/
import { churchExportSchema, type ChurchExport, type ExportWebsite, type WebsiteTemplate, WEBSITE_TEMPLATES } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { appVersion } from '../lib/version.js';
const iso = (d: Date | null | undefined) => (d ? d.toISOString() : null);
const uploadPath = (filename: string) => `uploads/${filename.replace(/[^A-Za-z0-9._/-]/g, '-')}`;
const ROLE_NAMES: Record<string, string> = { owner: 'website owner', admin: 'website admin', editor: 'website editor', ministry_leader: 'ministry leader', viewer: 'website viewer' };
export async function buildExport(ctx: Ctx): Promise<ChurchExport> {
const db = ctx.db;
const [design, pages, messages, events, versions, media, users] = await Promise.all([
db.siteDesign.findUnique({ where: { id: 1 } }),
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
db.message.findMany({ orderBy: { date: 'asc' }, include: { series: true } }),
db.simpleEvent.findMany({ orderBy: { startsAt: 'asc' } }),
db.siteVersion.findMany({ orderBy: { number: 'asc' } }),
db.mediaAsset.findMany({ orderBy: { createdAt: 'asc' } }),
db.websiteUser.findMany({ orderBy: { name: 'asc' } }),
]);
const mediaPath = new Map(media.map((m) => [m.id, uploadPath(m.filename)]));
const names = new Map(users.map((u) => [u.id, u.name]));
const template: WebsiteTemplate = (WEBSITE_TEMPLATES as readonly string[]).includes(design?.template ?? '') ? (design!.template as WebsiteTemplate) : 'heritage';
const website: ExportWebsite = {
template,
firstPublishedAt: iso(versions[0]?.publishedAt),
style: Object.fromEntries(Object.entries((design?.style ?? {}) as Record<string, unknown>).filter(([, v]) => typeof v === 'string')) as Record<string, string>,
pages: pages.map((p, n) => ({
ref: `g${n + 1}`,
title: p.title,
path: p.kind === 'home' ? '/' : `/${p.slug}`,
kind: p.kind,
inNavigation: p.inNav,
seo: { title: p.seoTitle, description: p.description },
sections: p.sections.map((s) => ({ type: s.type, variant: s.variant ?? '', hidden: s.hidden, content: (s.data ?? {}) as Record<string, never> })),
})),
messages: messages.map((m, n) => ({
ref: `m${n + 1}`, title: m.title, date: iso(m.date), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage, notes: m.notes,
url: m.mediaUrl, source: m.source === 'youtube_feed' ? 'youtube-feed' as const : 'manual' as const, hidden: m.hidden,
})),
events: events.map((e, n) => ({
ref: `w${n + 1}`, title: e.title, description: e.description, startsAt: iso(e.startsAt), endsAt: iso(e.endsAt), location: e.location,
link: e.link, image: e.imageId ? mediaPath.get(e.imageId) ?? null : null, published: e.publishedAt !== null,
})),
versions: versions.map((v) => ({ number: v.number, publishedAt: iso(v.publishedAt), by: names.get(v.publishedBy) ?? null, note: v.note })),
media: media.map((m) => ({ path: uploadPath(m.filename), alt: m.alt || null, caption: null })),
};
return churchExportSchema.parse({
schema: 'crosscode.church-export/1',
exportedAt: ctx.now().toISOString(),
product: 'website',
productVersion: appVersion(),
church: { name: (await ctx.settings.get('church_name')) || 'Church Website', timezone: ctx.config.timezone },
people: users.map((u, n) => ({
ref: `p${n + 1}`, name: u.name, email: u.email, phone: null, role: ROLE_NAMES[u.role] ?? u.role, createdAt: iso(u.createdAt),
consent: { email: null, whatsapp: null, privacyNoticeAcceptedAt: null },
})),
events: [], registrations: [], payments: [], checkIns: [], rosters: [],
settings: { address: ctx.config.publicUrl },
files: media.map((m) => ({ path: uploadPath(m.filename), bytes: m.bytes })),
website,
});
}
+163
View File
@@ -0,0 +1,163 @@
/**
* The event feed (WEBSITE-1.0-PLAN §8, ROADMAP-v3 §4), both ways, as Cross Events 2.4:
*
* - **Publish my events** (AppSetting `feed_publish`, on by default): the Website's published simple
* events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in
* `deleted` for 90 days. Only events it made itself, never ones it imported (no loops).
* - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and
* at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch
* fails, one bad event skipped without holding up the rest, and only events that really come
* from that sibling.
* - Linked siblings are told (`event.changed`) when one of the Website's events changes.
*/
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from '../links/http.js';
import { imageOf } from '../site/snapshot.js';
const DAY = 864e5;
export const ENDED_KEEP_DAYS = 30;
export const REMOVED_KEEP_DAYS = 90;
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
const OVERLAP_MS = 5 * 60 * 1000;
export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true);
type SimpleRow = {
id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null;
description: string | null; imageId: string | null; link: string | null; cancelled: boolean; updatedAt: Date;
};
/** One of the Website's simple events as `crosscode.event/1`. */
export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string, imageUrl: string | null): CrosscodeEvent {
const url = `${ctx.config.publicUrl}/events/${e.slug}`;
const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3));
return {
schema: EVENT_SCHEMA,
id: e.id,
origin: { product: 'website', installId, url },
status: e.cancelled ? 'cancelled' : 'published',
updatedAt: e.updatedAt.toISOString(),
title: e.title.slice(0, 200),
summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null,
description: e.description,
imageUrl,
timezone: e.timezone,
startsAt: e.startsAt.toISOString(),
endsAt: ends.toISOString(),
allDay: e.allDay,
sessions: [],
location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null,
campus: null,
series: null,
tags: [],
// Only Cross Events takes registrations: a link, or nothing (roadmap decision 4).
registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null },
} as CrosscodeEvent;
}
/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */
export async function buildFeed(ctx: Ctx, since: Date | null): Promise<EventFeed> {
const now = ctx.now();
const installId = (await ctx.settings.get('hub_install_id'))!;
const [rows, media, removals] = await Promise.all([
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }),
ctx.db.mediaAsset.findMany(),
ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }),
]);
const byId = new Map(media.map((m) => [m.id, m]));
const events: CrosscodeEvent[] = [];
for (const row of rows) {
const ends = row.endsAt ?? row.startsAt;
if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue;
if (since && row.updatedAt <= since) continue;
const m = row.imageId ? byId.get(row.imageId) : null;
const e = toCrosscodeEvent(ctx, row, installId, m ? `${ctx.config.publicUrl}${imageOf(m).url}` : null);
// Never publish something the contract refuses.
if (eventSchema.safeParse(e).success) events.push(e);
}
return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) };
}
/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */
export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) {
if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } });
else await ctx.db.feedRemoval.deleteMany({ where: { eventId } });
}
/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */
export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> {
if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 };
const senderId = await ctx.settings.get('hub_install_id');
if (!senderId) return { told: 0, failed: 0 };
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) };
const raw = JSON.stringify(body);
let told = 0;
let failed = 0;
await Promise.all(links.map(async (link) => {
try {
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw });
await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
told++;
} catch (e) {
failed++;
console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message);
}
}));
return { told, failed };
}
type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
/** Fetches one sibling's feed into read-only copies. */
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
if (!link.showEvents) {
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
}
const now = ctx.now();
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
if (since) url.searchParams.set('updatedSince', since.toISOString());
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1 (${parsed.error.issues.slice(0, 2).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')})`);
const { feed, rejected } = parsed;
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`})`);
// Only events that really come from this sibling: one product can't speak for another.
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
for (const e of theirs) {
const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now };
const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } });
if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data });
else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } });
}
let deleted = 0;
for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count;
// A full fetch is the whole list: anything not in it is gone.
if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count;
await ctx.db.productLink.update({
where: { installId: link.installId },
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
});
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length };
} catch (e) {
const error = String((e as Error)?.message || e).slice(0, 500);
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
return { installId: link.installId, ok: false, error };
}
}
/** Every linked sibling, one after another; one failing never stops the rest. */
export async function syncAll(ctx: Ctx) {
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
let failed = 0;
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
return { links: links.length, failed };
}
+48
View File
@@ -0,0 +1,48 @@
/**
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
*/
import type { Request, RequestHandler, Response } from 'express';
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
super(message);
}
}
/** Known errors carry a status and code; anything else is a 500. */
export function sendError(res: Response, e: unknown) {
if (e instanceof ApiError) {
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
}
console.error('[api]', e);
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
}
/** A handler whose result is sent as JSON; an error (thrown or rejected) as `{ error }`. */
export const handle = (fn: (req: Request, res: Response) => unknown): RequestHandler => (req, res) => {
Promise.resolve().then(() => fn(req, res)).then((out) => {
if (out !== undefined && !res.headersSent) res.json(out);
}).catch((e) => sendError(res, e));
};
/**
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address, as
* Accounts' http.ts. With SameSite=Lax cookies this stops another site posting on someone's behalf.
*/
export function sameOrigin(publicUrl: string, production: boolean): RequestHandler {
const own = new URL(publicUrl).origin;
return (req, res, next) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
let origin = req.get('origin') ?? null;
if (!origin && req.get('referer')) {
try {
origin = new URL(req.get('referer')!).origin;
} catch {
origin = null;
}
}
if (origin === own || (!production && origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))) return next();
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
};
}
+210
View File
@@ -0,0 +1,210 @@
/**
* The Website and the Hub (docs/hub-protocol.md §6, protocol v2, product `website`), as Accounts'
* hub/client.ts: register with a `CCW-` licence key (by itself from HUB_LICENCE_KEY on a Hub
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
* `linkedProducts` (the church's other installs) is cached for Connect, and the Website connects
* itself to the church's Accounts once the Hub lists it (links/connect.ts).
*
* The install id the Hub gives is also this site's OIDC client id at Accounts.
*/
import crypto from 'node:crypto';
import { hub } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { appVersion } from '../lib/version.js';
import { connectAccountsIfListed } from '../links/connect.js';
import { keyPair, saveLinkedProducts } from '../links/store.js';
import { hubPublicKey, verifyToken } from './licence.js';
import { storage } from '../admin/media.js';
import { lastBackupAt } from '../backups/backups.js';
import { jobsHealth } from '../jobs.js';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
const DAY = 24 * 60 * 60 * 1000;
const STARTED_AT = Date.now();
/** 5 GB included (ROADMAP-v3 §10); the licence's `limits.storageBytes` says more when steps were bought. */
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
export class HubError extends Error {
constructor(message: string, public code: string, public status: number) {
super(message);
}
}
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
const raw = JSON.stringify(body);
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (sign) {
const timestamp = ctx.now().toISOString();
headers['X-Hub-Install'] = sign.installId;
headers['X-Hub-Timestamp'] = timestamp;
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
}
let res: Response;
try {
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (e) {
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
}
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
return data;
}
export async function dbUp(ctx: Ctx): Promise<boolean> {
try {
await ctx.db.$queryRaw`SELECT 1`;
return true;
} catch {
return false;
}
}
export async function health(ctx: Ctx) {
return {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db: await dbUp(ctx),
// 1.4.0: the real job mode and failures, and the newest backup (before: always null, so the
// Hub warned "No backup reported").
jobs: await jobsHealth(ctx),
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
disk: null,
errorsLast24h: null,
pendingMigrations: 0,
};
}
/** Aggregate counts only (hub.websiteStatsSchema): never anyone's details. */
export async function stats(ctx: Ctx) {
const now = ctx.now();
const since = new Date(now.getTime() - 30 * DAY);
const [published, drafts, total, last30d, upcomingSimple, imported, editors, media] = await Promise.all([
ctx.db.siteVersion.count(),
ctx.db.page.count({ where: { archivedAt: null } }),
ctx.db.message.count({ where: { hidden: false } }),
ctx.db.message.count({ where: { hidden: false, date: { gte: since } } }),
ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }),
ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }),
ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }),
storage(ctx),
]);
return {
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
pages: { published: published > 0 ? drafts : 0, drafts: published > 0 ? 0 : drafts },
messages: { total, last30d },
events: { upcomingSimple, imported },
editors,
// The limit the licence gives (5 GB plus steps bought): the Hub emails the church's admin at
// 80% and 100% (decision 12).
storage: { usedBytes: media.usedBytes, includedBytes: media.limitBytes },
};
}
/** Register with a licence key (HUB_LICENCE_KEY). */
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('WEBSITE_URL isn\'t set.', 'NO_SITE_URL', 400);
const { publicKeyPem } = await keyPair(ctx);
const body = {
protocolVersion: PROTOCOL_VERSION,
licenceKey: licenceKey.trim().toUpperCase(),
product: 'website',
install: {
name: 'Website',
url: ctx.config.publicUrl,
adminContact,
version: appVersion(),
timezone: ctx.config.timezone,
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
features: {},
publicKey: publicKeyPem,
},
};
const check = hub.registerRequestSchema.safeParse(body);
if (!check.success) throw new HubError('That doesn\'t look like a Website licence key (CCW-…).', 'INVALID_REQUEST', 400);
const data = await post(ctx, '/api/installs/register', check.data);
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
await ctx.settings.setMany({
hub_install_id: String(data.installId),
hub_install_secret: String(data.installSecret),
hub_licence: String(data.licence),
hub_last_heartbeat_at: ctx.now().toISOString(),
hub_last_error: null,
hub_public_key_status: 'matches',
});
await saveLinkedProducts(ctx, data.linkedProducts);
await connectAccountsIfListed(ctx);
return claims;
}
/** The heartbeat (every 15 minutes). Skips quietly when not connected. */
export async function heartbeat(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
const secret = await ctx.settings.get('hub_install_secret');
if (!installId || !secret) return { skipped: 'not connected' };
const status = await ctx.settings.get('hub_public_key_status');
const { publicKeyPem } = await keyPair(ctx);
const body = {
protocolVersion: PROTOCOL_VERSION,
product: 'website',
version: appVersion(),
health: await health(ctx),
stats: await stats(ctx),
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
};
try {
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
await ctx.settings.setMany({
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
hub_last_heartbeat_at: ctx.now().toISOString(),
hub_last_error: null,
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
});
await saveLinkedProducts(ctx, data.linkedProducts);
await connectAccountsIfListed(ctx);
return { ok: true };
} catch (e) {
const err = e as HubError;
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
if (err.code === 'INSTALL_NOT_FOUND') {
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
return { ok: false, reconnect: true };
}
throw e;
}
}
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
const key = ctx.config.hubLicenceKey;
if (!key) return { connected: false, reason: 'no_key' };
for (let i = 1; i <= attempts; i++) {
try {
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
return { connected: true };
} catch (e) {
const err = e as HubError;
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
}
}
return { connected: false, reason: 'unreachable' };
}
/**
* "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more
* 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer.
*/
export async function requestStorage(ctx: Ctx, steps: number, requestedBy: string | null, now: { usedBytes: number; limitBytes: number }) {
const installId = await ctx.settings.get('hub_install_id');
const secret = await ctx.settings.get('hub_install_secret');
if (!installId || !secret) throw new HubError('This site isn\'t connected to the Hub yet, so it can\'t ask for more storage.', 'NOT_CONNECTED', 503);
const body = hub.storageRequestSchema.parse({ protocolVersion: PROTOCOL_VERSION, steps, usedBytes: now.usedBytes, limitBytes: now.limitBytes, requestedBy });
const data = await post(ctx, '/api/installs/storage-request', body, { installId, secret });
const reply = hub.storageRequestResponseSchema.safeParse(data);
if (!reply.success) throw new HubError('The Hub answered in a way this site doesn\'t understand.', 'BAD_REPLY', 502);
return reply.data;
}
+69
View File
@@ -0,0 +1,69 @@
/**
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
* key, as Cross Events does. A lapsed licence never takes the public site down (the Hub is never on the runtime path,
* ROADMAP-v3 §1): admins see a banner.
*/
import crypto from 'node:crypto';
import type { Ctx } from '../context.js';
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
const DAY = 24 * 60 * 60 * 1000;
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
export function normalisePem(input: string | null | undefined): string | null {
const text = String(input || '').replace(/\\n/g, '\n').trim();
if (!text) return null;
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
}
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
}
export type LicenceClaims = {
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
};
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
if (!pem) return null;
const parts = String(token || '').split('.');
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
try {
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
} catch {
return null;
}
}
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
/** The state for verified claims. Pure. */
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
return { state: 'lapsed', endsAt, daysLeft: null };
}
export async function licenceStatus(ctx: Ctx) {
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
const claims = verifyToken(token, hubPublicKey(ctx));
const valid = claims && claims.installId === installId ? claims : null;
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
}
/** The church's Hub customer id (the same for every product), once the licence says it. */
export async function customerId(ctx: Ctx): Promise<string | null> {
return (await licenceStatus(ctx)).claims?.customerId ?? null;
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
* with the Hub from HUB_LICENCE_KEY, then the background jobs (src/jobs.ts, 1.4.0): heartbeats,
* which also link the site to the church's Accounts once the Hub lists it, the event feed, the
* hourly YouTube feed (§7) and the nightly database backup.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.js';
import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat } from './hub/client.js';
import { startJobs } from './jobs.js';
import { loadConfig } from './lib/config.js';
import { ensureStarterPages } from './site/starter.js';
async function main() {
const config = loadConfig();
const url = process.env.DATABASE_URL;
if (!url) throw new Error('DATABASE_URL isn\'t set.');
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
const ctx = createCtx(config, db);
// A new install's fixed pages (home, Plan your visit, …), before anything is served.
await ensureStarterPages(ctx)
.then((kinds) => { if (kinds.length) console.log(`[website] Added the starter pages: ${kinds.join(', ')}.`); })
.catch((e) => console.error('[website] Couldn\'t add the starter pages:', (e as Error).message));
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
// 1.4.0: the heartbeat, the event feed, YouTube and the nightly backup, on pg-boss.
const stopJobs = await startJobs(ctx, url);
connectFromEnv(ctx).then((r) => {
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
await stopJobs();
server.close();
await db.$disconnect();
process.exit(0);
};
process.on('SIGTERM', stop);
process.on('SIGINT', stop);
}
main().catch((e) => {
console.error('[website] Failed to start:', e);
process.exit(1);
});
+306
View File
@@ -0,0 +1,306 @@
/**
* Background jobs on pg-boss (1.4.0, as Accounts and 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. Before 1.4.0 the heartbeat, the event feed and YouTube were plain timers.
*
* 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';
import { syncAll } from './feed/feed.js';
import { heartbeat } from './hub/client.js';
import { syncYoutube } from './site/youtube.js';
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
// A database backup every night (Settings → Backups), after Accounts' at 02:00 on the same server.
{ name: 'backup', label: 'Database backup', cron: '20 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) },
// ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback".
{ name: 'event-feed', label: 'Events from the church\'s other sites (Cross Events)', cron: '*/15 * * * *', env: 'FEED_JOB_ENABLED', run: (ctx) => syncAll(ctx) },
{ name: 'youtube', label: 'Messages: new videos from the church\'s YouTube channel', cron: '7 * * * *', env: 'YOUTUBE_JOB_ENABLED', run: (ctx) => syncYoutube(ctx) },
];
const SCHEMA = 'pgboss_website';
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 {
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-website-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) ?? [],
};
}),
};
}
/** What the Hub's heartbeat reports (hub.healthSchema `jobs`): the real mode and failed runs in 24 hours. */
export async function jobsHealth(ctx: Ctx): Promise<{ mode: 'queue' | 'timers' | 'off'; failedLast24h: number }> {
const since = ctx.now().getTime() - 24 * 3600e3;
if (state.mode === 'queue') {
try {
const rows = await ctx.db.$queryRawUnsafe<{ n: number | bigint }[]>(
`SELECT count(*)::int AS n FROM ${SCHEMA}.job WHERE state = 'failed' AND name = ANY($1::text[]) AND completed_on > now() - interval '24 hours'`,
JOBS.map((j) => j.name),
);
return { mode: 'queue', failedLast24h: Number(rows[0]?.n ?? 0) };
} catch {
return { mode: 'queue', failedLast24h: 0 };
}
}
let failed = 0;
for (const runs of state.history.values()) failed += runs.filter((r) => r.state === 'failed' && (r.completedOn?.getTime() ?? 0) > since).length;
return { mode: state.mode, failedLast24h: failed };
}
+19
View File
@@ -0,0 +1,19 @@
/**
* The admin audit log (who changed what, WEBSITE-1.0-PLAN §4). Logging never breaks the
* action it records.
*/
import type { Request } from 'express';
import type { Ctx } from '../context.js';
export function clientIp(req: Request | undefined): string | null {
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
}
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
try {
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
} catch (e) {
console.error('[audit]', (e as Error).message);
}
}
+72
View File
@@ -0,0 +1,72 @@
/**
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
* tests pass their own with `loadConfig({...})`.
*/
export type TrustProxy = false | number | string | string[];
export type Config = {
/** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */
publicUrl: string;
port: number;
/** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */
secret: string;
production: boolean;
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
trustProxySetting: TrustProxy;
hubUrl: string;
hubLicenceKey: string | null;
hubPublicKey: string | null;
/** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */
hubAdminName: string | null;
hubAdminEmail: string | null;
timezone: string;
jobsEnabled: boolean;
/** Where uploads go; default backend/uploads. */
uploadDir: string | null;
/** Local testing only: linked products (Accounts) on http or private addresses. */
allowPrivateLinks: boolean;
/** How long an admin stays signed in (days). */
sessionDays: number;
/** 1.4.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */
databaseUrl: string | null;
/** 1.4.0: where backups go; default backend/backups (tests use their own folder). */
backupDir: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
const raw = (v ?? '').trim();
if (raw === '') return production ? 1 : false;
const lower = raw.toLowerCase();
if (lower === 'true') return 1;
if (lower === 'false') return false;
if (/^\d+$/.test(raw)) return Number(raw) || false;
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
}
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
const production = env.NODE_ENV === 'production';
const secret = env.WEBSITE_SECRET || '';
if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.');
return {
publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''),
port: Number(env.PORT || 5300),
secret: secret || 'development-only-secret-change-me-0123456789',
production,
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null,
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
jobsEnabled: bool(env.JOBS_ENABLED, true),
uploadDir: env.UPLOAD_DIR?.trim() || null,
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)),
databaseUrl: env.DATABASE_URL?.trim() || null,
backupDir: null,
};
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Secrets at rest (AES-256-GCM, as Accounts' lib/crypto.ts), and tokens. The key comes from
* WEBSITE_SECRET; encrypted values start with "enc:".
*/
import crypto from 'node:crypto';
const SENTINEL = 'enc:';
export class Secrets {
private readonly key: Buffer;
constructor(secret: string) {
this.key = crypto.scryptSync(secret, 'crosscode-website-aes256gcm-v1', 32);
}
encrypt(plain: string): string {
if (plain.startsWith(SENTINEL)) return plain;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
}
/** Throws if the value was changed or encrypted with another key. */
decrypt(value: string): string {
if (!value.startsWith(SENTINEL)) return value;
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
decipher.setAuthTag(Buffer.from(tag, 'hex'));
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
}
}
/** A random token for a cookie (32 bytes, base64url). */
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
/** What's stored for a token: only its SHA-256. */
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
+64
View File
@@ -0,0 +1,64 @@
/**
* Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are
* encrypted at rest and never sent to the browser. A short cache keeps pages from reading the
* table on every request.
*/
import type { Ctx } from '../context.js';
export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']);
const TTL_MS = 30_000;
export class Settings {
private cache = new Map<string, { value: string | null; at: number }>();
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
async get(key: string): Promise<string | null> {
const hit = this.cache.get(key);
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
let value = row?.value ?? null;
if (value !== null && SECRET_SETTINGS.has(key)) {
try {
value = this.ctx.secrets.decrypt(value);
} catch {
value = null;
}
}
this.cache.set(key, { value, at: Date.now() });
return value;
}
async bool(key: string, fallback: boolean): Promise<boolean> {
const v = await this.get(key);
return v === null || v === '' ? fallback : v === 'true';
}
async json<T>(key: string, fallback: T): Promise<T> {
const v = await this.get(key);
if (!v) return fallback;
try {
return JSON.parse(v) as T;
} catch {
return fallback;
}
}
async set(key: string, value: string | null): Promise<void> {
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
else {
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
}
this.cache.delete(key);
}
async setMany(values: Record<string, string | null>): Promise<void> {
for (const [k, v] of Object.entries(values)) await this.set(k, v);
}
forget(): void {
this.cache.clear();
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
* however the process was started (PM2 doesn't set npm_package_version).
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
let cached: string | null = null;
export function appVersion(): string {
if (!cached) {
try {
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
} catch {
cached = '0.0.0';
}
}
return cached;
}
+222
View File
@@ -0,0 +1,222 @@
/**
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4 and Accounts). The Website links
* to the church's **Accounts** (signing in: the link's secret is where the client secret comes
* from, and Accounts registers this site as an OIDC client when it accepts) and, for the event
* feed, to **Events** and later the **App**.
*
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in this
* site's cached `linkedProducts` (same church), signed with the key the Hub listed for it.
*/
import {
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
} from '@crosscode/contracts';
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, linkedProducts, listedProduct } from './store.js';
export class LinkError extends Error {
constructor(message: string, public code: string, public status = 400) {
super(message);
}
}
/** The products the Website links to. */
const LINKABLE = new Set(['accounts', 'events', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const SIGN_IN_TRY_EVERY_MS = 15 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.0.2: a fresh list of the church's products from the Hub (a heartbeat), at most once a minute,
* so a message from an unknown install can't make the Website call the Hub more often than that.
* Several callers inside that minute share one heartbeat. Never throws.
*/
async function refreshList(ctx: Ctx): Promise<void> {
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
// Imported here: hub/client.ts imports this file (it links to Accounts after each heartbeat).
r = { at: now, run: import('../hub/client.js').then((m) => m.heartbeat(ctx)).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
}
/**
* 1.0.2: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat), the Website asks the Hub for a fresh list and looks again.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
await refreshList(ctx);
return listedProduct(ctx, installId);
}
type Actor = { id: string | null; role: string };
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
if (!installId) throw new LinkError('The Website isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
const { privateKeyPem } = await keyPair(ctx);
return { installId, url: ctx.config.publicUrl, privateKeyPem };
}
const party = (s: { installId: string; url: string }) => ({ product: 'website' as const, installId: s.installId, url: s.url });
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
const now = ctx.now();
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
try {
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
return true;
} catch (e) {
if ((e as { code?: string }).code === 'P2002') return false;
throw e;
}
}
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null };
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
}
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) =>
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
}, me.privateKeyPem);
let reply: unknown;
try {
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
} catch (e) {
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
throw e;
}
const parsed = linkConnectedSchema.safeParse(reply);
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
const r: LinkConnected = parsed.data;
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() }).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
}
const link = await saveLink(ctx, sibling, secret, actor.id);
await logLink(ctx, 'product_link_connected', link, actor, req, 'website');
return link;
}
/** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
const parsed = linkConnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.product)) {
throw new LinkError('The Hub doesn\'t list that install for this church (the Website asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
const link = await saveLink(ctx, sibling, m.secret, null);
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
return signLink<Omit<LinkConnected, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
}, me.privateKeyPem);
}
/** This site ends a link. The local link goes even if the sibling can't be reached. */
export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
const link = await ctx.db.productLink.findUnique({ where: { installId } });
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
let told = false;
let problem: string | null = null;
try {
const me = await self(ctx);
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
told = true;
} catch (e) {
problem = (e as Error).message;
}
await ctx.db.productLink.delete({ where: { installId } });
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'website');
return { told, problem };
}
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
const parsed = linkDisconnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
if (!link) return;
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
await ctx.db.productLink.delete({ where: { installId: link.installId } });
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
}
/**
* The Website signs in through Accounts, so it connects to the church's Accounts by itself once the
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
* Never throws: a failure is tried again at the next heartbeat.
*/
export function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
// 1.0.2: one connect at a time (a heartbeat and a sign-in can both try): two at once would each
// send Accounts a different secret, and the one each side kept last might not be the same.
let run = connecting.get(ctx);
if (!run) {
run = connectAccountsOnce(ctx).finally(() => connecting.delete(ctx));
connecting.set(ctx, run);
}
return run;
}
const connecting = new WeakMap<Ctx, Promise<'connected' | 'skipped' | 'failed'>>();
async function connectAccountsOnce(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
if (!listed) return 'skipped';
try {
await connectTo(ctx, listed.installId, { id: null, role: 'system' });
return 'connected';
} catch (e) {
console.warn('[links] Connecting to Accounts failed:', (e as Error).message);
return 'failed';
}
}
const signInTries = new WeakMap<Ctx, number>();
/**
* 1.0.2: someone wants to sign in and there's no link to Accounts yet: link now instead of waiting
* for the next heartbeat. If the cached list has no Accounts, the Hub is asked for a fresh one first
* (which links by itself when it lists one). Tried at most every 15 seconds, so visitors opening
* /admin can't make the Website call Accounts or the Hub more often than that.
*/
export async function linkAccountsNow(ctx: Ctx): Promise<void> {
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return;
const now = ctx.now().getTime();
const last = signInTries.get(ctx);
if (last !== undefined && now - last < SIGN_IN_TRY_EVERY_MS) return;
signInTries.set(ctx, now);
if (!(await linkedProducts(ctx)).some((p) => p.product === 'accounts')) await refreshList(ctx);
await connectAccountsIfListed(ctx);
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
*/
import dns from 'node:dns/promises';
import net from 'node:net';
import type { Ctx } from '../context.js';
const TIMEOUT_MS = 15000;
const MAX_BYTES = 5 * 1024 * 1024;
export class LinkCallError extends Error {
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
super(message);
}
}
export function isPrivateAddress(ip: string): boolean {
if (net.isIPv4(ip)) {
const [a, b] = ip.split('.').map(Number) as [number, number];
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
}
if (net.isIPv6(ip)) {
const v = ip.toLowerCase();
if (v === '::1' || v === '::') return true;
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
if (mapped) return isPrivateAddress(mapped[1]!);
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
}
return true;
}
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
let url: URL;
try {
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
} catch {
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
}
const allow = ctx.config.allowPrivateLinks;
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
if (!allow) {
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
}
return url;
}
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
let res: Response;
try {
res = await fetch(url, {
method: init.method,
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
body: init.body,
redirect: 'manual',
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (e) {
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
}
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
const text = await res.text();
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
let data: unknown = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
}
if (!res.ok) {
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
}
return data;
}
+108
View File
@@ -0,0 +1,108 @@
/**
* What the church's other products call (`crosscode.link/1` and friends), as Cross Events'
* cross-product routes. Errors use the link protocol's `{ code, message }`.
*
* POST /links/v1/connect, /disconnect a sibling connects or disconnects
* GET /feed/v1/events?updatedSince= the Website's events (crosscode.event-feed/1), public
* POST /feed/v1/changed a sibling's events changed: fetch them now (signed)
* POST /church/v1/changed Accounts: the church profile changed (signed)
*/
import express from 'express';
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { churchChanged } from '../church/profile.js';
import { buildFeed, publishOn, syncLink } from '../feed/feed.js';
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
export function linksRouter(ctx: Ctx) {
const r = express.Router();
const json = express.json({ limit: '32kb' });
const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message });
const fail = (res: express.Response, e: unknown) => {
if (e instanceof LinkError) return say(res, e.status, e.code, e.message);
console.error('[links]', e);
return say(res, 500, 'INTERNAL', 'Something went wrong.');
};
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
try {
res.json(await acceptConnect(ctx, req.body, req));
} catch (e) {
fail(res, e);
}
});
r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => {
try {
await acceptDisconnect(ctx, req.body, req);
res.json({ ok: true });
} catch (e) {
fail(res, e);
}
});
r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => {
try {
if (!(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events.');
if (!(await ctx.settings.get('hub_install_id'))) return say(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
const since = raw ? new Date(raw) : null;
if (raw && (!since || !Number.isFinite(since.getTime()))) return say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
res.set('Cache-Control', 'no-store');
return res.json(await buildFeed(ctx, since));
} catch (e) {
return fail(res, e);
}
});
/** A signed message from a linked sibling: its link, or the reason it's refused. */
async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link || (accountsOnly && link.product !== 'accounts')) {
say(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
return null;
}
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() });
if (!check.ok) {
say(res, 401, check.code, 'The signature doesn\'t match this link.');
return null;
}
let body: unknown;
try {
body = JSON.parse(rawBody.toString('utf8'));
} catch {
body = null;
}
return { link, body };
}
const raw = express.raw({ type: () => true, limit: '16kb' });
r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res);
if (!got) return undefined;
if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
// Fetched after answering: the sibling doesn't wait for it.
if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); });
return res.status(202).json({ accepted: true, fetching: got.link.showEvents });
} catch (e) {
return fail(res, e);
}
});
r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res, true);
if (!got) return undefined;
if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.');
churchChanged(ctx);
return res.status(202).json({ accepted: true });
} catch (e) {
return fail(res, e);
}
});
return r;
}
+34
View File
@@ -0,0 +1,34 @@
/**
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
* hub_linked_products.
*/
import { hub } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
type LinkedProduct = hub.LinkedProduct;
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
const pair = generateEd25519();
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
}
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
}
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
if (!Array.isArray(list)) return;
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
}
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
}
+183
View File
@@ -0,0 +1,183 @@
/**
* Everything the public site needs to draw a page (WEBSITE-1.0-PLAN §1): the latest published
* snapshot, the church profile from Accounts, the colours made safe, the fonts and corners, and
* the messages and events (which publish on their own, so they're read live). Before the first
* publish: Coming soon, from the profile alone (§5).
*/
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { buildSnapshot, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
title: string;
summary: string | null;
startsAt: string;
endsAt: string | null;
allDay: boolean;
location: string | null;
image: Image | null;
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
url: string;
/** The Website's own events: their page here is /events/<slug> (`url` may be their outside link). */
slug: string | null;
/** An outside link for more information or signing up (the Website's own events). */
link: string | null;
from: 'website' | 'events' | 'app';
registration: { status: string; priceFromCents: number | null } | null;
};
export type SiteMessage = {
slug: string;
title: string;
date: string;
speaker: string | null;
series: string | null;
passage: string | null;
source: 'youtube' | 'spotify';
/** For the embed (youtube-nocookie) or the Spotify player, loaded only when clicked. */
embedUrl: string | null;
url: string;
thumbnail: string | null;
};
type Common = {
church: Church | null;
palette: Palette;
/** The shared brand style, else what the template suggests (§3). */
style: { fontPairing: string; corners: string };
/** Search engines' verification codes, for the home page's meta tags (§11). */
verification: { google: string | null; bing: string | null };
/** 1.2.0: the site's own icon (Settings), else null: the church's icon, else one made for it. */
favicon: string | null;
};
export type SiteContent =
| (Common & { mode: 'coming-soon'; template: WebsiteTemplate; comingSoonText: string })
| (Common & {
mode: 'published';
version: number;
/** Without its `source` (the working copy's rows): visitors never get internal ids or hidden sections. */
snapshot: Omit<Snapshot, 'source'>;
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
transparentHeader: Record<string, boolean>;
messages: SiteMessage[];
events: SiteEvent[];
});
const DEFAULT_COLOUR = '#1f4e79';
function brandFor(church: Church | null, template: WebsiteTemplate) {
return {
palette: buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null),
style: {
fontPairing: church?.branding.style?.fontPairing ?? TEMPLATE_FONT_PAIRINGS[template][0],
corners: church?.branding.style?.corners ?? TEMPLATE_STYLE[template].suggestedCorners,
},
};
}
/** Where the site serves a YouTube video's thumbnail from (site/thumbnails.ts): visitors never ask YouTube. */
export const thumbnailPath = (videoId: string) => `/api/thumbnails/${videoId}.jpg`;
/** A message's thumbnail on the site: its YouTube video's, served from here; none for Spotify. */
export function messageThumbnail(m: { source: string; mediaUrl: string }) {
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
return yt ? thumbnailPath(yt) : null;
}
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
export function youtubeId(url: string): string | null {
try {
const u = new URL(url);
if (u.hostname === 'youtu.be') return u.pathname.slice(1) || null;
if (/(^|\.)youtube(-nocookie)?\.com$/.test(u.hostname)) return u.searchParams.get('v') ?? (/^\/(embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[2] ?? null);
} catch {
// Not a URL.
}
return null;
}
/** `https://open.spotify.com/episode/abc` → the embed address; null for anything else. */
export function spotifyEmbed(url: string): string | null {
const m = /^https:\/\/open\.spotify\.com\/(episode|show)\/([A-Za-z0-9]+)/.exec(url);
return m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : null;
}
async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
const rows = await ctx.db.message.findMany({ where: { hidden: false, publishedAt: { not: null } }, orderBy: { date: 'desc' }, take: 24, include: { series: true } });
return rows.map((m) => {
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
return {
slug: m.slug, title: m.title, date: m.date.toISOString(), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage,
source: m.source === 'spotify' ? 'spotify' : 'youtube',
embedUrl: yt ? `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1` : spotifyEmbed(m.mediaUrl),
url: m.mediaUrl,
thumbnail: messageThumbnail(m),
};
});
}
async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
const now = ctx.now();
const [simple, imported, media] = await Promise.all([
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, cancelled: false, OR: [{ startsAt: { gte: now } }, { endsAt: { gte: now } }] }, orderBy: { startsAt: 'asc' }, take: 50 }),
ctx.db.importedEvent.findMany({ where: { startsAt: { gte: new Date(now.getTime() - 7 * 864e5) } }, orderBy: { startsAt: 'asc' }, take: 50 }),
ctx.db.mediaAsset.findMany(),
]);
const image = (id: string | null) => {
const m = id ? media.find((x) => x.id === id) : null;
return m ? imageOf(m) : null;
};
const own: SiteEvent[] = simple.map((e) => ({
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
}));
const copies: SiteEvent[] = imported.flatMap((row) => {
const e = row.data as unknown as CrosscodeEvent;
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
return [{
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, slug: null, link: null, from: e.origin.product,
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
} satisfies SiteEvent];
});
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
}
/** What visitors see: the latest published version, else Coming soon. */
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
return contentFrom(ctx, church, published);
}
/** The preview (§4): the working copy as it would look published, whatever was published before. */
export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<SiteContent> {
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx, opts)]);
return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot });
}
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
const [google, bing, faviconId] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification'), ctx.settings.get('favicon_media_id')]);
const verification = { google: google || null, bing: bing || null };
const icon = faviconId ? await ctx.db.mediaAsset.findUnique({ where: { id: faviconId } }) : null;
const favicon = icon ? mediaUrl(icon.filename) : null;
if (!published) {
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
return {
mode: 'coming-soon', template, church, ...brandFor(church, template), verification, favicon,
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
const { source: _source, ...snapshot } = published.snapshot;
const template = snapshot.design.template;
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
}));
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, favicon, messages, events };
}
+95
View File
@@ -0,0 +1,95 @@
/**
* The site's colours from the church's two (WEBSITE-1.0-PLAN §3, "Colours from the church, made
* safe"): tints and shades, the text colour on each, all checked against WCAG AA (4.5:1 for text).
* A colour that fails is darkened (or lightened) until it passes, and the admin is told why.
*/
export type Rgb = [number, number, number];
const AA = 4.5;
const WHITE: Rgb = [255, 255, 255];
const INK: Rgb = [17, 24, 39];
export function hexToRgb(hex: string): Rgb {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
const n = parseInt(m ? m[1]! : '1f4e79', 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
function luminance([r, g, b]: Rgb): number {
const lin = (v: number) => {
const s = v / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}
export function contrast(a: Rgb, b: Rgb): number {
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
return (x + 0.05) / (y + 0.05);
}
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
for (let t = 0; t <= 1; t += 0.02) {
const d = mix(c, [0, 0, 0], t);
if (contrast(d, against) >= ratio) return d;
}
return [0, 0, 0];
}
export type Palette = {
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
brand: string;
brandDark: string;
onBrand: string;
/** The church's colour as text or a link on white: darkened when it's too light to read. */
brandText: string;
/** A soft background in the church's colour (Section colour "Tinted"). */
brandTint: string;
accent: string;
onAccent: string;
/** What was changed and why, for the admin (§3: "the admin is told why"). */
notes: string[];
};
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
const notes: string[] = [];
const primary = hexToRgb(primaryHex);
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
// background is darkened until white does.
let brand = primary;
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
if (!onBrand) {
brand = darkenUntil(primary, WHITE);
onBrand = WHITE;
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
}
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
return {
brand: triple(brand),
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
onBrand: triple(onBrand),
brandText: triple(brandTextRgb),
brandTint: triple(mix(primary, WHITE, 0.92)),
accent: triple(accent),
onAccent: triple(onAccent),
notes,
};
}
+68
View File
@@ -0,0 +1,68 @@
/**
* What an admin fills in for each homepage section (WEBSITE-1.0-PLAN §2: "every section stores its
* data, validated with a zod schema per section type"). Never tied to a template: every template
* draws every variant from the same data (§3). Lists (ministries, leaders, events, messages) come
* from their own tables; the section only holds its heading and intro.
*
* Images are media ids here; the published snapshot turns them into `{ url, alt }`.
*/
import { z } from 'zod';
import type { SectionType } from './variants.js';
const text = (max: number) => z.string().trim().max(max);
const optional = (max: number) => text(max).nullable().default(null);
const mediaId = z.string().uuid();
/** A link on the site (`/visit`) or elsewhere (https only). */
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
export const SECTION_SCHEMAS = {
hero: z.object({
headline: text(120).min(1),
subline: optional(300),
/** `photo` and `split` use the first; `collage` up to three. */
images: z.array(mediaId).max(3).default([]),
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
videoId: mediaId.nullable().default(null),
button,
}),
serviceTimes: z.object({
heading: optional(80),
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
note: optional(300),
}),
welcome: z.object({
heading: optional(120),
/** The mission line, above the introduction in every variant (§3). */
mission: optional(200),
body: text(4000).default(''),
imageId: mediaId.nullable().default(null),
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
}),
ministries: z.object({ heading: optional(80), intro: optional(400) }),
team: z.object({ heading: optional(80), intro: optional(400) }),
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
latestMessage: z.object({ heading: optional(80) }),
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
} as const satisfies Record<SectionType, z.ZodType>;
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
export const BLOCK_SCHEMAS = {
text: z.object({ heading: optional(120), body: text(20000) }),
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
} as const;
export type BlockType = keyof typeof BLOCK_SCHEMAS;
export const isBlockType = (t: string): t is BlockType => t in BLOCK_SCHEMAS;
/** A section's or block's data, checked; null when it doesn't fit (it's then left out, never shown broken). */
export function parseSectionData(type: string, data: unknown): Record<string, unknown> | null {
const schema = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
if (!schema) return null;
const r = schema.safeParse(data ?? {});
return r.success ? (r.data as Record<string, unknown>) : null;
}
+208
View File
@@ -0,0 +1,208 @@
/**
* Published versions (WEBSITE-1.0-PLAN §4): Publish copies the working copy into an immutable
* snapshot (`SiteVersion.snapshot`), and visitors always see the latest. The snapshot holds the
* site's design and every page with its sections, ministries and leaders, with images already
* turned into `{ url, alt }`, so showing the site never reads the working copy.
*
* Messages and simple events aren't in it: they publish on their own (decision 9) and are read
* live (content.ts).
*/
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1;
/** An image to show: the photo, and its responsive sizes as `srcset`s when it has them (§3). */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
export type SnapshotPage = {
kind: string;
slug: string;
/** `/` for home, else `/<slug>`. */
path: string;
title: string;
seoTitle: string | null;
description: string | null;
navLabel: string;
inNav: boolean;
image: Image | null;
sections: SnapshotSection[];
};
export type Snapshot = {
v: typeof SNAPSHOT_VERSION;
design: SiteDesign;
pages: SnapshotPage[];
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
/** Every image the sections refer to, by media id. */
media: Record<string, Image>;
/** Earlier page addresses (without the /) and the path each page has now: a permanent redirect. */
redirects: Record<string, string>;
/** The working copy's rows at publish time: Restore and Discard copy from here (§4). */
source: Source;
};
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
/** A media row as an Image, with `srcset`s from its sizes and the photo itself as the widest. */
export function imageOf(m: MediaRow): Image {
const img: Image = { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height };
const sizes = Array.isArray(m.sizes) ? (m.sizes as { w: number; webp: string; jpg: string }[]) : [];
if (sizes.length && m.width) {
const dir = m.filename.includes('/') ? m.filename.slice(0, m.filename.lastIndexOf('/') + 1) : '';
const set = (key: 'webp' | 'jpg') => [...sizes.map((x) => `${mediaUrl(dir + x[key])} ${x.w}w`), `${img.url} ${m.width}w`].join(', ');
img.srcset = { webp: set('webp'), jpg: set('jpg') };
}
return img;
}
/** The design as saved, made safe: an unknown template, variant or section falls back to the default. */
export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign {
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
const base = defaultDesign(template);
if (!saved) return base;
const variants = { ...base.variants } as Record<SectionType, string>;
const v = (saved.variants ?? {}) as Record<string, unknown>;
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
const home = Array.isArray(saved.home)
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
: base.home;
// Every section listed once: any missing one is added at the end, hidden.
for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
const style = { ...base.style, ...Object.fromEntries(Object.entries((saved.style ?? {}) as Record<string, unknown>).filter(([, x]) => typeof x === 'string')) };
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
}
/** The working copy's rows, as saved (the source of a snapshot, so a version can be restored, §4). */
export type Source = {
design: { template: string; variants: unknown; home: unknown; style: unknown } | null;
pages: {
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
inNav: boolean; position: number; imageId: string | null;
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
}[];
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
};
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
export async function readWorkingCopy(ctx: Ctx) {
const db = ctx.db;
const [design, pages, ministries, leaders] = await Promise.all([
db.siteDesign.findUnique({ where: { id: 1 } }),
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
]);
return { design, pages, ministries, leaders };
}
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
return {
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
pages: w.pages.map((p) => ({
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
position: p.position, imageId: p.imageId,
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
})),
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
};
}
/** The working copy as a snapshot (what Publish saves, and what the preview shows). */
export async function buildSnapshot(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<Snapshot> {
const [w, media, history] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany(), ctx.db.slugHistory.findMany()]);
const source = toSource(w);
// "Choose your template" (ROADMAP-v3 §6): the church's own content in another template, as a
// switch would make it, without saving anything.
if (opts.asTemplate) source.design = switchTemplate(cleanDesign(source.design), opts.asTemplate).design;
const snap = snapshotFrom(source, media);
const pathOf = new Map(w.pages.map((p) => [p.id, p.kind === 'home' ? '/' : `/${p.slug}`]));
const live = new Set(w.pages.map((p) => p.slug));
for (const h of history) {
const to = pathOf.get(h.pageId);
if (to && !live.has(h.slug)) snap.redirects[h.slug] = to;
}
return snap;
}
export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
const images = new Map(media.map((m) => [m.id, imageOf(m)]));
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
const used: Record<string, Image> = {};
const collect = (data: unknown) => {
// Every media id anywhere in a section's data (images, videoId, imageId, photoId).
const walk = (x: unknown) => {
if (typeof x === 'string' && images.has(x)) used[x] = images.get(x)!;
else if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
};
walk(data);
};
const d = cleanDesign(source.design);
const snapshotPages: SnapshotPage[] = source.pages.map((p) => {
const sections: SnapshotSection[] = [];
if (p.kind === 'home') {
// The homepage: the design's order and variants, each section's data from the page.
const byType = new Map(p.sections.map((x) => [x.type, x]));
for (const entry of d.home) {
if (entry.hidden) continue;
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
if (!data) continue;
collect(data);
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
}
} else {
for (const x of p.sections) {
if (x.hidden) continue;
const data = parseSectionData(x.type, x.data);
if (!data) continue;
collect(data);
sections.push({ type: x.type, variant: x.variant, data });
}
}
return {
kind: p.kind, slug: p.slug, path: p.kind === 'home' ? '/' : `/${p.slug}`, title: p.title, seoTitle: p.seoTitle, description: p.description,
navLabel: p.navLabel || p.title, inNav: p.inNav && p.kind !== 'home', image: image(p.imageId), sections,
};
});
return {
v: SNAPSHOT_VERSION,
design: d,
pages: snapshotPages,
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
media: used,
redirects: {},
source,
};
}
/** Publish (§4): the whole working copy becomes the next version, at once. */
export async function publish(ctx: Ctx, by: { id: string; role: string }, note: string | null = null) {
const snapshot = await buildSnapshot(ctx);
const last = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true } });
const version = await ctx.db.siteVersion.create({
data: { number: (last?.number ?? 0) + 1, snapshot: snapshot as never, note, publishedBy: by.id, publishedAt: ctx.now() },
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'site_published', targetType: 'site_version', targetId: String(version.number), metadata: { note } });
return version;
}
/** The latest published snapshot, or null before the first publish (Coming soon). */
export async function publishedSnapshot(ctx: Ctx): Promise<{ number: number; publishedAt: Date; snapshot: Snapshot } | null> {
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } });
if (!latest) return null;
const snap = latest.snapshot as unknown as Snapshot;
if (!snap || snap.v !== SNAPSHOT_VERSION) return null;
return { number: latest.number, publishedAt: latest.publishedAt, snapshot: { ...snap, design: cleanDesign(snap.design as never) } };
}
+88
View File
@@ -0,0 +1,88 @@
/**
* The fixed pages (WEBSITE-1.0-PLAN §6) with starter text, for a site that has no pages yet: a new
* install. Without them the home page had no sections (the site and its preview showed only the
* header and footer) and the other pages didn't exist. Terms and Safeguarding come from starter
* text too (§2), linked from the footer rather than the menu.
*
* Checked at startup (ensureStarterPages): a site with none of the fixed pages gets them all, one
* without a home page gets that. A page a church removed (archived) isn't brought back, except home,
* which can't be removed. Nothing is published: the pages are drafts like any other change. The text names no church, since a new install isn't
* always linked to its church profile yet; every section and block can be edited.
*/
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import type { SectionData } from './sections.js';
type Block = { type: string; data: Record<string, unknown> };
type StarterPage = { kind: string; slug: string; title: string; inNav?: boolean; description: string; sections: Block[] };
const VISIT = { label: 'Plan your visit', href: '/visit' };
export const STARTER_HOME: SectionData = {
hero: { headline: 'You are welcome here', subline: 'Join us this Sunday. Come as you are.', images: [], videoId: null, button: VISIT },
serviceTimes: { heading: 'Join us this Sunday', note: null },
welcome: {
heading: 'Welcome', mission: null, imageId: null, pastor: null,
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here.',
},
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
team: { heading: 'Our team', intro: null },
events: { heading: 'Coming up', count: 3 },
latestMessage: { heading: 'Latest message' },
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: VISIT, imageId: null },
};
const text = (heading: string | null, body: string): Block => ({ type: 'text', data: { heading, body } });
export const STARTER_PAGES: StarterPage[] = [
{ kind: 'home', slug: 'home', title: 'Home', description: 'Join us this Sunday. Come as you are.', sections: Object.entries(STARTER_HOME).map(([type, data]) => ({ type, data })) },
{
kind: 'visit', slug: 'visit', title: 'Plan your visit', description: 'What to expect on your first Sunday with us.', sections: [
text('What to expect', 'We sing together, pray, and hear a message from the Bible. Dress is casual, and there is coffee after the service.'),
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Get in touch and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
],
},
{ kind: 'about', slug: 'about', title: 'About us', description: 'Our story, what we believe and what we value.', sections: [text('Our story', 'Tell your church\'s story here: how it started, what you believe and what you value.')] },
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', description: 'Find your place in our church family.', sections: [] },
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', description: 'The team who lead our church.', sections: [] },
{ kind: 'events', slug: 'events', title: 'Events', description: 'What is coming up at our church.', sections: [] },
{ kind: 'messages', slug: 'messages', title: 'Messages', description: 'Sunday messages from our church.', sections: [] },
{ kind: 'give', slug: 'give', title: 'Give', description: 'How to give to our church.', sections: [text('Giving', 'Thank you for giving. Add how to give here: your bank details, or links to SnapScan, Zapper or PayFast.')] },
{ kind: 'contact', slug: 'contact', title: 'Contact', description: 'How to find us and get in touch.', sections: [] },
{
kind: 'terms', slug: 'terms', title: 'Terms of use', inNav: false, description: 'The terms for using this website.', sections: [
text(null, 'This website is run by our church to share who we are, what we do and when we meet. You may use it for your own, personal purposes.\n\nWe do our best to keep it accurate and up to date, but things change: please check service times and events with us if you are unsure.\n\nLinks to other websites are for your convenience; we are not responsible for what they say.\n\nHow we handle personal information is in our privacy notice, linked at the bottom of every page.'),
],
},
{
kind: 'safeguarding', slug: 'safeguarding', title: 'Safeguarding', inNav: false, description: 'How we keep children and vulnerable adults safe.', sections: [
text(null, 'We are committed to the safety of every child and vulnerable adult in our care. Everyone who serves with children or vulnerable adults is screened and trained, and we follow a written safeguarding policy.\n\nIf you are worried about someone\'s safety, or about how anyone at our church has behaved, please speak to a member of our leadership team. If someone is in immediate danger, contact the police.'),
],
},
];
/**
* Adds the fixed pages a site is missing: all of them while it has none of them (only pages it made
* itself, or nothing at all), else just the home page if that's missing. A page whose address
* another page already has is left out. Custom pages move after them. Returns the kinds added.
*/
export async function ensureStarterPages(ctx: Ctx): Promise<string[]> {
const db = ctx.db;
const existing = await db.page.findMany({ select: { id: true, kind: true, slug: true, position: true, archivedAt: true } });
const fixed = existing.filter((p) => p.kind !== 'custom');
const wanted = fixed.length === 0 ? STARTER_PAGES : fixed.some((p) => p.kind === 'home' && !p.archivedAt) ? [] : STARTER_PAGES.filter((p) => p.kind === 'home');
const slugs = new Set(existing.map((p) => p.slug));
const adding = wanted.filter((p) => !slugs.has(p.slug));
if (!adding.length) return [];
// The site's own pages keep their order, after the fixed ones.
for (const p of existing.filter((x) => x.kind === 'custom')) await db.page.update({ where: { id: p.id }, data: { position: p.position + adding.length } });
let position = 0;
for (const p of adding) {
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: position++, description: p.description, inNav: p.inNav ?? true } });
let i = 0;
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, position: i++, data: s.data as never } });
}
const kinds = adding.map((p) => p.kind);
await audit(ctx, { actorId: null, actorRole: 'system', action: 'starter_pages_added', targetType: 'page', metadata: { kinds } });
return kinds;
}
+18
View File
@@ -0,0 +1,18 @@
/**
* What the public site shows right now: Coming soon until the first publish (§5, decision 3), then
* the latest published version. After the first publish there's no going back to Coming soon.
*/
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
export type SiteStatus =
| { mode: 'coming-soon' }
| { mode: 'published'; version: number; publishedAt: string; template: WebsiteTemplate | null };
export async function siteStatus(ctx: Ctx): Promise<SiteStatus> {
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true, publishedAt: true, snapshot: true } });
if (!latest) return { mode: 'coming-soon' };
const t = (latest.snapshot as { design?: { template?: unknown } } | null)?.design?.template;
const template = (WEBSITE_TEMPLATES as readonly unknown[]).includes(t) ? (t as WebsiteTemplate) : null;
return { mode: 'published', version: latest.number, publishedAt: latest.publishedAt.toISOString(), template };
}
@@ -0,0 +1,70 @@
/**
* A message's YouTube thumbnail, served from the site (WEBSITE-1.0-PLAN §7: nothing loads from
* YouTube until a visitor clicks play). The backend fetches `i.ytimg.com/vi/<id>/hqdefault.jpg`
* once and keeps it in `<uploads>/.thumbnails/` (not served from /api/uploads, which denies dot
* folders, and not counted as the church's storage). Only the ids of the site's own messages are
* fetched, so the route is never a proxy for anything else.
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { youtubeId } from './content.js';
export { thumbnailPath } from './content.js';
export type Fetcher = (url: string) => Promise<Response>;
const ID = /^[A-Za-z0-9_-]{6,20}$/;
const MAX_BYTES = 1024 * 1024;
const cacheDir = (ctx: Ctx) => path.join(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), '.thumbnails');
const defaultFetcher: Fetcher = (url) => fetch(url, { signal: AbortSignal.timeout(10_000) });
/** One fetch per video at a time, however many visitors ask at once. */
const inFlight = new Map<string, Promise<Buffer | null>>();
async function isOurVideo(ctx: Ctx, videoId: string) {
const rows = await ctx.db.message.findMany({ where: { mediaUrl: { contains: videoId } }, select: { mediaUrl: true, source: true }, take: 5 });
return rows.some((m) => m.source !== 'spotify' && youtubeId(m.mediaUrl) === videoId);
}
async function download(fetcher: Fetcher, videoId: string): Promise<Buffer | null> {
try {
const res = await fetcher(`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`);
if (!res.ok || !/^image\/jpe?g/.test(res.headers.get('content-type') ?? '')) return null;
const body = Buffer.from(await res.arrayBuffer());
// A JPEG by its bytes, and a sensible size.
if (body.length > MAX_BYTES || body.length < 3 || body[0] !== 0xff || body[1] !== 0xd8 || body[2] !== 0xff) return null;
return body;
} catch {
return null;
}
}
/** The thumbnail's bytes, from the cache or YouTube; null when it isn't one of the site's videos or YouTube has none. */
export async function thumbnail(ctx: Ctx, videoId: string, fetcher: Fetcher = ctx.fetch ?? defaultFetcher): Promise<Buffer | null> {
if (!ID.test(videoId)) return null;
const file = path.join(cacheDir(ctx), `${videoId}.jpg`);
try {
return await fs.readFile(file);
} catch {
// Not cached yet.
}
if (!(await isOurVideo(ctx, videoId))) return null;
let pending = inFlight.get(videoId);
if (!pending) {
pending = (async () => {
const body = await download(fetcher, videoId);
if (body) {
await fs.mkdir(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
await fs.writeFile(tmp, body);
await fs.rename(tmp, file);
}
return body;
})().finally(() => inFlight.delete(videoId));
inFlight.set(videoId, pending);
}
return pending;
}
+202
View File
@@ -0,0 +1,202 @@
/**
* Section variants per template (docs/WEBSITE-1.0-PLAN.md §3, "Section variants per template",
* decision 16, confirmed 2026-11-25).
*
* Every template draws every variant, so nothing is ever unavailable and a template switch never
* needs a fallback. A template only sets which variant each section starts with, which ones it
* recommends, its header options, its homepage order and its style defaults.
*
* The ids are stored on each section (`hero.variant = "photo"`), so **an id never changes or goes
* away** once released, like the font pairing ids in `@crosscode/contracts`.
*/
import { z } from 'zod';
import type { Corners, WebsiteTemplate } from '@crosscode/contracts';
/** The homepage section types and their variant ids. */
export const SECTION_VARIANTS = {
hero: ['photo', 'video', 'collage', 'split', 'text'],
serviceTimes: ['panel', 'strip', 'map'],
welcome: ['text', 'image-text', 'pastor'],
ministries: ['cards', 'list', 'bands'],
team: ['faces', 'list', 'featured'],
events: ['cards', 'list', 'calendar'],
latestMessage: ['video', 'card', 'compact'],
invitation: ['banner', 'centred', 'image'],
} as const;
export type SectionType = keyof typeof SECTION_VARIANTS;
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
export const sectionTypeSchema = z.enum(SECTION_TYPES);
/** Whether `variant` is one of `section`'s ids. */
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
}
/** Per section: the default first, then the other recommended variants. */
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
heritage: {
hero: ['photo', 'split', 'text'],
serviceTimes: ['panel', 'map'],
welcome: ['pastor', 'text'],
ministries: ['list', 'cards'],
team: ['featured', 'faces'],
events: ['list', 'calendar'],
latestMessage: ['card', 'video'],
invitation: ['centred', 'banner'],
},
bold: {
hero: ['video', 'photo', 'split'],
serviceTimes: ['strip', 'map'],
welcome: ['image-text', 'pastor'],
ministries: ['bands', 'cards'],
team: ['faces', 'featured'],
events: ['cards', 'calendar'],
latestMessage: ['video', 'card'],
invitation: ['image', 'banner'],
},
community: {
hero: ['collage', 'photo', 'split'],
serviceTimes: ['map', 'panel'],
welcome: ['pastor', 'image-text'],
ministries: ['cards', 'bands'],
team: ['faces', 'featured'],
events: ['cards', 'calendar'],
latestMessage: ['card', 'video'],
invitation: ['banner', 'image'],
},
clean: {
hero: ['text', 'split', 'photo'],
serviceTimes: ['strip', 'panel'],
welcome: ['text', 'image-text'],
ministries: ['list', 'cards'],
team: ['list', 'faces'],
events: ['list', 'calendar'],
latestMessage: ['compact', 'card'],
invitation: ['centred', 'banner'],
},
};
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
}
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
}
/** The "Header" style setting: each template's options, default first. */
export const TEMPLATE_HEADERS = {
heritage: ['centred', 'centred-top-bar'],
bold: ['transparent', 'solid'],
community: ['logo-left-button', 'logo-left-tinted'],
clean: ['small', 'small-menu'],
} as const satisfies Record<WebsiteTemplate, readonly [string, ...string[]]>;
/**
* The transparent header only sits over a photo, video or collage hero; on any other first section
* it's drawn solid, so it never puts white text on white.
*/
export function headerIsTransparent(template: WebsiteTemplate, header: string, heroVariant: Variant<'hero'> | null): boolean {
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
}
/** A homepage entry: the section and whether it shows. */
export type HomeEntry = { section: SectionType; hidden: boolean };
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
...shown.map((section) => ({ section, hidden: false })),
...hidden.map((section) => ({ section, hidden: true })),
];
/** The default homepage order (the church can reorder, hide and show). Every section is listed once. */
export const TEMPLATE_HOME_ORDER: Record<WebsiteTemplate, HomeEntry[]> = {
heritage: order(['hero', 'serviceTimes', 'welcome', 'latestMessage', 'ministries', 'team', 'events', 'invitation']),
bold: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'ministries', 'invitation'], ['team']),
community: order(['hero', 'welcome', 'serviceTimes', 'ministries', 'team', 'events', 'latestMessage', 'invitation']),
clean: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'invitation'], ['ministries', 'team']),
};
/** The Website-only style settings (§3, "Style settings"). Fonts and corners are the church's, shared. */
export const SECTION_COLOURS = ['light', 'tinted', 'mixed'] as const;
export const SPACINGS = ['airy', 'compact'] as const;
export const BUTTONS = ['solid', 'outline', 'pill'] as const;
export const IMAGE_TREATMENTS = ['natural', 'mono', 'duotone'] as const;
export type SiteStyle = {
sectionColour: (typeof SECTION_COLOURS)[number];
spacing: (typeof SPACINGS)[number];
buttons: (typeof BUTTONS)[number];
images: (typeof IMAGE_TREATMENTS)[number];
header: string;
};
export const TEMPLATE_STYLE: Record<WebsiteTemplate, SiteStyle & { suggestedCorners: Corners }> = {
heritage: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'centred', suggestedCorners: 'sharp' },
bold: { sectionColour: 'mixed', spacing: 'compact', buttons: 'solid', images: 'natural', header: 'transparent', suggestedCorners: 'sharp' },
community: { sectionColour: 'tinted', spacing: 'airy', buttons: 'pill', images: 'natural', header: 'logo-left-button', suggestedCorners: 'round' },
clean: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'small', suggestedCorners: 'soft' },
};
const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] as const;
/** The site's design: what a template switch changes. Content is never part of it. */
export type SiteDesign = {
template: WebsiteTemplate;
variants: { [S in SectionType]: Variant<S> };
home: HomeEntry[];
style: SiteStyle;
};
/** A fresh site on `template`: every default. */
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
}
export type DesignChange = { what: string; from: string; to: string };
const sameOrder = (a: HomeEntry[], b: HomeEntry[]) =>
a.length === b.length && a.every((e, i) => e.section === b[i]!.section && e.hidden === b[i]!.hidden);
/**
* Switching template (§3, "Switching template"): anything still on the old template's default
* moves to the new template's default; anything the church chose stays. Returns the new design and
* what moved, for the Publish screen ("Hero: Collage → Text only, Clean's default").
*/
export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { design: SiteDesign; changes: DesignChange[] } {
if (current.template === to) return { design: current, changes: [] };
const from = current.template;
const target = defaultDesign(to);
const changes: DesignChange[] = [{ what: 'template', from, to }];
const variants = { ...current.variants } as Record<SectionType, string>;
for (const s of SECTION_TYPES) {
const next = target.variants[s];
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
variants[s] = next;
}
}
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e }));
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
const style = { ...current.style };
const oldStyle = TEMPLATE_STYLE[from];
for (const k of STYLE_KEYS) {
// A header from the old template's options means nothing in the new one, so it always moves.
const untouched = current.style[k] === oldStyle[k] || (k === 'header' && !(TEMPLATE_HEADERS[to] as readonly string[]).includes(current.style.header));
if (untouched && current.style[k] !== target.style[k]) {
changes.push({ what: `style.${k}`, from: current.style[k], to: target.style[k] });
(style as Record<string, string>)[k] = target.style[k];
}
}
return { design: { template: to, variants: variants as SiteDesign['variants'], home, style }, changes };
}
@@ -0,0 +1,141 @@
/**
* Pending changes, Discard and Restore (WEBSITE-1.0-PLAN §4). The working copy is compared with
* the latest published version's `source`, item by item: the site's design, each page (with its
* sections), each ministry and each leader.
*
* changes(ctx) what Publish would put live: added, changed or removed, who and when
* discard(ctx, key) one item back to its published state (an added one is archived)
* restore(ctx, n) a whole version back into the working copy (then previewed and published
* like any other change; nothing is lost)
*
* Archive instead of delete: a removed page, ministry or leader keeps its row (`archivedAt`).
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
export type ChangeKind = 'added' | 'changed' | 'removed';
export type Change = { key: string; kind: ChangeKind; what: 'design' | 'page' | 'ministry' | 'leader'; label: string; by: string | null; at: string | null };
type Item = { key: string; what: Change['what']; label: string; value: unknown };
function items(s: Source | null): Map<string, Item> {
const m = new Map<string, Item>();
if (!s) return m;
if (s.design) m.set('design', { key: 'design', what: 'design', label: 'Template and style', value: s.design });
for (const p of s.pages) m.set(`page:${p.id}`, { key: `page:${p.id}`, what: 'page', label: p.title, value: p });
for (const x of s.ministries) m.set(`ministry:${x.id}`, { key: `ministry:${x.id}`, what: 'ministry', label: x.name, value: x });
for (const x of s.leaders) m.set(`leader:${x.id}`, { key: `leader:${x.id}`, what: 'leader', label: x.name, value: x });
return m;
}
/** JSON with sorted keys, so two copies of the same thing compare equal. */
function stable(v: unknown): string {
if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`;
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`;
return JSON.stringify(v ?? null);
}
async function publishedSource(ctx: Ctx): Promise<Source | null> {
return (await publishedSnapshot(ctx))?.snapshot.source ?? null;
}
export async function changes(ctx: Ctx): Promise<Change[]> {
const w = await readWorkingCopy(ctx);
const now = items(toSource(w));
const then = items(await publishedSource(ctx));
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
// Who changed it last, and when: the row's own, or (for a page) its latest section's.
const who = new Map<string, { by: string | null; at: Date | null }>();
if (w.design) who.set('design', { by: w.design.updatedBy, at: w.design.updatedAt });
for (const p of w.pages) {
const latest = [p, ...p.sections].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!;
who.set(`page:${p.id}`, { by: latest.updatedBy, at: latest.updatedAt });
}
for (const x of w.ministries) who.set(`ministry:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
for (const x of w.leaders) who.set(`leader:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
const out: Change[] = [];
const meta = (key: string) => {
const h = who.get(key);
return { by: h?.by ? names.get(h.by) ?? null : null, at: h?.at?.toISOString() ?? null };
};
for (const [key, item] of now) {
const before = then.get(key);
if (!before) out.push({ key, kind: 'added', what: item.what, label: item.label, ...meta(key) });
else if (stable(before.value) !== stable(item.value)) out.push({ key, kind: 'changed', what: item.what, label: item.label, ...meta(key) });
}
for (const [key, item] of then) if (!now.has(key)) out.push({ key, kind: 'removed', what: item.what, label: item.label, by: null, at: null });
return out;
}
type Who = { id: string; role: string };
/** Puts one item of `source` into the working copy as it is there (or archives it when absent). */
async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
const db = ctx.db;
const [what, id] = key.split(':') as [string, string | undefined];
const stamp = { updatedBy: by.id };
if (what === 'design') {
if (!source?.design) throw new ApiError(409, 'NOTHING_PUBLISHED', 'The design has never been published, so there\'s nothing to go back to.');
const d = source.design;
const data = { template: d.template, variants: d.variants as never, home: d.home as never, style: d.style as never, ...stamp };
await db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
return;
}
if (!id) throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
if (what === 'page') {
const p = source?.pages.find((x) => x.id === id);
if (!p) {
await db.page.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } });
return;
}
// A page that was added since takes the slug: move it aside first.
const clash = await db.page.findFirst({ where: { slug: p.slug, NOT: { id } } });
if (clash) await db.page.update({ where: { id: clash.id }, data: { slug: `${clash.slug}-${clash.id.slice(0, 6)}` } });
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
await db.section.deleteMany({ where: { pageId: id } });
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
return;
}
if (what === 'ministry') {
const m = source?.ministries.find((x) => x.id === id);
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
return;
}
if (what === 'leader') {
const l = source?.leaders.find((x) => x.id === id);
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
return;
}
throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
}
/** Discard (§4): one pending change goes back to its published value. */
export async function discard(ctx: Ctx, key: string, by: Who) {
const pending = (await changes(ctx)).find((c) => c.key === key);
if (!pending) throw new ApiError(404, 'NO_SUCH_CHANGE', 'That change isn\'t pending any more.');
await apply(ctx, key, await publishedSource(ctx), by);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'change_discarded', targetType: pending.what, targetId: key, metadata: { label: pending.label, kind: pending.kind } });
return pending;
}
/** Restore (§4): version `number` back into the working copy, to preview and publish. */
export async function restore(ctx: Ctx, number: number, by: Who) {
const v = await ctx.db.siteVersion.findUnique({ where: { number } });
const source = (v?.snapshot as { source?: Source } | null)?.source;
if (!v || !source) throw new ApiError(404, 'NO_SUCH_VERSION', 'That version can\'t be restored.');
const keys = new Set([...items(toSource(await readWorkingCopy(ctx))).keys(), ...items(source).keys()]);
for (const key of keys) {
if (key === 'design' && !source.design) continue;
await apply(ctx, key, source, by);
}
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'version_restored', targetType: 'site_version', targetId: String(number) });
return { restored: number, pending: (await changes(ctx)).length };
}
+101
View File
@@ -0,0 +1,101 @@
/**
* Messages from YouTube, automatically (WEBSITE-1.0-PLAN §7, decision 7): the church's channel or a
* playlist, read from YouTube's public feed (no API key) every hour. Each new video becomes a
* message, live at once (decision 9); admins add the speaker, series and passage afterwards, or hide
* one. A video already here (by its id, however it came in) is never added twice.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
export type YoutubeSource = { kind: 'channel' | 'playlist'; id: string };
/** A channel id (UC…), a channel or playlist address, or a playlist id (PL…, UU…, OL…). */
export function parseSource(input: string): YoutubeSource | null {
const v = input.trim();
const channel = /(?:^|\/channel\/)(UC[\w-]{22})(?:[/?#]|$)/.exec(v);
if (channel) return { kind: 'channel', id: channel[1]! };
const list = /[?&]list=([\w-]{10,64})/.exec(v) ?? /^((?:PL|UU|OL|FL)[\w-]{10,62})$/.exec(v);
if (list) return { kind: 'playlist', id: list[1]! };
return null;
}
export const feedUrl = (s: YoutubeSource) => `https://www.youtube.com/feeds/videos.xml?${s.kind === 'channel' ? 'channel_id' : 'playlist_id'}=${encodeURIComponent(s.id)}`;
export type FeedVideo = { videoId: string; title: string; published: Date; thumbnail: string | null };
const unescape = (s: string) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&amp;/g, '&');
/** The videos in a YouTube Atom feed. Entries without an id, title or date are left out. */
export function parseFeed(xml: string): FeedVideo[] {
const out: FeedVideo[] = [];
for (const m of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {
const e = m[1]!;
const videoId = /<yt:videoId>([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1];
const title = /<title>([\s\S]*?)<\/title>/.exec(e)?.[1];
const published = /<published>([^<]+)<\/published>/.exec(e)?.[1];
const thumbnail = /<media:thumbnail url="([^"]+)"/.exec(e)?.[1] ?? null;
const date = published ? new Date(published) : null;
if (!videoId || !title || !date || Number.isNaN(date.getTime())) continue;
out.push({ videoId, title: unescape(title.trim()).slice(0, 500), published: date, thumbnail: thumbnail && thumbnail.startsWith('https://') ? thumbnail : null });
}
return out;
}
export async function getSource(ctx: Ctx): Promise<YoutubeSource | null> {
return ctx.settings.json<YoutubeSource | null>('youtube_source', null);
}
export async function setSource(ctx: Ctx, input: string | null): Promise<YoutubeSource | null> {
if (!input?.trim()) {
await ctx.settings.set('youtube_source', null);
return null;
}
const s = parseSource(input);
if (!s) throw new ApiError(400, 'VALIDATION', 'That isn\'t a YouTube channel id (UC…) or playlist address.', { youtube: 'A channel id (UC…) or a playlist link' });
await ctx.settings.set('youtube_source', JSON.stringify(s));
return s;
}
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'message';
export async function uniqueSlug(ctx: Ctx, title: string, model: 'message' | 'simpleEvent', except?: string) {
const base = slugify(title);
for (let n = 1; ; n++) {
const slug = n === 1 ? base : `${base}-${n}`;
const taken = model === 'message'
? await ctx.db.message.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } })
: await ctx.db.simpleEvent.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (!taken) return slug;
}
}
type Fetcher = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
/** The hourly job: new videos become messages. Returns how many were added. */
export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, { signal: AbortSignal.timeout(15000), headers: { accept: 'application/atom+xml' } })) {
const source = await getSource(ctx);
if (!source) return { added: 0, skipped: 'no source' };
let videos: FeedVideo[];
try {
const res = await fetcher(feedUrl(source));
if (!res.ok) throw new Error(`YouTube answered ${res.status}`);
videos = parseFeed(await res.text());
} catch (e) {
await ctx.settings.set('youtube_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 300));
return { added: 0, error: (e as Error).message };
}
let added = 0;
for (const v of videos) {
if (await ctx.db.message.findUnique({ where: { externalId: v.videoId } })) continue;
await ctx.db.message.create({
data: {
slug: await uniqueSlug(ctx, v.title, 'message'), title: v.title, date: v.published, source: 'youtube_feed',
mediaUrl: `https://www.youtube.com/watch?v=${v.videoId}`, externalId: v.videoId, thumbnailUrl: v.thumbnail, publishedAt: ctx.now(),
},
});
added++;
}
await ctx.settings.setMany({ youtube_last_sync_at: ctx.now().toISOString(), youtube_last_error: null });
return { added };
}
+228
View File
@@ -0,0 +1,228 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import sharp from 'sharp';
import { loadDemo } from '../src/demo/demoChurch.js';
import { hashToken } from '../src/lib/crypto.js';
import { dimensions, sniff } from '../src/admin/media.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
/** The demo church, and a signed-in admin with `role`. Returns a request helper with their cookie. */
async function signedIn(role: Role = 'editor', opts: { ministryId?: string | null } = {}) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-admin-'));
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor', 'ministry_leader', 'viewer'].indexOf(role) + 1}`;
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role, ministryId: opts.ministryId ?? null } });
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const cookie = `ccw_session=token-${role}`;
const as = {
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE),
upload: (p: string, bytes: Buffer) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(bytes),
};
const pages = (await as.get('/pages')).body as { id: string; kind: string; slug: string }[];
return { ...h, as, id, dir, cookie, page: (kind: string) => pages.find((p) => p.kind === kind)!.id };
}
describe('the admin: who may do what (§10)', () => {
it('lets a Viewer look but change nothing', async () => {
const { as, page } = await signedIn('viewer');
assert.equal((await as.get('/overview')).status, 200);
assert.equal((await as.put(`/pages/${page('about')}`, { title: 'Us' })).status, 403);
assert.equal((await as.post('/publish')).status, 403);
});
it('lets a Ministry leader change their own ministry only, and not publish', async () => {
const { as, db } = await signedIn('ministry_leader');
const list = (await as.get('/ministries')).body as { id: string; name: string }[];
await db.websiteUser.update({ where: { id: '00000000-0000-4000-8000-000000000004' }, data: { ministryId: list[0]!.id } });
assert.equal((await as.put(`/ministries/${list[0]!.id}`, { name: 'Kids church', summary: 'Ages 3 to 12' })).status, 200);
assert.equal((await as.put(`/ministries/${list[1]!.id}`, { name: 'Youth' })).status, 403);
assert.equal((await as.post('/publish')).status, 403);
});
it('refuses a change that didn\'t come from the site itself', async () => {
const { app, cookie, page } = await signedIn('editor');
const res = await request(app).put(`/api/v1/admin/pages/${page('about')}`).set('Cookie', cookie).set('Origin', 'https://evil.example').send({ title: 'x' });
assert.equal(res.status, 403);
});
});
describe('editing, publishing, discarding, restoring (§4)', () => {
it('lists a change with who made it; Publish puts it live; nothing left to publish', async () => {
const { as, page, app } = await signedIn('editor');
assert.deepEqual((await as.get('/changes')).body, []);
const r = await as.put(`/pages/${page('about')}`, { title: 'Our story' });
assert.equal(r.status, 200);
const pending = (await as.get('/changes')).body;
assert.equal(pending.length, 1);
assert.equal(pending[0].kind, 'changed');
assert.equal(pending[0].label, 'Our story');
assert.equal(pending[0].by, 'Sam the editor');
// Visitors still see the published title until Publish.
const before = (await request(app).get('/api/v1/site/content')).body;
assert.equal(before.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'About us');
assert.equal(before.snapshot.source, undefined, 'never sent to visitors');
const pub = await as.post('/publish', { note: 'New page title' });
assert.equal(pub.status, 200);
assert.equal(pub.body.number, 2);
const after = (await request(app).get('/api/v1/site/content')).body;
assert.equal(after.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'Our story');
assert.equal((await as.post('/publish')).body.error.code, 'NOTHING_TO_PUBLISH');
});
it('discards one change, back to its published value; an added page is archived', async () => {
const { as, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Changed' });
const added = await as.post('/pages', { title: 'Youth camp', slug: 'youth-camp' });
assert.equal(added.status, 200);
assert.equal((await as.get('/changes')).body.length, 2);
assert.equal((await as.post('/discard', { key: `page:${page('about')}` })).status, 200);
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
await as.post('/discard', { key: `page:${added.body.id}` });
assert.deepEqual((await as.get('/changes')).body, []);
assert.equal((await as.get(`/pages/${added.body.id}`)).status, 404);
assert.equal((await as.post('/discard', { key: 'page:nope' })).status, 404);
});
it('restores an older version into the working copy, to preview and publish', async () => {
const { as, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Version two' });
await as.post('/publish');
await as.del(`/pages/${page('give')}`);
await as.post('/publish');
const r = await as.post('/versions/1/restore');
assert.equal(r.status, 200);
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
assert.equal((await as.get(`/pages/${page('give')}`)).status, 200, 'the removed page is back');
assert.equal(r.body.pending, 2);
const versions = (await as.get('/versions')).body;
assert.deepEqual(versions.map((v: { number: number }) => v.number), [3, 2, 1]);
});
it('switches template, keeping the church\'s own choices, and says what moved', async () => {
const { as } = await signedIn('editor');
await as.put('/design', { variants: { team: 'list' } });
const r = await as.put('/design', { template: 'bold' });
assert.equal(r.status, 200);
assert.equal(r.body.design.template, 'bold');
assert.equal(r.body.design.variants.team, 'list', 'kept');
assert.equal(r.body.design.variants.hero, 'video', 'moved to Bold\'s default');
assert.ok(r.body.moved.some((m: { what: string }) => m.what === 'hero.variant'));
assert.equal((await as.put('/design', { variants: { hero: 'spinning' } })).status, 400);
assert.equal((await as.put('/design', { style: { header: 'centred' } })).status, 400, 'a Heritage header on Bold');
});
it('checks a section\'s data and says which field is wrong', async () => {
const { as, page } = await signedIn('editor');
const bad = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: '', button: { label: 'Go', href: 'javascript:x' } } });
assert.equal(bad.status, 400);
assert.ok(bad.body.error.fields.headline);
assert.ok(bad.body.error.fields['button.href']);
const good = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: 'Welcome home' } });
assert.equal(good.status, 200);
});
it('adds, moves and removes blocks on a page; refuses an address the site uses', async () => {
const { as, page } = await signedIn('editor');
const id = page('about');
const added = (await as.post(`/pages/${id}/blocks`, { type: 'quote' })).body;
assert.equal(added.sections.at(-1).type, 'quote');
const quote = added.sections.at(-1).id;
const moved = (await as.post(`/pages/${id}/blocks/${quote}/move`, { direction: 'up' })).body;
assert.equal(moved.sections.at(-2).id, quote);
assert.equal((await as.del(`/pages/${id}/blocks/${quote}`)).body.sections.some((s: { id: string }) => s.id === quote), false);
assert.equal((await as.post('/pages', { title: 'Admin', slug: 'admin' })).status, 400);
assert.equal((await as.post('/pages', { title: 'Visit', slug: 'visit' })).body.error.code, 'SLUG_TAKEN');
});
});
describe('the preview (§4)', () => {
it('shows the working copy to a signed-in admin, never to anyone else', async () => {
const { as, app, cookie, page } = await signedIn('editor');
await as.put(`/pages/${page('about')}`, { title: 'Draft title' });
assert.equal((await request(app).get('/api/v1/site/preview')).status, 401);
const p = await request(app).get('/api/v1/site/preview').set('Cookie', cookie);
assert.equal(p.status, 200);
assert.equal(p.body.snapshot.pages.find((x: { kind: string }) => x.kind === 'about').title, 'Draft title');
assert.equal(p.body.preview.canPublish, true);
assert.match(String(p.headers['x-robots-tag']), /noindex/);
});
it('a shared link works signed out for 7 days, until revoked', async () => {
const { as, app } = await signedIn('editor');
const link = (await as.post('/preview-links')).body;
const token = link.url.split('/preview/')[1];
const p = await request(app).get('/api/v1/site/preview').set('x-preview-token', token);
assert.equal(p.status, 200);
assert.equal(p.body.preview.canPublish, false);
await as.del(`/preview-links/${link.id}`);
assert.equal((await request(app).get('/api/v1/site/preview').set('x-preview-token', token)).status, 401);
assert.equal((await as.get('/preview-links')).body[0].active, false);
});
});
describe('uploads and storage (§10, decision 12)', () => {
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]), Buffer.from('IHDR'), Buffer.from([0, 0, 2, 128, 0, 0, 1, 224]), Buffer.alloc(40)]);
it('knows a photo by its bytes, and its size', () => {
assert.deepEqual(sniff(png), { ext: 'png', mime: 'image/png' });
assert.deepEqual(dimensions(png, { ext: 'png', mime: 'image/png' }), { width: 640, height: 480 });
assert.equal(sniff(Buffer.from('<svg>')), null);
});
it('keeps a photo upright and without its location, in responsive sizes; refuses what isn\'t one', async () => {
const { as, dir, app } = await signedIn('editor');
// A 2000 × 1200 phone photo with its GPS position in the metadata.
const photo = await sharp({ create: { width: 2000, height: 1200, channels: 3, background: '#1d5c63' } })
.jpeg().withExifMerge({ IFD3: { GPSLatitudeRef: 'S', GPSLatitude: '25/1 44/1 46/1' } }).toBuffer();
assert.ok((await sharp(photo).metadata()).exif, 'the test photo has EXIF');
const up = await as.upload('/media?alt=The%20hall', photo);
assert.equal(up.status, 200);
assert.equal(up.body.width, 2000);
assert.deepEqual(up.body.sizes.map((x: { w: number }) => x.w), [480, 960, 1600]);
const file = path.join(dir, up.body.filename);
assert.equal((await sharp(fs.readFileSync(file)).metadata()).exif, undefined, 'no metadata kept');
const files = fs.readdirSync(path.dirname(file));
assert.equal(files.length, 7, 'the photo and 3 sizes in WebP and JPEG');
const total = files.reduce((t, n) => t + fs.statSync(path.join(path.dirname(file), n)).size, 0);
assert.equal(up.body.bytes, total, 'every file counts towards storage');
// The site gets srcsets.
const about = (await as.get('/pages')).body.find((p: { kind: string }) => p.kind === 'about').id;
await as.put(`/pages/${about}`, { imageId: up.body.id });
await as.post('/publish');
const content = (await request(app).get('/api/v1/site/content')).body;
const img = content.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').image;
assert.match(img.srcset.webp, /-480\.webp 480w, .*-960\.webp 960w, .*-1600\.webp 1600w, .*\.jpg 2000w$/);
const big = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#e0a458' } }).png().toBuffer();
const b = await as.upload('/media', big);
assert.equal(b.body.width, 2400, 'kept at most 2400 wide');
assert.equal(b.body.height, 1800);
assert.equal((await as.upload('/media', Buffer.from('<svg onload=alert(1)>'))).status, 415);
assert.equal((await as.upload('/media', png)).status, 415, 'a PNG header with nothing behind it');
});
it('stops uploads when storage is full', async () => {
const { as, db } = await signedIn('editor');
const photo = await sharp({ create: { width: 800, height: 600, channels: 3, background: '#ffffff' } }).jpeg().toBuffer();
// The media library already holds the included 5 GB.
await db.mediaAsset.create({ data: { filename: 'big.jpg', mime: 'image/jpeg', bytes: 5 * 1024 ** 3 } });
const full = await as.upload('/media', photo);
assert.equal(full.status, 409);
assert.equal(full.body.error.code, 'STORAGE_FULL');
assert.equal((await as.get('/media')).body.storage.full, true);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from '../src/app.js';
import { createCtx, type Db } from '../src/context.js';
import { loadConfig } from '../src/lib/config.js';
import { appVersion } from '../src/lib/version.js';
type Version = { number: number; publishedAt: Date; snapshot: unknown };
/** Just what the app uses so far: a ping and the latest published version. */
function fakeDb(opts: { up?: boolean; versions?: Version[] } = {}): Db {
const versions = opts.versions ?? [];
return {
$queryRaw: async () => {
if (opts.up === false) throw new Error('down');
return [{ '?column?': 1 }];
},
siteVersion: {
findFirst: async () => [...versions].sort((a, b) => b.number - a.number)[0] ?? null,
},
} as unknown as Db;
}
const app = (db: Db) => createApp(createCtx(loadConfig({}), db));
describe('the app', () => {
it('answers /api/health with the product and version', async () => {
const res = await request(app(fakeDb())).get('/api/health');
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: 'ok', product: 'website', version: appVersion(), db: true });
});
it('says 503 when the database is down', async () => {
const res = await request(app(fakeDb({ up: false }))).get('/api/health');
assert.equal(res.status, 503);
assert.equal(res.body.db, false);
});
it('shows Coming soon until the first publish', async () => {
const res = await request(app(fakeDb())).get('/api/v1/site/status');
assert.deepEqual(res.body, { mode: 'coming-soon' });
});
it('shows the latest published version after it', async () => {
const at = new Date('2026-12-01T08:00:00Z');
const res = await request(app(fakeDb({ versions: [
{ number: 1, publishedAt: new Date('2026-11-30T08:00:00Z'), snapshot: { design: { template: 'heritage' } } },
{ number: 2, publishedAt: at, snapshot: { design: { template: 'clean' } } },
] }))).get('/api/v1/site/status');
assert.deepEqual(res.body, { mode: 'published', version: 2, publishedAt: at.toISOString(), template: 'clean' });
});
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
const res = await request(app(fakeDb())).get('/api/nothing');
assert.equal(res.status, 404);
assert.equal(res.body.error.code, 'NOT_FOUND');
assert.equal(res.headers['x-robots-tag'], 'noindex');
assert.equal(res.headers['x-powered-by'], undefined);
});
});
describe('config', () => {
it('refuses production without a secret', () => {
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /WEBSITE_SECRET/);
});
it('defaults to the development ports', () => {
const c = loadConfig({});
assert.equal(c.port, 5300);
assert.equal(c.publicUrl, 'http://localhost:3300');
});
});
@@ -0,0 +1,87 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { previewContent, siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { harness, SITE } from './support/harness.js';
async function site() {
const h = await harness({ linked: false });
const people = { ann: '00000000-0000-4000-8000-00000000000a', ben: '00000000-0000-4000-8000-00000000000b', lee: '00000000-0000-4000-8000-00000000000c' };
const kids = await h.db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const youth = await h.db.ministry.create({ data: { slug: 'youth', name: 'Youth' } });
await h.db.websiteUser.create({ data: { id: people.ann, name: 'Ann', email: 'ann@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.ben, name: 'Ben', email: 'ben@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.lee, name: 'Lee', email: 'lee@hope.test', role: 'ministry_leader', ministryId: kids.id } });
for (const [k, id] of Object.entries(people)) await h.db.session.create({ data: { tokenHash: hashToken(k), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const as = (who: keyof typeof people) => (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', `ccw_session=${who}`).set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, as, kids, youth };
}
describe('two editors at once (§4)', () => {
it("doesn't overwrite someone else's save, and says who", async () => {
const { as, db } = await site();
const page = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About' } });
const loaded = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
await new Promise((r) => setTimeout(r, 5));
assert.equal((await as('ben')('put', `/pages/${page.id}`, { title: "Ben's title", ifUpdatedAt: loaded })).status, 200);
const ann = await as('ann')('put', `/pages/${page.id}`, { title: "Ann's title", ifUpdatedAt: loaded });
assert.equal(ann.status, 409);
assert.match(ann.body.error.message, /^Ben changed this/);
assert.equal((await as('ann')('get', `/pages/${page.id}`)).body.title, "Ben's title");
// Her own earlier save never blocks her.
const fresh = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'One', ifUpdatedAt: fresh })).status, 200);
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'Two', ifUpdatedAt: fresh })).status, 200);
});
});
describe("a Ministry leader's events (§10)", () => {
it('adds and changes their own ministry\'s events only, and an Editor publishes them', async () => {
const { as, kids, youth } = await site();
const startsAt = new Date(Date.now() + 864e5).toISOString();
assert.equal((await as('lee')('post', '/events', { title: 'Youth night', startsAt, ministryId: youth.id })).status, 403);
assert.equal((await as('lee')('post', '/events', { title: 'No ministry', startsAt })).status, 403);
const mine = await as('lee')('post', '/events', { title: 'Kids party', startsAt, ministryId: kids.id });
assert.equal(mine.status, 200);
assert.equal((await as('lee')('put', `/events/${mine.body.id}`, { title: 'Kids party!', startsAt, ministryId: kids.id })).status, 200);
assert.equal((await as('lee')('post', `/events/${mine.body.id}/state`, { published: true })).status, 403);
const other = await as('ann')('post', '/events', { title: 'Picnic', startsAt });
assert.equal((await as('lee')('put', `/events/${other.body.id}`, { title: 'Mine now', startsAt, ministryId: kids.id })).status, 403);
assert.equal((await as('ann')('post', `/events/${mine.body.id}/state`, { published: true })).status, 200);
});
});
describe('choosing a template with the church\'s own content', () => {
it('previews the content in another template without saving anything', async () => {
const { ctx, db, as, app } = await site();
await db.siteDesign.create({ data: { id: 1, template: 'heritage', variants: {}, home: [], style: {} } });
const c = await previewContent(ctx, { asTemplate: 'bold' });
assert.equal(c.mode === 'published' && c.snapshot.design.template, 'bold');
assert.equal((await as('ann')('get', '/design')).body.design.template, 'heritage', 'nothing saved');
const viaHeader = await request(app).get('/api/v1/site/preview').set('Cookie', 'ccw_session=ann').set('x-preview-template', 'clean');
assert.equal(viaHeader.body.snapshot.design.template, 'clean');
assert.equal(viaHeader.body.preview.canPublish, false, 'no publishing from a try-on');
});
});
describe('an address that changed (§6)', () => {
it('sends the old address on to the new one once published', async () => {
const { ctx, db, as } = await site();
const page = await db.page.create({ data: { kind: 'custom', slug: 'youth-camp', title: 'Youth camp' } });
await as('ann')('put', `/pages/${page.id}`, { slug: 'camp' });
await as('ann')('put', `/pages/${page.id}`, { slug: 'summer-camp' });
await publish(ctx, { id: 'x', role: 'system' });
const c = await siteContent(ctx);
assert.deepEqual(c.mode === 'published' && c.snapshot.redirects, { 'youth-camp': '/summer-camp', camp: '/summer-camp' });
// A new page taking an old address wins over its redirect.
await db.page.create({ data: { kind: 'custom', slug: 'camp', title: 'Camp info' } });
await publish(ctx, { id: 'x', role: 'system' });
const after = await siteContent(ctx);
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
});
});
+175
View File
@@ -0,0 +1,175 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema, eventSchema } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { hashToken } from '../src/lib/crypto.js';
import { buildFeed, syncLink } from '../src/feed/feed.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { harness, INSTALL_ID, SITE } from './support/harness.js';
const EVENTS_ID = '5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e';
const SECRET = 'events-link-secret-0123456789abcdef';
/** A Cross Events event, as its feed sends it. */
function ev(id: string, title: string, inDays: number, over: Record<string, unknown> = {}) {
const start = new Date(Date.now() + inDays * 864e5);
return {
schema: EVENT_SCHEMA, id, origin: { product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${id.slice(0, 4)}` },
status: 'published', updatedAt: new Date().toISOString(), title, summary: null, description: null, imageUrl: null, timezone: 'Africa/Johannesburg',
startsAt: start.toISOString(), endsAt: new Date(start.getTime() + 3600e3).toISOString(), allDay: false, sessions: [], location: { name: 'The hall', address: null, onlineUrl: null },
campus: null, series: null, tags: [], registration: { mode: 'origin', url: `https://events.hope.test/events/${id.slice(0, 4)}`, status: 'open', opensAt: null, closesAt: null, priceFrom: { amountCents: 45000, currency: 'ZAR' } },
...over,
};
}
/** A Cross Events site: serves whatever feed the test sets, and records what it's told. */
async function fakeEvents() {
const state = { feed: null as unknown, status: 200, asked: [] as string[], told: [] as { headers: http.IncomingHttpHeaders; body: string }[] };
const app = express();
app.get('/api/feed/v1/events', (req, res) => { state.asked.push(req.url); res.status(state.status).json(state.feed); });
app.post('/api/feed/v1/changed', express.text({ type: () => true }), (req, res) => { state.told.push({ headers: req.headers, body: req.body }); res.status(202).json({ accepted: true }); });
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, state };
}
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
async function site() {
const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true' } });
const events = await fakeEvents();
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: events.url, publicKey: 'x', secret: h.ctx.secrets.encrypt(SECRET), connectedAt: new Date() } });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000001', name: 'O', email: 'o@hope.test', role: 'owner' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000001', expiresAt: new Date(Date.now() + 864e5) } });
await publish(h.ctx, { id: 'x', role: 'system' });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
const link = async () => (await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } })) as unknown as Parameters<typeof syncLink>[1];
return { ...h, events, go, link };
}
describe('publishing the Website\'s events (Publish my events)', () => {
it('serves its published simple events as crosscode.event/1, removed ones as deleted', async () => {
const { go, app } = await site();
const start = new Date(Date.now() + 5 * 864e5).toISOString();
const a = (await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/p' })).body;
const b = (await go('post', '/events', { title: 'Carols', startsAt: start })).body;
await go('post', `/events/${a.id}/state`, { published: true });
await go('post', `/events/${b.id}/state`, { published: true });
const feed = (await request(app).get('/api/feed/v1/events')).body;
assert.ok(eventFeedSchema.safeParse(feed).success);
assert.equal(feed.events.length, 2);
const picnic = feed.events.find((e: { title: string }) => e.title === 'Picnic');
assert.ok(eventSchema.safeParse(picnic).success);
assert.deepEqual(picnic.origin, { product: 'website', installId: INSTALL_ID, url: `${SITE}/events/picnic` });
assert.deepEqual([picnic.registration.mode, picnic.registration.url], ['external', 'https://forms.example/p']);
const before = new Date().toISOString();
await go('post', `/events/${b.id}/state`, { published: false });
const since = (await request(app).get(`/api/feed/v1/events?updatedSince=${encodeURIComponent(before)}`)).body;
assert.deepEqual(since.deleted.map((d: { id: string }) => d.id), [b.id]);
assert.equal(since.events.length, 0, 'nothing else changed since');
assert.equal((await request(app).get('/api/feed/v1/events?updatedSince=nonsense')).status, 400);
await go('put', '/feed', { publish: false });
assert.equal((await request(app).get('/api/feed/v1/events')).status, 404);
});
it('tells the church\'s Events, signed, when one of its events changes', async () => {
const { go, events } = await site();
const e = (await go('post', '/events', { title: 'Picnic', startsAt: new Date(Date.now() + 864e5).toISOString() })).body;
await go('post', `/events/${e.id}/state`, { published: true });
await new Promise((r) => setTimeout(r, 200));
const told = events.state.told.at(-1)!;
assert.equal(told.headers[LINK_HEADERS.sender], INSTALL_ID);
assert.deepEqual(JSON.parse(told.body).eventIds, [e.id]);
});
});
describe('showing events from Cross Events (Show events from)', () => {
it('imports only its own, valid events; they show on the site and link back to Events', async () => {
const { ctx, events, link, db } = await site();
events.state.feed = {
schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [],
events: [
ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10),
ev('7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a', 'From someone else', 4, { origin: { product: 'events', installId: '00000000-0000-4000-8000-0000000000ff', url: 'https://other.test/e' } }),
{ ...ev('8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b', 'Broken', 3), startsAt: 'not a date' },
],
};
const r = await syncLink(ctx, await link());
assert.deepEqual([r.ok, r.imported, r.rejected], [true, 1, 1]);
const c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 1);
if (c.mode === 'published') {
assert.equal(c.events[0]!.title, 'Youth camp');
assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d');
assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 });
}
assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/);
});
it('asks only for what changed next time, drops deleted ones, and keeps the last good copy when Events is down', async () => {
const { ctx, events, link, db } = await site();
const id = '6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f';
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev(id, 'Youth camp', 10)] };
await syncLink(ctx, await link());
events.state.status = 503;
const down = await syncLink(ctx, await link());
assert.equal(down.ok, false);
assert.equal(await db.importedEvent.count(), 1, 'the last good copy stays');
assert.match(events.state.asked.at(-1)!, /updatedSince=/);
events.state.status = 200;
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [{ id, deletedAt: new Date().toISOString() }], events: [] };
await syncLink(ctx, await link());
assert.equal(await db.importedEvent.count(), 0);
});
it('switching Show events off removes its events; a signed event.changed fetches at once', async () => {
const { ctx, events, link, db, go, app } = await site();
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10)] };
await syncLink(ctx, await link());
await go('put', `/links/${EVENTS_ID}`, { showEvents: false });
assert.equal(await db.importedEvent.count(), 0);
await go('put', `/links/${EVENTS_ID}`, { showEvents: true });
assert.equal(await db.importedEvent.count(), 1);
const body = JSON.stringify({ schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [] });
const asked = events.state.asked.length;
const ok = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: SECRET, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(ok.status, 202);
await new Promise((r) => setTimeout(r, 200));
assert.equal(events.state.asked.length, asked + 1);
const forged = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: 'wrong-secret-0123456789abcdefghij', rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(forged.status, 401);
const links = (await go('get', '/links')).body;
assert.equal(links.products.find((p: { product: string }) => p.product === 'events').events, 1);
});
it('takes church.changed only from Accounts, signed', async () => {
const { app, db, ctx } = await site();
const accounts = (await db.productLink.findFirst({ where: { product: 'accounts' } }))!;
const body = JSON.stringify({ schema: 'crosscode.church/1', type: 'church.changed', occurredAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
const send = (sender: string, secret: string) => request(app).post('/api/church/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: sender, secret, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal((await send(String(accounts.installId), ctx.secrets.decrypt(String(accounts.secret)))).status, 202);
assert.equal((await send(EVENTS_ID, SECRET)).status, 404, 'Events isn\'t Accounts');
});
});
describe('the feed builder', () => {
it('leaves out events that ended over 30 days ago', async () => {
const { ctx, db } = await site();
await db.simpleEvent.create({ data: { slug: 'old', title: 'Old', startsAt: new Date(Date.now() - 40 * 864e5), publishedAt: new Date() } });
assert.equal((await buildFeed(ctx, null)).events.length, 0);
});
});
@@ -0,0 +1,111 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { parseFeed, parseSource, syncYoutube } from '../src/site/youtube.js';
import { harness, SITE } from './support/harness.js';
const FEED = `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:yt="http://www.youtube.com/xml/schemas/2015" xmlns:media="http://search.yahoo.com/mrss/" xmlns="http://www.w3.org/2005/Atom">
<title>Hope Family Church</title>
<entry>
<id>yt:video:abcDEF12345</id>
<yt:videoId>abcDEF12345</yt:videoId>
<title>Hope &amp; joy | Sunday 23 Nov</title>
<published>2026-11-23T08:00:00+00:00</published>
<media:group><media:thumbnail url="https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg" width="480" height="360"/></media:group>
</entry>
<entry>
<yt:videoId>zzzYYY98765</yt:videoId>
<title>Bread for the road</title>
<published>2026-11-16T08:00:00+00:00</published>
</entry>
<entry><title>No id</title><published>2026-11-01T08:00:00+00:00</published></entry>
</feed>`;
async function signedIn() {
const h = await harness({ linked: false });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000003', name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000003', expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
await publish(h.ctx, { id: 'x', role: 'system' });
return { ...h, go };
}
describe('messages from YouTube (§7)', () => {
it('reads a channel id, a channel address or a playlist', () => {
assert.deepEqual(parseSource('UCaBcDeFgHiJkLmNoPqRsTuV'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/channel/UCaBcDeFgHiJkLmNoPqRsTuV/videos'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/playlist?list=PLabcdefghij123'), { kind: 'playlist', id: 'PLabcdefghij123' });
assert.equal(parseSource('https://www.youtube.com/@hopefamily'), null);
});
it('parses the feed, leaving out entries it can\'t use', () => {
const v = parseFeed(FEED);
assert.equal(v.length, 2);
assert.equal(v[0]!.title, 'Hope & joy | Sunday 23 Nov');
assert.equal(v[0]!.thumbnail, 'https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg');
});
it('adds new videos as live messages, once, and says when YouTube can\'t be reached', async () => {
const h = await harness({ linked: false });
await h.ctx.settings.set('youtube_source', JSON.stringify({ kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' }));
let asked = '';
const ok = async (u: string) => { asked = u; return { ok: true, status: 200, text: async () => FEED }; };
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 2 });
assert.equal(asked, 'https://www.youtube.com/feeds/videos.xml?channel_id=UCaBcDeFgHiJkLmNoPqRsTuV');
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 0 });
await publish(h.ctx, { id: 'x', role: 'system' });
const c = await siteContent(h.ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.title, 'Hope & joy | Sunday 23 Nov');
const down = await syncYoutube(h.ctx, async () => ({ ok: false, status: 503, text: async () => '' }));
assert.match(String(down.error), /503/);
assert.match(String(await h.ctx.settings.get('youtube_last_error')), /503/);
});
});
describe('messages and events in the admin (decision 9)', () => {
it('adds a message by link, publishes it on its own, and refuses a duplicate or a stranger link', async () => {
const { go, ctx } = await signedIn();
const m = await go('post', '/messages', { title: 'Grace', date: '2026-11-22', mediaUrl: 'https://youtu.be/abcDEF12345', speaker: 'Thandi', series: 'Hope' });
assert.equal(m.status, 200);
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages.length, 0, 'not live until its own Publish');
await go('post', `/messages/${m.body.id}/publish`, { live: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.series, 'Hope');
assert.equal((await go('post', '/messages', { title: 'Again', date: '2026-11-22', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345' })).body.error.code, 'DUPLICATE');
assert.equal((await go('post', '/messages', { title: 'X', date: '2026-11-22', mediaUrl: 'https://evil.example/v' })).status, 400);
const spotify = await go('post', '/messages', { title: 'Podcast', date: '2026-11-22', mediaUrl: 'https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk' });
assert.equal(spotify.body.source, 'spotify');
});
it('keeps a feed message from being deleted (it would come back): hide it instead', async () => {
const { go, db } = await signedIn();
const row = await db.message.create({ data: { slug: 'x', title: 'From YouTube', date: new Date(), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345', externalId: 'abcDEF12345' } });
assert.equal((await go('delete', `/messages/${row.id}`)).body.error.code, 'FROM_FEED');
});
it('creates, publishes, cancels and removes a simple event', async () => {
const { go, ctx } = await signedIn();
const start = new Date(Date.now() + 7 * 864e5).toISOString();
const bad = await go('post', '/events', { title: 'Picnic', startsAt: start, endsAt: new Date(Date.now()).toISOString() });
assert.ok(bad.body.error.fields.endsAt);
const e = await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/picnic' });
assert.equal(e.status, 200);
assert.equal(e.body.slug, 'picnic');
await go('post', `/events/${e.body.id}/state`, { published: true });
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events[0]!.url, 'https://forms.example/picnic');
await go('post', `/events/${e.body.id}/state`, { cancelled: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 0);
assert.equal((await go('delete', `/events/${e.body.id}`)).status, 200);
assert.equal((await go('get', '/events')).body.length, 0);
});
});
+198
View File
@@ -0,0 +1,198 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { churchExportSchema, hub, INTERNAL_ID_KEYS, LINK_SCHEMA, linkConnectSchema, type LinkConnected } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import { buildExport } from '../src/export/churchExport.js';
import { stats } from '../src/hub/client.js';
import { connectAccountsIfListed } from '../src/links/connect.js';
import { keyPair, saveLinkedProducts } from '../src/links/store.js';
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID, SITE } from './support/harness.js';
const accountsKeys = generateEd25519();
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
/** The church's Accounts, accepting a connect as apps/accounts/backend/src/links/connect.ts does. */
async function fakeAccounts(websitePublicKey: () => Promise<string>, opts: { badSignature?: boolean } = {}) {
const app = express();
const seen: unknown[] = [];
app.post('/api/links/v1/connect', express.json(), async (req, res) => {
const m = linkConnectSchema.parse(req.body);
seen.push(m);
if (!verifyLink(m as unknown as Record<string, unknown>, await websitePublicKey()).ok) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
const reply = signLink<Omit<LinkConnected, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connected', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: `http://127.0.0.1:${port}` },
to: { installId: m.from.installId }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, opts.badSignature ? generateEd25519().privateKeyPem : accountsKeys.privateKeyPem);
return res.json(reply);
});
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const port = (server.address() as AddressInfo).port;
return { url: `http://127.0.0.1:${port}`, seen, close: () => new Promise((r) => server.close(r)) };
}
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
describe('linking to the church\'s Accounts', () => {
it('connects by itself once the Hub lists an Accounts, with a secret both sides keep', async () => {
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'nothing listed yet');
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
assert.equal(await connectAccountsIfListed(h.ctx), 'connected');
const link = await h.db.productLink.findUnique({ where: { installId: ACCOUNTS_INSTALL_ID } });
assert.equal(link!.product, 'accounts');
const sent = accounts.seen[0] as { secret: string; from: { product: string; installId: string } };
assert.equal(sent.from.product, 'website');
assert.equal(sent.from.installId, INSTALL_ID);
assert.equal(h.ctx.secrets.decrypt(String(link!.secret)), sent.secret);
assert.notEqual(link!.secret, sent.secret, 'stored encrypted');
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'already linked');
assert.equal(accounts.seen.length, 1);
});
it('doesn\'t keep a link whose answer isn\'t signed with the key the Hub listed', async () => {
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem, { badSignature: true });
closers.push(accounts.close);
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
assert.equal(await connectAccountsIfListed(h.ctx), 'failed');
assert.equal(await h.db.productLink.count(), 0);
});
it('accepts a connect from a listed sibling signed with its key, once', async () => {
const h = await harness({ linked: false });
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test', publicKey: accountsPublic }]);
const message = () => signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test' },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, accountsKeys.privateKeyPem);
const m = message();
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200);
assert.equal(res.body.type, 'link.connected');
assert.ok(verifyLink(res.body, (await keyPair(h.ctx)).publicKeyPem).ok);
assert.equal(await h.db.productLink.count(), 1);
assert.equal((await request(h.app).post('/api/links/v1/connect').send(m)).body.code, 'REPLAYED');
const forged = { ...message(), signature: message().signature };
assert.equal((await request(h.app).post('/api/links/v1/connect').send(forged)).status, 401);
});
});
/** A Hub answering heartbeats with `list` as the church's products (only what the Website reads). */
async function fakeHub(list: () => unknown[]) {
const calls: string[] = [];
const server = http.createServer((req, res) => {
calls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: list() }));
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, calls };
}
describe('1.0.2: linking right after an install', () => {
it('links to Accounts when someone opens /admin, asking the Hub for a fresh list first', async () => {
let accountsUrl = '';
const hubServer = await fakeHub(() => [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accountsUrl, publicKey: accountsPublic }]);
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true', HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
accountsUrl = accounts.url;
// The Website's cached list has no Accounts yet (it registered before the Hub knew of one).
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//, 'off to Accounts, not the problem page');
assert.deepEqual(hubServer.calls, ['/api/installs/heartbeat']);
assert.equal(accounts.seen.length, 1, 'one connect, not one from the heartbeat and another from the sign-in');
assert.equal(await h.db.productLink.count({ where: { product: 'accounts' } }), 1);
});
it('tries again at most every 15 seconds while it can\'t link', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const hubServer = await fakeHub(() => []);
const h = await harness({ linked: false, env: { HUB_URL: hubServer.url } });
h.ctx.now = () => clock;
await h.ctx.settings.set('hub_install_secret', 'secret');
const problem = `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`;
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal(hubServer.calls.length, 1);
clock = new Date(clock.getTime() + 61_000);
await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(hubServer.calls.length, 2);
});
it('accepts a connect from a product installed after its last heartbeat (Events, for the event feed)', async () => {
const EVENTS_INSTALL_ID = '4d2e8f3a-9b1c-4d0e-8f7a-6b5c4d3e2f1a';
const eventsKeys = generateEd25519();
const events = { product: 'events', installId: EVENTS_INSTALL_ID, url: 'https://events.hope.test', publicKey: ed25519PublicToPem(eventsKeys.publicKey) };
const hubServer = await fakeHub(() => [events]);
const h = await harness({ env: { HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const m = signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'events', installId: EVENTS_INSTALL_ID, url: events.url },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, eventsKeys.privateKeyPem);
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(hubServer.calls.length, 1);
assert.equal(await h.db.productLink.count({ where: { product: 'events' } }), 1);
});
});
describe('the heartbeat and the export', () => {
it('reports aggregate counts the Hub accepts', async () => {
const h = await harness();
await h.db.mediaAsset.create({ data: { filename: 'hero.jpg', mime: 'image/jpeg', bytes: 1200 } });
await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
const s = await stats(h.ctx);
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
assert.equal(s.storage.usedBytes, 1200);
assert.deepEqual(s.pages, { published: 0, drafts: 1 });
});
it('exports the content in crosscode.church-export/1, without internal ids', async () => {
const h = await harness();
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: {}, home: [], style: { spacing: 'airy' } } });
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
await h.db.section.create({ data: { pageId: home.id, type: 'hero', variant: 'text', data: { headline: 'Welcome home' } } });
const img = await h.db.mediaAsset.create({ data: { filename: '2026/hero.jpg', mime: 'image/jpeg', bytes: 1200, alt: 'The hall' } });
await h.db.simpleEvent.create({ data: { slug: 'picnic', title: 'Picnic', startsAt: new Date('2026-12-05T08:00:00Z'), imageId: img.id, publishedAt: new Date() } });
await h.db.message.create({ data: { slug: 'hope', title: 'Hope', date: new Date('2026-11-22T08:00:00Z'), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abc' } });
await h.db.websiteUser.create({ data: { id: '11111111-1111-4111-8111-111111111111', name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
await h.db.siteVersion.create({ data: { number: 1, snapshot: {}, publishedBy: '11111111-1111-4111-8111-111111111111', note: 'First' } });
const data = await buildExport(h.ctx);
assert.ok(churchExportSchema.safeParse(data).success);
const w = data.website!;
assert.equal(w.template, 'clean');
assert.equal(w.pages[0]!.path, '/');
assert.deepEqual(w.pages[0]!.sections[0], { type: 'hero', variant: 'text', hidden: false, content: { headline: 'Welcome home' } });
assert.equal(w.events[0]!.image, 'uploads/2026/hero.jpg');
assert.equal(w.messages[0]!.source, 'youtube-feed');
assert.deepEqual(w.versions[0], { number: 1, publishedAt: w.versions[0]!.publishedAt, by: 'Sam', note: 'First' });
assert.equal(data.people[0]!.role, 'website owner');
const keys: string[] = [];
const walk = (x: unknown) => {
if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') for (const [k, v] of Object.entries(x)) { keys.push(k); walk(v); }
};
walk({ ...data, website: { ...w, pages: w.pages.map((p) => ({ ...p, sections: p.sections.map((s) => ({ ...s, content: {} })) })) } });
assert.deepEqual(keys.filter((k) => INTERNAL_ID_KEYS.test(k)), []);
});
});
@@ -0,0 +1,175 @@
// 1.4.0: database backups (Settings → Backups) and the background jobs (Settings → Background
// jobs), as Accounts and Cross Events; the heartbeat reports both to the Hub.
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import zlib from 'node:zlib';
import request from 'supertest';
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, runBackupJob, type Dumper } from '../src/backups/backups.js';
import { health } from '../src/hub/client.js';
import { JOBS, cronFor, isEnabled, jobsHealth, runNow, useEnvForTest } from '../src/jobs.js';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor';
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
after(() => useEnvForTest(process.env));
async function site() {
const h = await harness({ linked: false });
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-backups-'));
h.ctx.config.backupDir = dir;
h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/website_test';
const as = async (role: Role) => {
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor'].indexOf(role) + 1}`;
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const cookie = `ccw_session=token-${role}`;
return {
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
};
};
return { ...h, dir, as };
}
describe('backups (1.4.0)', () => {
it('a backup is the gzipped dump, named as the crosscode script names them', async () => {
const h = await site();
const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Page" ();\n'));
assert.match(b.filename, BACKUP_FILE);
assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(h.dir, b.filename))).toString(), 'CREATE TABLE "Page" ();\n');
assert.equal(backupName(new Date(2026, 10, 27, 2, 20, 5)), 'website-20261127-022005.sql.gz');
const again = await runBackup(h.ctx, dumpOf('-- again\n'));
assert.notEqual(again.filename, b.filename, 'a second one in the same second gets its own name');
});
it('a dump that fails part-way leaves no file, and says why', async () => {
const h = await site();
await assert.rejects(runBackup(h.ctx, failing), /connection refused/);
assert.equal((await listBackups(h.ctx)).length, 0);
assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/);
await runBackup(h.ctx, dumpOf('-- fine\n'));
assert.equal(await h.ctx.settings.get('backup_last_error'), null);
});
it('only the newest are kept; a download only by a backup\'s own name', async () => {
const h = await site();
await h.ctx.settings.set('backup_retain_count', '2');
for (const n of [1, 2, 3]) await runBackup(h.ctx, dumpOf(`-- ${n}\n`));
const left = await listBackups(h.ctx);
assert.equal(left.length, 2);
assert.ok(backupPath(h.ctx, left[0]!.filename));
assert.equal(backupPath(h.ctx, '../.env'), null);
assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null);
});
it('the nightly backup is skipped while it\'s turned off', async () => {
const h = await site();
await h.ctx.settings.set('backup_nightly', 'false');
assert.deepEqual(await runBackupJob(h.ctx), { skipped: true });
});
it('admins see, change and download them; editors can\'t', async () => {
const h = await site();
await runBackup(h.ctx, dumpOf('-- a backup\n'));
const editor = await h.as('editor');
assert.equal((await editor.get('/backups')).status, 403);
assert.equal((await editor.post('/backups/run')).status, 403);
assert.equal((await editor.get('/pages')).status, 200, 'the admin-only routes don\'t stop the others');
const admin = await h.as('admin');
const list = await admin.get('/backups');
assert.equal(list.status, 200, JSON.stringify(list.body));
assert.equal(list.body.nightly, true);
assert.equal(list.body.retain, 14);
const file = await admin.get(`/backups/${list.body.items[0].filename}/download`).buffer(true).parse((res, cb) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => cb(null, Buffer.concat(chunks)));
});
assert.equal(file.status, 200);
assert.equal(file.headers['cache-control'], 'no-store');
assert.equal(zlib.gunzipSync(file.body as Buffer).toString(), '-- a backup\n');
assert.equal((await admin.get('/backups/nope.sql.gz/download')).status, 404);
assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1);
assert.equal((await admin.put('/backups/settings', { retain: 0, nightly: true })).status, 400);
const saved = await admin.put('/backups/settings', { retain: 30, nightly: false });
assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 });
assert.equal(await h.ctx.settings.bool('backup_nightly', true), false);
});
it('the heartbeat reports the newest backup and the real job mode (before: null, so the Hub warned)', async () => {
const h = await site();
assert.equal((await health(h.ctx)).lastBackupAt, null);
await runBackup(h.ctx, dumpOf('-- x\n'));
const report = await health(h.ctx);
assert.ok(report.lastBackupAt && Date.parse(report.lastBackupAt) > Date.now() - 60e3);
assert.deepEqual(report.jobs, await jobsHealth(h.ctx));
assert.equal(report.jobs.mode, 'off', 'no job system started in the tests');
});
});
describe('background jobs (1.4.0)', () => {
const backup = JOBS.find((j) => j.name === 'backup')!;
it('the heartbeat, the event feed, YouTube and the backup are jobs', () => {
assert.deepEqual(JOBS.map((j) => j.name).sort(), ['backup', 'event-feed', 'hub-heartbeat', 'youtube']);
});
it('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
const h = await site();
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
h.ctx.config.jobsEnabled = true; // nothing is started here either way
const admin = await h.as('admin');
type Row = { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } };
let job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, false);
assert.equal(job.cron, '30 1 * * *');
assert.deepEqual(job.override, { enabled: null, cron: null });
const on = await admin.put('/jobs/backup', { enabled: true, cron: '0 3 * * *' });
assert.equal(on.status, 200, JSON.stringify(on.body));
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 * * *');
job = ((await admin.get('/jobs')).body.jobs as Row[]).find((j) => j.name === 'backup')!;
assert.equal(job.enabled, true);
assert.equal(job.envEnabled, false);
const back = await admin.put('/jobs/backup', { enabled: null, cron: null });
assert.deepEqual(back.body.override, { enabled: null, cron: null });
assert.equal(isEnabled(h.ctx, backup), false);
assert.equal(await h.db.auditLog.count({ where: { action: 'job_settings_changed' } }), 2);
useEnvForTest(process.env);
});
it('a bad schedule, a bad switch and an unknown job are refused; editors can\'t change jobs', async () => {
const h = await site();
const admin = await h.as('admin');
assert.equal((await admin.put('/jobs/backup', { cron: 'every night' })).status, 400);
assert.equal((await admin.put('/jobs/backup', { enabled: 'yes' })).status, 400);
assert.equal((await admin.put('/jobs/nope', { enabled: true })).status, 404);
const editor = await h.as('editor');
assert.equal((await editor.get('/jobs')).status, 403);
assert.equal((await editor.put('/jobs/backup', { enabled: false })).status, 403);
});
it('running one now runs it here (no queue in the tests) and remembers the run', async () => {
const h = await site();
h.ctx.config.databaseUrl = null;
await assert.rejects(runNow(h.ctx, 'backup'), /DATABASE_URL/);
const admin = await h.as('admin');
const ran = await admin.post('/jobs/youtube/run');
assert.equal(ran.status, 200, JSON.stringify(ran.body));
assert.deepEqual(ran.body, { queued: false, output: { added: 0, skipped: 'no source' } });
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
/** A site linked to Accounts, with an Owner and an Admin signed in (each with their own cookie). */
async function site() {
const h = await harness();
const people: Record<string, { id: string; cookie: string }> = {};
for (const [n, role] of (['owner', 'admin', 'editor'] as Role[]).entries()) {
const id = `00000000-0000-4000-8000-00000000000${n + 1}`;
await h.db.websiteUser.create({ data: { id, name: role, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`t-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
people[role] = { id, cookie: `ccw_session=t-${role}` };
}
const as = (role: string) => ({
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie),
post: (p: string, b: object) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
put: (p: string, b: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE),
});
return { ...h, people, as };
}
describe('who can use the admin (§10)', () => {
it('adds someone by email through Accounts, who can then sign in with that role', async () => {
const { as, fake, db } = await site();
const r = await as('admin').post('/people', { name: 'New Editor', email: 'New@Hope.test', role: 'editor' });
assert.equal(r.status, 200);
assert.equal(r.body.newAccount, true);
assert.deepEqual(fake.requests[0], { type: 'people.ensure', actor: '00000000-0000-4000-8000-000000000002', name: 'New Editor', email: 'new@hope.test', phone: null, returnUrl: `${SITE}/admin` });
const u = await db.websiteUser.findUnique({ where: { id: r.body.id } });
assert.equal(u!.role, 'editor');
assert.equal((await as('admin').post('/people', { name: 'Again', email: 'new@hope.test', role: 'viewer' })).body.error.code, 'ALREADY_ADDED');
const list = (await as('owner').get('/people')).body;
assert.equal(list.length, 4);
});
it('needs a ministry for a Ministry leader', async () => {
const { as, db } = await site();
assert.equal((await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader' })).status, 400);
const m = await db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const r = await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader', ministryId: m.id });
assert.equal(r.status, 200);
assert.equal((await as('admin').get('/people')).body.find((p: { id: string }) => p.id === r.body.id).ministry, 'Kids');
});
it('keeps Owners to Owners, and nobody changes themselves', async () => {
const { as, people } = await site();
assert.equal((await as('admin').post('/people', { name: 'O', email: 'o@hope.test', role: 'owner' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').del(`/people/${people.owner!.id}`)).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('owner').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'SELF');
assert.equal((await as('editor').get('/people')).status, 403);
assert.equal((await as('owner').post('/people', { name: 'Second owner', email: 'o@hope.test', role: 'owner' })).status, 200);
});
it('a lower role takes effect at once; removing someone ends their sessions', async () => {
const { as, people, db } = await site();
assert.equal((await as('owner').put(`/people/${people.editor!.id}`, { role: 'viewer' })).status, 200);
assert.equal(await db.session.count({ where: { userId: people.editor!.id } }), 0);
assert.equal((await as('owner').del(`/people/${people.admin!.id}`)).status, 200);
assert.equal(await db.websiteUser.count({ where: { id: people.admin!.id } }), 0);
assert.equal((await as('admin').get('/people')).status, 401);
});
});
@@ -0,0 +1,82 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { harness, SITE } from './support/harness.js';
async function site(role: 'owner' | 'editor' | 'viewer' = 'owner') {
const h = await harness();
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, go, id };
}
describe("the church's shared details, saved through Accounts (decision 10)", () => {
it('sends only what changed, as the signed-in admin', async () => {
const { go, fake, id } = await site();
const r = await go('put', '/church', { church: { serviceTimes: [{ day: 'sunday', time: '09:30', label: 'Morning', campus: null, note: null }] }, ifUpdatedAt: '2026-11-25T08:00:00.000Z' });
assert.equal(r.status, 200);
const sent = fake.requests.at(-1)!;
assert.equal(sent.type, 'church.update');
assert.equal(sent.actor, id);
assert.deepEqual(Object.keys(sent.church!), ['serviceTimes']);
});
it('says so when someone changed the profile in between, and checks the fields first', async () => {
const { go } = await site();
const stale = await go('put', '/church', { church: { name: 'Hope' }, ifUpdatedAt: '2000-01-01T00:00:00.000Z' });
assert.equal(stale.body.error.code, 'PROFILE_CHANGED');
const bad = await go('put', '/church', { church: { contact: { email: null, phone: '012 345', whatsapp: null, address: null } } });
assert.equal(bad.status, 400);
assert.ok(bad.body.error.fields['contact.phone']);
});
it("is an Editor's job, not a Viewer's", async () => {
const { go } = await site('viewer');
assert.equal((await go('put', '/church', { church: { name: 'X' } })).status, 403);
});
});
describe('settings, the menu and the audit log', () => {
it('takes a verification code, or the whole meta tag, and the site shows it', async () => {
const { go, ctx } = await site();
const r = await go('put', '/settings', { googleVerification: '<meta name="google-site-verification" content="abc123XYZ_-" />', bingVerification: 'B1NGcode99', comingSoonText: 'Opening at Easter.' });
assert.equal(r.status, 200);
assert.equal(r.body.googleVerification, 'abc123XYZ_-');
const c = await siteContent(ctx);
assert.deepEqual(c.verification, { google: 'abc123XYZ_-', bing: 'B1NGcode99' });
assert.equal(c.mode === 'coming-soon' && c.comingSoonText, 'Opening at Easter.');
assert.equal((await go('put', '/settings', { googleVerification: '<script>' })).status, 400);
});
it('sets the site icon from the media library, live at once, and takes it off again', async () => {
const { go, ctx, db } = await site();
assert.equal((await siteContent(ctx)).favicon, null, 'none: the site uses its default');
const m = await db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 100, width: 512, height: 512 } });
assert.equal((await go('put', '/settings', { faviconId: '00000000-0000-4000-8000-0000000000ff' })).body.error.fields.faviconId, 'That picture isn\'t in the media library');
const r = await go('put', '/settings', { faviconId: m.id });
assert.equal(r.body.faviconId, m.id);
assert.equal((await siteContent(ctx)).favicon, '/api/uploads/icon.png');
assert.equal((await go('put', '/settings', { faviconId: null })).body.faviconId, null);
assert.equal((await siteContent(ctx)).favicon, null);
});
it('orders the menu, and the audit log says who did what', async () => {
const { go, db } = await site();
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
const b = await db.page.create({ data: { kind: 'give', slug: 'give', title: 'Give', position: 2 } });
assert.equal((await go('put', '/pages-order', { ids: [b.id, a.id] })).status, 200);
assert.deepEqual((await go('get', '/pages')).body.map((p: { slug: string }) => p.slug), ['give', 'about']);
await go('put', '/settings', { comingSoonText: 'Soon.' });
const log = (await go('get', '/audit')).body;
assert.deepEqual([log[0].who, log[0].action], ['Sam', 'Changed the settings']);
const overview = (await go('get', '/overview')).body;
assert.equal(overview.recent[0].action, 'Changed the settings');
});
});
+171
View File
@@ -0,0 +1,171 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { cookieHeader, cookiesFrom, harness, SITE } from './support/harness.js';
const OWNER = '11111111-1111-4111-8111-111111111111';
const OTHER = '22222222-2222-4222-8222-222222222222';
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
async function signIn(h: Awaited<ReturnType<typeof harness>>, returnTo = '/admin/pages?x=1', cookies: Record<string, string> = {}, mfa = false) {
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
assert.equal(start.status, 303);
const after = cookiesFrom(start, cookies);
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
return { start, back, cookies: cookiesFrom(back, after) };
}
describe('signing in to the admin through Accounts', () => {
it('sends people to Accounts with the page they were on', async () => {
const h = await harness();
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin%2Fpages');
assert.equal(res.status, 303);
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//);
assert.deepEqual(h.fake.started, [{ returnTo: '/admin/pages', requireTwoFactor: false }]);
assert.match(String(res.headers['set-cookie']), /ccw_signin=.*Path=\/api\/auth.*HttpOnly/);
});
it('refuses a foreign return address (back to the home page instead)', async () => {
const h = await harness();
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
assert.equal(h.fake.started[0]!.returnTo, '/');
});
it('says so when the Website isn\'t linked to Accounts yet', async () => {
const h = await harness({ linked: false });
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`);
});
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
const h = await harness();
h.fake.next = { sub: OWNER, email: 'Pastor@Hope.test' };
const { back, cookies } = await signIn(h);
assert.equal(back.headers.location, `${SITE}/admin/pages?x=1`);
assert.ok(cookies.ccw_session);
assert.match(String(back.headers['set-cookie']), /ccw_session=.*HttpOnly/);
const me = await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies));
assert.equal(me.status, 200);
assert.equal(me.body.user.role, 'owner');
assert.equal(me.body.user.email, 'pastor@hope.test');
assert.equal(me.body.mfa, true);
const audit = await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } });
assert.equal(audit.length, 1);
});
it('never makes a second Owner, nor one from an unverified email', async () => {
const h = await harness();
h.fake.next = { sub: OWNER, email_verified: false };
assert.match((await signIn(h)).back.headers.location!, /code=NO_ACCESS/);
assert.equal(await h.db.websiteUser.count(), 0);
h.fake.next = { sub: OWNER };
await signIn(h);
h.fake.next = { sub: OTHER };
const { back, cookies } = await signIn(h);
assert.match(back.headers.location!, /code=NO_ACCESS/);
assert.equal(cookies.ccw_session, undefined);
assert.equal(await h.db.websiteUser.count(), 1);
});
it('gives someone without a role on the Website no session', async () => {
const h = await harness();
h.fake.next = { sub: OTHER, email: 'member@hope.test' };
const { back, cookies } = await signIn(h);
assert.match(back.headers.location!, /\/auth\/problem\?code=NO_ACCESS/);
assert.equal(cookies.ccw_session, undefined);
});
it('asks Accounts again with a second step for an Owner who signed in without one, once', async () => {
const h = await harness();
h.fake.next = { sub: OWNER, amr: ['pwd'] };
const first = await signIn(h, '/admin');
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
assert.equal(first.cookies.ccw_session, undefined);
// Accounts still says no second step: explained, not looped.
const second = await signIn(h, '/admin', first.cookies, true);
assert.equal(h.fake.started.at(-1)!.requireTwoFactor, true);
assert.match(second.back.headers.location!, /code=TWO_FACTOR_NEEDED/);
// With it: signed in.
h.fake.next = { sub: OWNER, amr: ['pwd', 'mfa'] };
const third = await signIn(h, '/admin', {}, true);
assert.ok(third.cookies.ccw_session);
});
it('lets an Editor in without a second step, and Owners too when the church turned the rule off', async () => {
const h = await harness();
await h.db.websiteUser.create({ data: { id: OTHER, name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
h.fake.next = { sub: OTHER, email: 'ed@hope.test', amr: ['pwd'] };
assert.ok((await signIn(h)).cookies.ccw_session);
await h.ctx.settings.set('two_factor_required_for_admins', 'false');
h.fake.next = { sub: OWNER, amr: ['pwd'] };
assert.ok((await signIn(h)).cookies.ccw_session);
});
it('keeps the admin API to signed-in people', async () => {
const h = await harness();
const res = await request(h.app).get('/api/v1/admin/me');
assert.equal(res.status, 401);
assert.equal(res.body.error.code, 'SIGNED_OUT');
const me = await request(h.app).get('/api/auth/me').set('Cookie', 'ccw_session=made-up');
assert.equal(me.status, 401);
});
it('signs out here, then at Accounts (all the church\'s sites)', async () => {
const h = await harness();
h.fake.next = { sub: OWNER };
const { cookies } = await signIn(h);
const out = await request(h.app).post('/api/auth/signout').set('Cookie', cookieHeader(cookies));
assert.equal(out.status, 303);
assert.equal(out.headers.location, `https://accounts.hope.test/api/oidc/session/end?id_token_hint=id-token-for-${OWNER}`);
assert.equal(await h.db.session.count(), 0);
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
});
it('ends the person\'s sessions when Accounts says they signed out somewhere', async () => {
const h = await harness();
h.fake.next = { sub: OWNER };
const { cookies } = await signIn(h);
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: OWNER, sid: 'abc' }) });
assert.equal(res.status, 200);
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
assert.equal((await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: 'nonsense' })).status, 400);
});
});
describe("Accounts' calls", () => {
const call = (type: string, extra: object) => JSON.stringify({ schema: 'crosscode.identity/1', callId: '33333333-3333-4333-8333-333333333333', occurredAt: new Date().toISOString(), sub: OWNER, type, ...extra });
it('refuses a call Accounts didn\'t sign', async () => {
const h = await harness();
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send(call('user.updated', {}));
assert.equal(res.status, 401);
});
it('keeps the admin\'s name and email current, exports them, and removes them when the account goes', async () => {
const h = await harness();
await h.db.websiteUser.create({ data: { id: OWNER, name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
await h.db.session.create({ data: { tokenHash: 'x', userId: OWNER, expiresAt: new Date(Date.now() + 1e9) } });
const send = (body: string) => request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').set('x-test-signed', 'yes').send(body);
const profile = { name: 'Pastor Samuel', email: 'Sam@Hope.test', email_verified: true, phone_number: null, news_consent: { email: false, whatsapp: false } };
assert.deepEqual((await send(call('user.updated', { profile }))).body, { schema: 'crosscode.identity/1', ok: true });
const u = await h.db.websiteUser.findUnique({ where: { id: OWNER } });
assert.equal(u!.name, 'Pastor Samuel');
assert.equal(u!.email, 'sam@hope.test');
const exp = await send(call('user.export', { exportId: '44444444-4444-4444-8444-444444444444' }));
assert.equal(exp.body.product, 'website');
assert.equal(exp.body.sections[0].records[0].role, 'owner');
const del = await send(call('user.deleted', {}));
assert.equal(del.body.status, 'deleted');
assert.equal(await h.db.websiteUser.count(), 0);
assert.equal(await h.db.session.count(), 0);
});
});
+266
View File
@@ -0,0 +1,266 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import { WEBSITE_TEMPLATES, agent } from '@crosscode/contracts';
import { demoProfile, loadDemo, seedDesign } from '../src/demo/demoChurch.js';
import { DEMO_SEEDS, demoSeeds } from '../src/demo/seeds.js';
import { siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
import { parseSectionData } from '../src/site/sections.js';
import { buildSnapshot, cleanDesign, publish } from '../src/site/snapshot.js';
import { thumbnail } from '../src/site/thumbnails.js';
import { defaultDesign } from '../src/site/variants.js';
import { harness } from './support/harness.js';
const rgb = (triple: string) => triple.split(' ').map(Number) as [number, number, number];
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-'));
describe('colours from the church, made safe (§3)', () => {
it('keeps a dark colour as it is, with white text', () => {
const p = buildPalette('#1d5c63', '#e0a458');
assert.equal(p.brand, '29 92 99');
assert.equal(p.onBrand, '255 255 255');
assert.deepEqual(p.notes, []);
});
it('darkens a light colour for text on white, and says why', () => {
const p = buildPalette('#f5c542', null);
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5);
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5);
assert.ok(p.notes.some((n) => n.includes('darker shade')));
});
it('always gives readable text on the brand colour, whatever the church picks', () => {
for (const hex of ['#ff0000', '#00ff00', '#0000ff', '#888888', '#ffffff', '#000000', '#ff8800', '#00aaaa']) {
const p = buildPalette(hex, hex);
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5, hex);
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5, hex);
}
assert.deepEqual(hexToRgb('nonsense'), [31, 78, 121]);
});
});
describe('section data', () => {
it('fills defaults and refuses what doesn\'t fit', () => {
assert.deepEqual(parseSectionData('latestMessage', {}), { heading: null });
assert.equal(parseSectionData('hero', { headline: '' }), null);
assert.equal(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: 'javascript:alert(1)' } }), null);
assert.ok(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: '/visit' } }));
assert.equal(parseSectionData('nothing', {}), null);
});
});
describe('publishing (§4)', () => {
it('makes an unknown template, variant or section safe', () => {
const d = cleanDesign({ template: 'fancy', variants: { hero: 'spinning', team: 'list' }, home: [{ section: 'team' }, { section: 'nope' }], style: { spacing: 'compact', bad: 3 } });
assert.equal(d.template, 'heritage');
assert.equal(d.variants.hero, 'photo');
assert.equal(d.variants.team, 'list');
assert.equal(d.home[0]!.section, 'team');
assert.equal(d.home.length, 8);
assert.ok(d.home.slice(1).every((e) => e.hidden));
assert.equal(d.style.spacing, 'compact');
});
it('draws the homepage in the design\'s order and variants, leaving out hidden and broken sections', async () => {
const h = await harness();
const design = defaultDesign('clean');
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: design.variants, home: design.home, style: design.style } });
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
await h.db.section.create({ data: { pageId: home.id, type: 'hero', data: { headline: 'Welcome' } } });
await h.db.section.create({ data: { pageId: home.id, type: 'invitation', data: { heading: '' } } });
await h.db.section.create({ data: { pageId: home.id, type: 'team', data: {} } });
const snap = await buildSnapshot(h.ctx);
const types = snap.pages[0]!.sections.map((s) => s.type);
assert.deepEqual(types, ['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage'], 'Clean hides Team; the empty invitation is left out');
assert.equal(snap.pages[0]!.sections[0]!.variant, 'text');
assert.equal(snap.pages[0]!.path, '/');
});
it('numbers versions and keeps every one', async () => {
const h = await harness();
await publish(h.ctx, { id: 'u1', role: 'owner' }, 'First');
const v2 = await publish(h.ctx, { id: 'u1', role: 'owner' });
assert.equal(v2.number, 2);
assert.equal(await h.db.siteVersion.count(), 2);
});
});
describe('the public site\'s content', () => {
it('is Coming soon before the first publish, from the church profile', async () => {
const h = await harness({ linked: false });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'coming-soon');
assert.equal(c.church, null);
assert.equal(c.style.fontPairing, 'classic', 'Heritage\'s default pairing');
assert.equal(c.style.corners, 'sharp');
});
for (const template of WEBSITE_TEMPLATES) {
it(`loads and publishes the demo church on ${template}`, async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, template, { uploadDir: dir });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
assert.equal(c.snapshot.design.template, template);
assert.equal(c.church?.name, 'Acacia Hill Church');
assert.equal(c.snapshot.pages.length, 9);
assert.equal(c.snapshot.ministries.length, 4);
assert.equal(c.messages.length, 3);
assert.equal(c.events.length, 3);
assert.ok(c.events[0]!.startsAt < c.events[1]!.startsAt);
assert.equal(c.transparentHeader['/'], template === 'bold', 'only Bold\'s header sits over the hero');
const hero = c.snapshot.pages[0]!.sections[0]!;
assert.equal(hero.type, 'hero');
const firstImage = (hero.data.images as string[])[0]!;
assert.match(c.snapshot.media[firstImage]!.url, /^\/api\/uploads\/demo\/hero\.svg$/);
assert.ok(fs.existsSync(path.join(dir, 'demo', 'hero.svg')));
});
}
for (const profile of agent.WEBSITE_DEMO_PROFILES) {
it(`1.3.0: loads the ${profile} demo, keeping the church's own profile and naming it`, async () => {
const h = await harness({ linked: false });
const dir = tmp();
const own = { ...demoProfile('http://x.test'), name: 'Grace Point Church', shortName: 'Grace Point', branding: { ...demoProfile('').branding, colours: { primary: '#8a1538', accent: '#f2c14e' } } };
await h.ctx.settings.set('church_profile_local', JSON.stringify(own));
await loadDemo(h.ctx, profile, { uploadDir: dir });
const c = await siteContent(h.ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const seed = DEMO_SEEDS[profile];
assert.equal(c.snapshot.design.template, seed.template);
assert.equal(c.church?.name, 'Grace Point Church', 'the organisation settings stay');
assert.equal(c.snapshot.pages.length, 9);
assert.equal(c.snapshot.ministries.length, 4);
assert.equal(c.messages.length, 3);
assert.equal(c.events.length, 3);
const all = JSON.stringify(c.snapshot);
assert.doesNotMatch(all, /\{(name|short|city)\}/, 'every placeholder is filled in');
assert.doesNotMatch(all, /Acacia/, 'nothing of the development church');
assert.equal(c.snapshot.design.variants.hero, seedDesign(seed.template, seed.alternate).variants.hero);
assert.match(fs.readFileSync(path.join(dir, 'demo', 'hero.svg'), 'utf8'), /#8a1538/, 'pictures in the church\'s colours');
});
}
it('1.3.0: the two profiles of a template differ, the second on its other recommended variants and header', () => {
for (const template of WEBSITE_TEMPLATES) {
const [a, b] = demoSeeds().filter((s) => s.template === template);
assert.ok(a && b && !a.alternate && b.alternate, template);
const alt = seedDesign(template, true);
assert.notDeepEqual(alt.variants, seedDesign(template, false).variants);
assert.notEqual(alt.style.header, seedDesign(template, false).style.header);
assert.notEqual(a.hero.headline, b.hero.headline);
}
});
it('1.3.0: a profile keeps the site icon and the settings, and clears the old content, slugs and preview links', async () => {
const h = await harness({ linked: false });
const dir = tmp();
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const icon = (await h.db.mediaAsset.create({ data: { filename: 'icon.png', mime: 'image/png', bytes: 10, width: 64, height: 64, alt: 'Icon' } })) as { id: string };
await h.ctx.settings.set('favicon_media_id', icon.id);
await h.ctx.settings.set('coming_soon_text', 'Soon!');
await h.db.slugHistory.create({ data: { slug: 'old-about', pageId: 'gone' } });
await loadDemo(h.ctx, 'community-town', { uploadDir: dir });
assert.ok(await h.db.mediaAsset.findUnique({ where: { id: icon.id } }), 'the site icon stays');
assert.equal(await h.ctx.settings.get('favicon_media_id'), icon.id);
assert.equal(await h.ctx.settings.get('coming_soon_text'), 'Soon!');
assert.equal(await h.db.mediaAsset.count(), 11, 'the ten pictures and the icon');
assert.equal(await h.db.slugHistory.count(), 0);
assert.equal((await siteContent(h.ctx)).church?.name, 'Acacia Hill Church', 'the profile saved by the first demo stays');
});
it('1.3.0: a profile on a site with no church profile at all saves the demo one, so the site has a name', async () => {
const h = await harness({ linked: false });
await loadDemo(h.ctx, 'clean-campus', { uploadDir: tmp() });
const c = await siteContent(h.ctx);
assert.equal(c.church?.name, 'Acacia Hill Church');
assert.ok(c.mode === 'published' && JSON.stringify(c.snapshot).includes('Welcome to Acacia Hill'));
});
it('serves the uploads, never a folder or outside it, and the content over HTTP', async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'community', { uploadDir: dir });
const svg = await request(h.app).get('/api/uploads/demo/hero.svg');
assert.equal(svg.status, 200);
assert.match(String(svg.headers['content-security-policy']), /sandbox/);
assert.equal((await request(h.app).get('/api/uploads/demo/')).status, 404);
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/..%2f..%2fpackage.json')).status));
assert.equal((await request(h.app).get('/api/uploads/missing.png')).status, 404);
const content = await request(h.app).get('/api/v1/site/content');
assert.equal(content.body.mode, 'published');
assert.equal(content.body.snapshot.design.template, 'community');
});
});
describe("the messages' thumbnails, served from the site (§7)", () => {
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const youtube = (body: Buffer | string, type = 'image/jpeg', status = 200) => {
const asked: string[] = [];
const fetcher = async (url: string) => { asked.push(url); return new Response(typeof body === 'string' ? body : new Uint8Array(body), { status, headers: { 'content-type': type } }); };
return { asked, fetcher };
};
it("gives visitors the site's own address, never YouTube's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const content = await siteContent(h.ctx);
assert.ok(content.mode === 'published' && content.messages.length > 0);
for (const m of content.messages) assert.equal(m.thumbnail, '/api/thumbnails/aqz-KE-bpKQ.jpg');
});
it("fetches a message's thumbnail once and keeps it; nothing for a video that isn't the site's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const yt = youtube(jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(yt.asked, ['https://i.ytimg.com/vi/aqz-KE-bpKQ/hqdefault.jpg']);
assert.ok(fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
// Kept out of /api/uploads (a dot folder).
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/.thumbnails/aqz-KE-bpKQ.jpg')).status));
// Not one of the site's messages, or not an id: YouTube isn't asked.
assert.equal(await thumbnail(h.ctx, 'someoneElse1', yt.fetcher), null);
assert.equal(await thumbnail(h.ctx, '../../etc/x', yt.fetcher), null);
assert.equal(yt.asked.length, 1);
});
it("keeps nothing that isn't a JPEG, and says 404 when YouTube has none", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('<html>', 'text/html').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube(Buffer.from('GIF89a'), 'image/jpeg').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('', 'image/jpeg', 404).fetcher), null);
assert.ok(!fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
h.ctx.fetch = youtube('', 'image/jpeg', 404).fetcher;
const missing = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(missing.status, 404);
assert.equal(missing.headers['cache-control'], 'no-store');
h.ctx.fetch = youtube(jpeg).fetcher;
const ok = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(ok.status, 200);
assert.equal(ok.headers['content-type'], 'image/jpeg');
assert.equal((await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.png')).status, 404);
});
});
describe('message links', () => {
it('finds YouTube ids and Spotify embeds', () => {
assert.equal(youtubeId('https://www.youtube.com/watch?v=aqz-KE-bpKQ'), 'aqz-KE-bpKQ');
assert.equal(youtubeId('https://youtu.be/abc123'), 'abc123');
assert.equal(youtubeId('https://www.youtube.com/live/xyz'), 'xyz');
assert.equal(youtubeId('https://example.com/watch?v=abc'), null);
assert.equal(spotifyEmbed('https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk?si=1'), 'https://open.spotify.com/embed/episode/4rOoJ6Egrf8K2IrywzwOMk');
assert.equal(spotifyEmbed('https://evil.example/episode/x'), null);
});
});
@@ -0,0 +1,42 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { previewContent } from '../src/site/content.js';
import { ensureStarterPages, STARTER_PAGES } from '../src/site/starter.js';
import { harness } from './support/harness.js';
describe('a new install\'s starter pages', () => {
it('adds the fixed pages to a site with none, and the preview shows every homepage section', async () => {
const { ctx, db } = await harness({ linked: false });
assert.deepEqual(await ensureStarterPages(ctx), STARTER_PAGES.map((p) => p.kind));
const c = await previewContent(ctx);
assert.equal(c.mode, 'published');
if (c.mode !== 'published') return;
const home = c.snapshot.pages.find((p) => p.kind === 'home')!;
assert.deepEqual(home.sections.map((s) => s.type).sort(), ['events', 'hero', 'invitation', 'latestMessage', 'ministries', 'serviceTimes', 'team', 'welcome']);
// Every starter block fits its schema (a broken one would be left out of the site).
for (const p of STARTER_PAGES) assert.equal(c.snapshot.pages.find((x) => x.kind === p.kind)!.sections.length, p.sections.length, p.kind);
// Terms and Safeguarding are footer links, not menu items.
assert.equal(c.snapshot.pages.filter((p) => p.inNav).some((p) => p.kind === 'terms' || p.kind === 'safeguarding'), false);
// Only once.
assert.deepEqual(await ensureStarterPages(ctx), []);
assert.equal(await db.page.count(), STARTER_PAGES.length);
});
it('keeps the church\'s own pages, after the fixed ones, and skips an address they already use', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'custom', slug: 'test', title: 'Test', position: 1 } });
await db.page.create({ data: { kind: 'custom', slug: 'give', title: 'Giving', position: 2 } });
const kinds = await ensureStarterPages(ctx);
assert.ok(kinds.includes('home') && !kinds.includes('give'));
const pages = await db.page.findMany({ orderBy: { position: 'asc' } });
assert.equal(pages[0]!.kind, 'home');
assert.deepEqual(pages.slice(-2).map((p) => p.slug), ['test', 'give']);
});
it('adds only a missing home page to a site that has its other fixed pages', async () => {
const { ctx, db } = await harness({ linked: false });
await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', archivedAt: new Date() } });
assert.deepEqual(await ensureStarterPages(ctx), ['home']);
assert.deepEqual(await ensureStarterPages(ctx), []);
});
});
@@ -0,0 +1,74 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { hub } from '@crosscode/contracts';
import { hashToken } from '../src/lib/crypto.js';
import { stats } from '../src/hub/client.js';
import { harness, SITE } from './support/harness.js';
const SECRET = 'install-secret-0123456789abcdef0123456789';
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
/** The Hub: checks the install's signature as installApi.js does, and records what it's asked. */
async function fakeHub() {
const asked: { installId: string; body: unknown }[] = [];
const app = express();
app.post('/api/installs/storage-request', express.text({ type: () => true }), (req, res) => {
const ts = String(req.get('X-Hub-Timestamp'));
const expected = crypto.createHmac('sha256', SECRET).update(`${ts}.${req.body}`).digest('hex');
if (req.get('X-Hub-Signature') !== expected) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
const body = JSON.parse(req.body);
if (!hub.storageRequestSchema.safeParse(body).success) return res.status(400).json({ code: 'INVALID_REQUEST', message: 'no' });
asked.push({ installId: String(req.get('X-Hub-Install')), body });
return res.status(201).json({ requestedAt: new Date().toISOString(), steps: body.steps, alreadyRequested: asked.length > 1 });
});
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
closers.push(() => new Promise((r) => server.close(r)));
return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, asked };
}
async function site(role: 'owner' | 'editor') {
const fake = await fakeHub();
const h = await harness({ env: { HUB_URL: fake.url } });
await h.ctx.settings.set('hub_install_secret', SECRET);
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Pastor Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, fake, go };
}
describe('Get more storage (decision 12)', () => {
it('asks the Hub, signed, with who asked and what is used; shows the request open until the limit goes up', async () => {
const { go, fake, db } = await site('owner');
await db.mediaAsset.create({ data: { filename: 'a.jpg', mime: 'image/jpeg', bytes: 4_500_000_000 } });
const r = await go('post', '/storage-request', { steps: 2 });
assert.equal(r.status, 200);
assert.equal(fake.asked.length, 1);
assert.deepEqual(fake.asked[0]!.body, { protocolVersion: 2, steps: 2, usedBytes: 4_500_000_000, limitBytes: 5 * 1024 ** 3, requestedBy: 'Pastor Sam' });
const media = (await go('get', '/media')).body;
assert.equal(media.request.steps, 2);
assert.equal((await go('post', '/storage-request', { steps: 11 })).status, 400);
});
it('is an Owner\'s or Admin\'s to ask (it costs the church)', async () => {
const { go } = await site('editor');
assert.equal((await go('post', '/storage-request', { steps: 1 })).status, 403);
});
it('reports the licence\'s limit in the heartbeat, so the Hub can email at 80% and 100%', async () => {
const { ctx } = await site('owner');
const s = await stats(ctx);
assert.equal(s.storage.includedBytes, 5 * 1024 ** 3);
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
});
});
@@ -0,0 +1,117 @@
/**
* The Website's app on an in-memory database, with a stand-in for `@crosscode/auth-client` (the
* real one is tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts),
* linked to a church's Accounts and registered with the Hub.
*/
import type { IdentityClaims } from '@crosscode/contracts';
import type { AuthClientModule } from '../../src/auth/accounts.js';
import { createApp } from '../../src/app.js';
import { createCtx, type Ctx, type Db } from '../../src/context.js';
import { loadConfig } from '../../src/lib/config.js';
import { memoryDb, type MemoryDb } from './memoryDb.js';
export const SITE = 'https://www.hope.test';
export const ACCOUNTS = 'https://accounts.hope.test';
export const ADMIN_EMAIL = 'pastor@hope.test';
export const INSTALL_ID = '6f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f';
export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
/** What the stand-in Accounts answers with at the next callback. */
export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
/** Requests to Accounts (people.ensure, …). */
requests: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown> }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
return {
schema: 'crosscode.identity/1',
name: 'Pastor Sam',
email: ADMIN_EMAIL,
email_verified: true,
phone_number: null,
news_consent: { email: false, whatsapp: false },
amr: ['pwd', 'mfa'],
two_factor: 'totp',
privacy_notice_version: 1,
...over,
} as IdentityClaims;
}
function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
class SignInError extends Error {
constructor(message: string, public code: string) {
super(message);
}
}
return {
SignInError,
accountsClient: async () => ({
startSignIn: async (returnTo: string, opts: { requireTwoFactor?: boolean } = {}) => {
fake.started.push({ returnTo, requireTwoFactor: !!opts.requireTwoFactor });
return { url: `${ACCOUNTS}/api/oidc/auth?mfa=${opts.requireTwoFactor ? 1 : 0}`, cookie: Buffer.from(JSON.stringify({ returnTo })).toString('base64url') };
},
finishSignIn: async (_url: URL, cookie: string | undefined) => {
if (!cookie) throw new SignInError('expired', 'NO_PENDING');
const { returnTo } = JSON.parse(Buffer.from(cookie, 'base64url').toString()) as { returnTo: string };
return { claims: claims(fake.next), returnTo, idToken: `id-token-for-${fake.next.sub}` };
},
signOutUrl: (idToken?: string) => `${ACCOUNTS}/api/oidc/session/end?id_token_hint=${idToken ?? ''}`,
verifyLogoutToken: async (token: string) => {
try {
return JSON.parse(token) as { sub: string; sid: string | null };
} catch {
throw new SignInError('bad', 'BAD_TOKEN');
}
},
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
request: async (input: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown>; ifUpdatedAt?: string }) => {
fake.requests.push(input);
if (input.type === 'church.update') {
// An old ifUpdatedAt: someone saved in between.
if (input.ifUpdatedAt === '2000-01-01T00:00:00.000Z') throw Object.assign(new Error('changed'), { code: 'PROFILE_CHANGED', status: 409 });
return { schema: 'crosscode.identity-request/1', church: { name: 'Hope', ...input.church } };
}
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
},
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
return JSON.parse(raw.toString('utf8'));
},
}),
} as unknown as AuthClientModule;
}
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
const db = memoryDb();
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [], requests: [] };
const config = loadConfig({ WEBSITE_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake) });
await ctx.settings.set('hub_install_id', INSTALL_ID);
if (opts.linked !== false) {
await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } });
}
return { db, ctx, fake, app: createApp(ctx) };
}
export type Harness = Awaited<ReturnType<typeof harness>> & { db: MemoryDb; ctx: Ctx };
/** `name=value` pairs from a response's Set-Cookie, for the next request. */
export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Record<string, string> = {}): Record<string, string> {
const out = { ...keep };
for (const line of (res.headers['set-cookie'] as string[] | undefined) ?? []) {
const [pair, ...attrs] = line.split(';');
const i = pair!.indexOf('=');
const name = pair!.slice(0, i).trim();
const value = pair!.slice(i + 1).trim();
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a)) || value === '';
if (expired) delete out[name];
else out[name] = value;
}
return out;
}
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
@@ -0,0 +1,188 @@
/**
* An in-memory stand-in for the Prisma client (from Accounts' tests/support/memoryDb.ts): every
* model the Website uses, with the schema's defaults and unique fields, generic `where` matching
* (equality, in / notIn, gt / gte / lt / lte, not, contains, AND / OR), `include` of the relations
* below and `aggregate` sums. Enough to run the whole app in tests.
*/
import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
messageSeries: () => ({ summary: null, imageId: null }),
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
siteVersion: () => ({ note: null }),
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'], siteVersion: ['number'], page: ['slug'], message: ['slug', 'externalId'], previewLink: ['tokenHash'] };
const HAS_UPDATED_AT = new Set(['siteDesign', 'page', 'section', 'ministry', 'leader', 'message', 'simpleEvent', 'appSetting', 'productLink']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
page: { sections: { model: 'section', many: true, key: 'pageId' } },
message: { series: { model: 'messageSeries', many: false, key: 'seriesId' } },
};
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
function matchValue(actual: unknown, cond: unknown): boolean {
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
const c = cond as Record<string, unknown>;
const insensitive = c.mode === 'insensitive';
return Object.entries(c).every(([op, x]) => {
switch (op) {
case 'mode': return true;
case 'equals': return v(actual) === v(x);
case 'in': return (x as unknown[]).map(v).includes(v(actual));
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
case 'not': return x === null ? actual != null : !matchValue(actual, x);
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
default: throw new Error(`memoryDb: no operator ${op}`);
}
});
}
return v(actual) === v(cond);
}
export function matches(row: Row, where: Row = {}): boolean {
return Object.entries(where ?? {}).every(([k, cond]) => {
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
if (k === 'NOT') return !matches(row, cond as Row);
return matchValue(row[k], cond);
});
}
const clone = <T>(x: T): T => structuredClone(x);
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
function order(rows: Row[], orderBy?: Row | Row[]) {
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
return [...rows].sort((a, b) => {
for (const o of list) {
const [k, dir] = Object.entries(o)[0]!;
const x = v(a[k]) as number;
const y = v(b[k]) as number;
const d = x < y ? -1 : x > y ? 1 : 0;
if (d) return dir === 'desc' ? -d : d;
}
return 0;
});
}
function prismaError(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
const key = KEYS[name] ?? 'id';
const table = () => {
if (!tables.has(name)) tables.set(name, new Map());
return tables.get(name)!;
};
const findWhere = (where: Row) => {
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
return [...table().values()].find((r) => matches(r, where)) ?? null;
};
const checkUnique = (row: Row, except?: unknown) => {
for (const u of UNIQUE[name] ?? []) {
if (row[u] == null) continue;
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
}
};
const api = {
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
const rows = [...table().values()].filter((x) => matches(x, where));
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
},
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
create: async ({ data }: { data: Row }) => {
const now = new Date();
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
checkUnique(row);
table().set(row[key], row);
return clone(row);
},
update: async ({ where, data }: { where: Row; data: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
checkUnique(next, r[key]);
table().set(r[key], next);
return clone(next);
},
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
let count = 0;
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
return { count };
},
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
const r = findWhere(where);
return r ? api.update({ where, data: update }) : api.create({ data: create });
},
delete: async ({ where }: { where: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
table().delete(r[key]);
cascade(name, r[key]);
return clone(r);
},
deleteMany: async ({ where }: { where?: Row } = {}) => {
let count = 0;
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
return { count };
},
};
const cascade = (from: string, id: unknown) => {
if (from === 'page') for (const [k, r] of tables.get('section') ?? []) if (r.pageId === id) tables.get('section')!.delete(k);
if (from === 'productLink') for (const [k, r] of tables.get('importedEvent') ?? []) if (r.linkId === id) tables.get('importedEvent')!.delete(k);
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {
const spec = RELATIONS[name]?.[rel];
if (!on || !spec) continue;
const other = [...(tables.get(spec.model)?.values() ?? [])];
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
}
return row;
};
return api;
}
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
export function memoryDb(): MemoryDb {
const tables = new Map<string, Map<unknown, Row>>();
const models = new Map<string, ReturnType<typeof model>>();
return new Proxy({} as MemoryDb, {
get(_t, prop: string) {
if (prop === 'tables') return tables;
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
if (prop === '$disconnect') return async () => {};
if (prop === 'then') return undefined;
if (!models.has(prop)) models.set(prop, model(prop, tables));
return models.get(prop);
},
});
}
+103
View File
@@ -0,0 +1,103 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
import {
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
} from '../src/site/variants.js';
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
it('has the 26 confirmed variant ids', () => {
assert.equal(Object.values(SECTION_VARIANTS).flat().length, 26);
assert.deepEqual(SECTION_VARIANTS.hero, ['photo', 'video', 'collage', 'split', 'text']);
});
it('every template recommends only real variants, without repeats, with a default for every section', () => {
for (const t of WEBSITE_TEMPLATES) {
for (const s of SECTION_TYPES) {
const rec = TEMPLATE_VARIANTS[t][s] as readonly string[];
assert.ok(rec.length >= 2, `${t}.${s}`);
assert.equal(new Set(rec).size, rec.length, `${t}.${s} repeats`);
for (const v of rec) assert.ok(isVariant(s, v), `${t}.${s}: ${v}`);
}
}
});
it('has the confirmed defaults', () => {
assert.equal(defaultVariant('heritage', 'hero'), 'photo');
assert.equal(defaultVariant('bold', 'hero'), 'video');
assert.equal(defaultVariant('community', 'hero'), 'collage');
assert.equal(defaultVariant('clean', 'hero'), 'text');
assert.equal(defaultVariant('clean', 'latestMessage'), 'compact');
assert.ok(isRecommended('heritage', 'team', 'faces'));
assert.ok(!isRecommended('heritage', 'team', 'list'));
});
it('lists every section once in each homepage order; Bold hides Team, Clean hides Ministries and Team', () => {
for (const t of WEBSITE_TEMPLATES) {
assert.deepEqual([...TEMPLATE_HOME_ORDER[t].map((e) => e.section)].sort(), [...SECTION_TYPES].sort(), t);
}
const hidden = (t: keyof typeof TEMPLATE_HOME_ORDER) => TEMPLATE_HOME_ORDER[t].filter((e) => e.hidden).map((e) => e.section);
assert.deepEqual(hidden('heritage'), []);
assert.deepEqual(hidden('bold'), ['team']);
assert.deepEqual(hidden('community'), []);
assert.deepEqual(hidden('clean'), ['ministries', 'team']);
});
it("each template's default header is the first of its options", () => {
for (const t of WEBSITE_TEMPLATES) assert.equal(TEMPLATE_STYLE[t].header, TEMPLATE_HEADERS[t][0]);
});
it('suggests the confirmed corners', () => {
assert.deepEqual(WEBSITE_TEMPLATES.map((t) => TEMPLATE_STYLE[t].suggestedCorners), ['sharp', 'sharp', 'round', 'soft']);
});
it('only makes the header transparent over a photo, video or collage hero', () => {
assert.ok(headerIsTransparent('bold', 'transparent', 'video'));
assert.ok(!headerIsTransparent('bold', 'transparent', 'text'));
assert.ok(!headerIsTransparent('bold', 'transparent', 'split'));
assert.ok(!headerIsTransparent('bold', 'solid', 'photo'));
assert.ok(!headerIsTransparent('bold', 'transparent', null));
});
});
describe('switching template', () => {
it('moves an untouched site to every default of the new template', () => {
const { design, changes } = switchTemplate(defaultDesign('community'), 'clean');
assert.deepEqual(design, defaultDesign('clean'));
assert.ok(changes.some((c) => c.what === 'hero.variant' && c.from === 'collage' && c.to === 'text'));
assert.ok(changes.some((c) => c.what === 'home'));
assert.equal(changes[0]!.what, 'template');
});
it("keeps the church's own choices", () => {
const start = defaultDesign('heritage');
start.variants.hero = 'video';
start.style.buttons = 'pill';
start.home = [...start.home].reverse();
const { design, changes } = switchTemplate(start, 'clean');
assert.equal(design.template, 'clean');
assert.equal(design.variants.hero, 'video');
assert.equal(design.style.buttons, 'pill');
assert.deepEqual(design.home, start.home);
assert.equal(design.variants.team, 'list', 'an untouched section still moves');
assert.ok(!changes.some((c) => c.what === 'hero.variant' || c.what === 'home' || c.what === 'style.buttons'));
});
it("moves a header the new template doesn't have", () => {
const start = defaultDesign('bold');
start.style.header = 'solid';
const { design } = switchTemplate(start, 'heritage');
assert.equal(design.style.header, 'centred');
});
it('changes nothing when the template stays', () => {
const d = defaultDesign('bold');
assert.deepEqual(switchTemplate(d, 'bold'), { design: d, changes: [] });
});
it('round-trips an untouched site', () => {
const there = switchTemplate(defaultDesign('heritage'), 'bold').design;
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
});
});
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
"include": ["src"]
}

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