Compare commits

...
Author SHA1 Message Date
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
joshua 66557c7f1d Merge branch 'feat/events-3.7' 2026-11-24 23:29:24 +02:00
joshuaandClaude Opus 5.5 f4b6a41f83 Events 3.7.0 + @crosscode/ui 0.3.0: the church's fonts, corners and footer on the public pages
- Backend: the church profile from Accounts (src/accounts/church.ts, kept 10
  minutes, last copy kept while Accounts is down), public GET /api/v2/church,
  and church.changed accepted at POST /api/church/v1/changed (signed with the
  Accounts link; it answered 404 before).
- Frontend: brandAttributes on <html>, @crosscode/ui/fonts.css, body and
  h1-h3 use the church's pairing, --radius follows its corners; the dashboard
  and setup screens (data-cc-staff) keep their fonts and 0.5rem.
- The shared ChurchFooter on public pages when Accounts is connected (terms
  and cookie settings below it); header links to the church's other sites.
- @crosscode/ui 0.3.0: ChurchFooter takes `bottom`.
- Tests: tests/churchProfile.test.ts (8); e2e/church-brand.spec.ts and a
  /test/profile hook on the e2e Accounts.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:26:50 +02:00
317 changed files with 23358 additions and 476 deletions
+153
View File
@@ -2,6 +2,159 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.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).
Details in `apps/events/CHANGELOG.md`.
- **Events 3.7.0:** the church profile from Accounts (`GET /api/v2/church`), its fonts and corners
on the public pages, `ChurchFooter` and links to the church's other sites; `church.changed` is
accepted at `/api/church/v1/changed`. Dashboard and setup unchanged. No migrations.
- **`@crosscode/ui` 0.3.0:** `ChurchFooter` takes `bottom` (a product's own links).
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
additive and optional: products on 1.16.0 keep working. Accounts 1.7.0 ships with them because it
answers the new `church.update` request. Details of Accounts in `apps/accounts/CHANGELOG.md`.
- **Brand style** (`./style`): the 8 font pairings confirmed on 2026-11-24 (`FONT_PAIRINGS`:
`classic`, `scholarly`, `editorial`, `impact`, `contemporary`, `friendly`, `warm`, `modern`, each
with its heading and body font), the corner styles (`CORNERS`, `DEFAULT_CORNERS` = `soft`), the
Website's templates (`WEBSITE_TEMPLATES`) and the three pairings each recommends
(`TEMPLATE_FONT_PAIRINGS`, default first). The ids are stored in profiles and never change.
- **`crosscode.church/1`:** optional `branding.style` (`fontPairing`, `corners`, each nullable). An
id a product doesn't know yet reads as null, so a newer Accounts never breaks an older product.
- **`crosscode.church-export/1`:** an optional `website` part (template, first publish, style
settings, pages with their sections, messages, simple events, the publish history's notes and
the media library's alt text). New sample `church-export-website.json`.
- **`church.update`** (identity request, product → Accounts, signed with the link's secret): the
Website's admin changes shared profile facts (plan decision 10). The product checks the person's
role and sends them as `actor`; only the fields given change (`branding` field by field); live at
once, then `church.changed`. Optional `ifUpdatedAt` refuses with the new error code
`PROFILE_CHANGED` when someone saved in between. Reply: the profile (`churchUpdateReplySchema`).
Accounts 1.7.0 takes it from the Website only.
- **Licence:** optional `limits.storageBytes`, the Website's storage limit including add-ons (plan
decision 12). New sample `hub-licence-payload-website.json`.
- **Accounts 1.7.0:** the brand style in Admin → Church profile, the church's fonts, corners and
shared footer on its pages, and `church.update` from the Website. Update Accounts before (or with)
anything that sends `church.update`; nothing does until the Website.
- **`@crosscode/ui` 0.2.0:** `fonts.css` (the 8 pairings' fonts, Latin and Latin Extended, from the
pinned `@fontsource-variable` packages, with Capsize size-matched fallbacks on Arial or Georgia;
generated by `scripts/fonts.mjs`, checked by `npm test`, at most 160 KB per pairing for an
English page), `brandAttributes`, `ChurchFooter`, `productLinks`; the components' corners follow
`--cc-radius` and headings the pairing's heading font. Apps without a pairing look as before.
- `package-lock.json` catches up with the agent's and contracts' versions.
## agent@1.5.0 + contracts@1.16.0 + crosscode script - 2026-11-23
- **Fix: uninstalling one product removed the whole church.** `crosscode uninstall <church>` only
knew whole churches, while the Hub uninstalls per product: uninstalling cross-events-demo's
Events also removed its Accounts, which the Hub still showed as live, and its own uninstall
failed later ("No church cross-events-demo on this server").
- **`crosscode uninstall|export|purge <church> [product …]`.** With products named, only those
are backed up, kept (`.removed/<church>-<date>/<product>`) and removed; the church keeps the
others in church.env. Naming every product it still has removes the church (folder and app
user), so the last product to go always takes the church with it. The report gives `products`
and `remaining`. `purge` with products deletes only what was kept of those, also while the
church still has others. Without products, as before.
- **Agent 1.5.0** passes `products` through. **Contracts 1.16.0:** optional `products` on the
`export`, `uninstall` and `purge` job arguments, and `PRODUCT_UNINSTALL_MIN_AGENT` (an older
agent refuses the key). Hub 2.12.0 uses them.
- The Church Website plan's versions move up one again: contracts 1.17.0, Hub 2.13.0.
## agent@1.4.0 + contracts@1.15.0 - 2026-11-21
- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes
`/etc/frp/frps.ini`: it uses the path set on the Hub, else the `-c` in the frps/frpc systemd
unit, else the usual places (`/etc/frp`, `/usr/local/frp`, `/opt/frp` …), and reads TOML
(`proxyBindAddr`, `allowPorts = [{ start, end }]`) as well as INI. The central server's check
after an install failed with "No frps.ini at /etc/frp/frps.ini" on a server that keeps it
elsewhere. Stats say which file it uses (`frpConfigPath`). `crosscode` gets `FRPC_INI` for it
on church servers.
- **New jobs** (both modes): `frp-read` (the config, secrets hidden), `frp-write` (secrets put
back, `frp* verify`, backup, restart, the old file back if frp doesn't start) and
`probe-ports` (which of these ports are free here). Contracts 1.15.0: the job arguments,
`frpReadResultSchema`, `probePortsResultSchema`, `FRP_JOBS_MIN_AGENT`, `FRP_HIDDEN`,
`agentStats.frpConfigPath`. The Hub needs agent 1.4.0 on a server for these (Hub 2.11.0).
- The Church Website plan's versions move up one: contracts 1.16.0, Hub 2.12.0.
## crosscode script - 2026-11-20 (no tag: servers run `main`)
- **Fix:** the database dump made before each Accounts deploy (`apps/accounts/backend/backups/`)
counted as a file added by hand on Accounts below 1.3.0 (no `.gitignore` for it yet), so the
next deploy stopped with "changed or added by hand". Untracked files in that folder no longer
count (`CROSSCODE_OWN_DIRS` in `lib/common.sh`).
## events@3.6.1 - 2026-11-20
- **Events 3.6.1 (fix):** uploading a logo or favicon failed with "uploaded, but the site can't
show it yet" behind a proxy with a file-extension rule (FastPanel's static-file handling sent
`/api/uploads/…png` to the frontend). The site now passes `/api/*` and `/uploads/*` that reach
it on to the backend (new `BACKEND_INTERNAL_URL`, added on deploy).
- **crosscode script:** the nginx site it writes uses `location ^~ /api/` and `^~ /uploads/`.
## accounts@1.6.0 - 2026-11-20
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp for a verified number) after every
sign-in, as Cross Events' own sign-in did; Sign-in settings → `signin_notices` turns it off.
## events@3.6.0, accounts@1.5.0, contracts@1.14.0 - 2026-11-20
A nightly check that each site's copies of people match their church accounts, for changes that
never arrived.
- **Contracts 1.14.0:** `people.check` in `crosscode.identity-request/1` (`PEOPLE_CHECK_MAX` 500)
and `peopleCheckReplySchema` (each sub `active` / `deactivated` / `deleted` / `unknown`, with the
profile for the first two). Samples and JSON Schema `people-check-reply`.
- **Accounts 1.5.0:** answers it, only with profiles of people the product knows.
- **Events 3.6.0:** the `accounts-people-check` job (04:30): fixes out-of-date copies, handles
deleted accounts as `user.deleted`, and stops if most people are unknown (wrong Accounts?).
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
+85
View File
@@ -1,5 +1,90 @@
# 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).
### Added
- **Brand style** in the church profile (`branding.style`: font pairing and corners, contracts
1.17.0). Admin → Church profile → **Brand style** shows each of the 8 pairings in its own fonts,
and the three corner styles. Served in `GET /api/church/v1` and `/api/v2/branding`.
- **The church's fonts and corners on Accounts' pages**: `@crosscode/ui/fonts.css` (self-hosted, no
font requests to anyone else) and `brandAttributes` on `<html>`. Without a pairing the pages
keep the device fonts, so nothing changes until an admin picks one.
- **The shared footer** (`ChurchFooter` from `@crosscode/ui`) on the public pages (sign in, forgot
and reset password, signed out, confirm email): service times, address, contact, social links,
links to the church's other sites and the privacy notice, from the church profile.
- **`church.update`** (contracts 1.17.0): the church's Website changes shared profile facts for its
admins (WEBSITE-1.0-PLAN decision 10). Only from a product linked as `website`
(`WRONG_PRODUCT`), only for an `actor` who signs in through it (`NOT_ALLOWED`), and refused
with `PROFILE_CHANGED` (409) when `ifUpdatedAt` is out of date. Live at once; linked products get
`church.changed`; audited as `church_profile_changed_by_product` with the fields changed.
### Changed
- Saving the profile merges `branding` field by field (`mergeProfile`), so a form or product that
sends only part of it (the colours without the style, or only the style) never drops the rest.
## [1.6.0] - 2026-11-20
### Added
- **"New sign-in" notices**, as Cross Events' own sign-in sends (`src/accounts/signInNotice.ts`):
after each completed sign-in (the interaction reaching done, so not the silent ones a second
product gets from an existing session), an email with when, the site, rough location and device
(`newSignInEmail` in `src/lib/emails.ts`), and a WhatsApp message when the person has a verified
number and WhatsApp is set up. Location from ip-api.com in production only, never for private
addresses. Fire-and-forget: never holds up or fails a sign-in. Admins can turn it off:
`signin_notices` (Sign-in settings, on by default). In Accounts mode Cross Events no longer sends
its own, so before this nobody was told.
## [1.5.0] - 2026-11-20
Needs contracts 1.14.0.
### Added
- `people.check` (contracts 1.14.0): for up to 500 subs, the current profile of each person the
product knows (`active` / `deactivated`), `deleted` for a deleted account, `unknown` for anyone
else (no profile). Audited once per request (`people_checked_by_product`, counts only); the reply
isn't stored for retries, since it holds profiles. Cross Events 3.6.0 asks nightly.
## [1.4.0] - 2026-11-20
Works with every Cross Events 3.x and contracts 1.11.0 or later.
+36
View File
@@ -3,6 +3,42 @@
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
pairings, each shown in its own fonts, and sharp, soft or round corners. Your sign-in pages use
them now, and your new Church Website and Cross Events' public pages will too, so all your sites
look like one church. Until you pick, nothing changes.
- **A footer with your church's details** under the sign-in pages: service times, address, contact
details and links to your church's other sites, from the church profile.
- Getting ready for the **Church Website**: its admins will be able to change your service times,
logo and contact details from the website, and they'll change everywhere at once.
## 1.6.0
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
where, on what device and to which site, with what to do if it wasn't them, as Cross Events
does for its own sign-in. People with a confirmed WhatsApp number get it on WhatsApp too.
Admins can turn this off under Sign-in settings.
## 1.5.0
- Your church's sites can now check every night that the details they keep for each person match
their church account (Cross Events 3.6.0 does), so a change that didn't reach a site is fixed the
next morning.
## 1.4.0
- **Better-looking emails.** Sign-in codes, password links, "your account is ready" and the other
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.4.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",
@@ -0,0 +1,58 @@
/**
* "New sign-in" notices (1.6.0), as Cross Events sends for its own sign-in: after each completed
* sign-in, an email to the person, and a WhatsApp message too when they have a verified number and
* WhatsApp is set up. Admins can turn them off (Sign-in settings, `signin_notices`). Never holds up
* or fails the sign-in.
*
* The rough location comes from the IP (ip-api.com, as Cross Events), in production only, and never
* for private addresses.
*/
import type { Ctx } from '../context.js';
import { newSignInEmail } from '../lib/emails.js';
import { productName } from '../oidc/clients.js';
const PRIVATE_IP = /^(::1$|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fc|fd|fe80|::ffff:(127|10|192\.168)\.)/i;
/** "Chrome on Windows" from a user agent; the raw string when it can't tell. */
export function describeDevice(ua: string | null | undefined): string {
const s = String(ua || '');
if (!s) return 'Unknown device';
const browser = /Edg\//.test(s) ? 'Edge' : /OPR\/|Opera/.test(s) ? 'Opera' : /Firefox\//.test(s) ? 'Firefox'
: /SamsungBrowser\//.test(s) ? 'Samsung Internet' : /Chrome\//.test(s) ? 'Chrome' : /Safari\//.test(s) ? 'Safari' : null;
const os = /iPhone|iPad|iPod/.test(s) ? 'iPhone or iPad' : /Android/.test(s) ? 'Android' : /Windows/.test(s) ? 'Windows'
: /Mac OS X|Macintosh/.test(s) ? 'a Mac' : /CrOS/.test(s) ? 'a Chromebook' : /Linux/.test(s) ? 'Linux' : null;
if (browser && os) return `${browser} on ${os}`;
return browser || os || s.slice(0, 120);
}
async function roughLocation(ctx: Ctx, ip: string | null): Promise<string> {
if (!ip || PRIVATE_IP.test(ip) || !ctx.config.production) return 'Unknown';
try {
const res = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip.replace(/^::ffff:/, ''))}?fields=status,city,regionName,country`, { signal: AbortSignal.timeout(3000) });
const geo = (await res.json()) as { status?: string; city?: string; regionName?: string; country?: string };
const parts = geo.status === 'success' ? [geo.city, geo.regionName, geo.country].filter(Boolean) : [];
return parts.length ? parts.join(', ') : 'Unknown';
} catch {
return 'Unknown';
}
}
export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: string | null; userAgent: string | null; clientId: string | null }): Promise<'sent' | 'off' | 'failed'> {
try {
if (!(await ctx.settings.bool('signin_notices', true))) return 'off';
const a = await ctx.db.account.findUnique({ where: { id: o.accountId } });
if (!a || a.status !== 'active') return 'off';
const link = o.clientId ? await ctx.db.productLink.findUnique({ where: { installId: o.clientId } }) : null;
const site = link ? productName(link.product) : o.clientId === 'accounts-self' ? 'Your account page' : null;
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
}
return 'sent';
} catch (e) {
console.warn('[sign-in notice] not sent:', (e as Error).message);
return 'failed';
}
}
+31 -3
View File
@@ -69,10 +69,37 @@ export class ProfileError extends Error {
}
}
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
/** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */
export class ProfileChangedError extends Error {
constructor(public updatedAt: string) {
super('The church profile was changed by someone else since you opened it.');
}
}
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
/**
* The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form
* that doesn't know `branding.style` (or sends only the style) never drops the rest.
*/
export function mergeProfile(base: Record<string, unknown>, input: unknown): Record<string, unknown> {
if (!isObject(input)) return { ...base };
const next: Record<string, unknown> = { ...base, ...input };
if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding };
return next;
}
/**
* Saves changes (merged onto what's there) from an admin here or a product (`church.update`),
* and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since.
*/
export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise<Church> {
const current = await storedProfile(ctx);
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
if (opts.ifUpdatedAt) {
const now = current.updatedAt ?? new Date(0).toISOString();
if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now);
}
const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input);
const check = profileInputSchema.safeParse(next);
if (!check.success) {
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
@@ -92,6 +119,7 @@ export async function branding(ctx: Ctx) {
shortName: c.shortName,
logoUrl: c.branding.logoUrl,
colours: c.branding.colours,
style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null },
signupEnabled: await ctx.settings.bool('signup_enabled', true),
};
}
+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 () => {
@@ -8,7 +8,8 @@ import type Provider from 'oidc-provider';
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { clientIp, loginEvent } from '../lib/audit.js';
import { sendSignInNotice } from '../accounts/signInNotice.js';
import { resetPasswordEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
@@ -44,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const clientId = String(details.params.client_id ?? '') || null;
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
await signedInThrough(ctx, clientId, pending.accountId);
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
return { stage: 'done', redirectTo, ...extra };
}
+17
View File
@@ -206,3 +206,20 @@ export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Bu
: 'Email from Accounts works.';
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
}
/** A sign-in happened (1.6.0, as Cross Events' "New login detected"). `whatsapp`: the same in a few lines. */
export async function newSignInEmail(ctx: Ctx, o: { name?: string | null; when: string; location: string; device: string; site: string | null }): Promise<Built & { whatsapp: string }> {
const b = await brand(ctx);
const row = (k: string, v: string) => `<tr><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#64748b;font-size:13px;font-weight:600;width:34%">${esc(k)}</td><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#1e293b;font-size:14px;word-break:break-word">${esc(v)}</td></tr>`;
const body = title('New sign-in', `Someone signed in to your ${b.name} account`)
+ hello(o.name)
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin:0 0 8px 0">`
+ row('When', o.when) + (o.site ? row('Signed in to', o.site) : '') + row('Where (roughly)', o.location) + row('Device', o.device)
+ '</table>'
+ callout(`<strong>Not you?</strong> Change your password straight away from your account page, and let the church office know${contactLine(b)}.`, 'warning')
+ small('If this was you, there\'s nothing to do.');
const lines = [`When: ${o.when}`, ...(o.site ? [`Signed in to: ${o.site}`] : []), `Where (roughly): ${o.location}`, `Device: ${o.device}`];
const text = `Hello ${o.name || 'there'},\n\nSomeone signed in to your ${b.name} account.\n\n${lines.join('\n')}\n\nIf this wasn't you, change your password straight away and let the church office know${b.email ? ` (${b.email})` : ''}.\nIf it was you, there's nothing to do.`;
const whatsapp = `🔐 *New sign-in*\n\nHello ${o.name || 'there'}, someone signed in to your *${b.name}* account.\n\n${lines.join('\n')}\n\nNot you? Change your password straight away and let the church office know.`;
return { subject: `New sign-in to your ${b.name} account`, text, html: layout(b, body, `New sign-in: ${o.when}, ${o.device}.`), whatsapp };
}
+1 -1
View File
@@ -9,7 +9,7 @@ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_i
/** The settings an admin may read and change through the generic settings API. */
export const ADMIN_SETTINGS = new Set([
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
'wawp_access_token', 'wawp_instance_id',
]);
+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);
+39 -2
View File
@@ -27,10 +27,14 @@ import { newAccountEmail, testEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { appVersion } from '../lib/version.js';
import { BUILT_IN_VERSION } from '../privacy/notice.js';
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js';
import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js';
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
const PROFILE_EDITORS = new Set(['website']);
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
@@ -303,6 +307,38 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
return reply({ removed, kept });
}
case 'people.check': {
// 1.5.0: the product's regular check that its copies are current. Profiles only for people
// this product knows; a deleted account is said to be deleted (its sub was that person's).
const subs = [...new Set(r.subs)];
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId));
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a]));
const people = subs.map((sub) => {
const a = accounts.get(sub);
if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null };
if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null };
return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) };
});
const count = (s: string) => people.filter((p) => p.status === s).length;
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people });
}
case 'church.update': {
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
// checks it's the Website, that the person signs in through it, and audits it as theirs.
if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403);
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } });
if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403);
try {
const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt });
await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) });
return reply({ church });
} catch (e) {
if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409);
if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400);
throw e;
}
}
case 'church.branding': {
const changed = await applyLook(ctx, r.church, r.overwrite);
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
@@ -382,7 +418,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
}
const out = await handle(ctx, provider, link, secret, request, req);
// Checks write nothing, so they needn't be remembered.
const isCheck = 'check' in request && request.check;
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
if (!isCheck) {
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
}
@@ -0,0 +1,108 @@
// church.update (contracts 1.17.0, Accounts 1.7.0, WEBSITE-1.0-PLAN decision 10): the Website's
// admin changes shared profile facts through Accounts, and the brand style is kept by every save.
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, describe, test } from 'node:test';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, signedHeaders } from '@crosscode/contracts/signing';
import { startHarness, type Harness } from './support/harness.js';
import { church, mergeProfile, updateProfile } from '../src/church/profile.js';
const WEBSITE_ID = '7e2a1c3d-9b4f-4d6e-8f70-2b3c4d5e6f70';
const EVENTS_ID = '8f3b2d4e-0c5a-4e7f-9a81-3c4d5e6f7a81';
let h: Harness;
const secrets: Record<string, string> = {};
let editor: string;
before(async () => {
h = await startHarness();
for (const [id, product] of [[WEBSITE_ID, 'website'], [EVENTS_ID, 'events']] as const) {
secrets[id] = newLinkSecret();
await h.db.productLink.create({
data: { installId: id, product, url: `https://${product}.hope.test`, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secrets[id]!), connectedAt: new Date() },
});
}
const a = await h.makeAccount({ email: 'editor@hope.test' });
editor = a.id as string;
for (const linkId of [WEBSITE_ID, EVENTS_ID]) await h.db.productPerson.create({ data: { linkId, accountId: editor, via: 'sign_in', createdAt: new Date() } });
await updateProfile(h.ctx, { name: 'Hope Family Church', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } } });
});
after(async () => { await h.close(); });
async function ask(body: Record<string, unknown>, from = WEBSITE_ID) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: editor, type: 'church.update', ...body });
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret: secrets[from]!, rawBody: raw });
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}
describe('church.update from the Website', () => {
test('changes only the style, keeps the colours and logo, and goes live at once', async () => {
const res = await ask({ church: { branding: { style: { fontPairing: 'warm', corners: 'round' } } } });
assert.equal(res.status, 200, JSON.stringify(res.body));
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'round' });
assert.equal(c.branding.colours.primary, '#1f4e79');
assert.equal(c.name, 'Hope Family Church');
assert.deepEqual((res.body.church as { branding: unknown }).branding, c.branding);
});
test('tells every linked product the profile changed, and audits it as the editor', async () => {
const before = await h.db.delivery.count();
const res = await ask({ church: { shortName: 'Hope Family' } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.ok((await h.db.delivery.count()) > before);
const log = await h.db.auditLog.findFirst({ where: { action: 'church_profile_changed_by_product' }, orderBy: { createdAt: 'desc' } });
assert.equal(log?.actorId, editor);
});
test('refuses another product, someone who doesn\'t sign in through the Website, and a stale edit', async () => {
const events = await ask({ church: { name: 'Hijacked' } }, EVENTS_ID);
assert.equal(events.status, 403);
assert.equal(events.body.code, 'WRONG_PRODUCT');
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
const notKnown = await ask({ actor: stranger.id as string, church: { name: 'Hijacked' } });
assert.equal(notKnown.status, 403);
assert.equal(notKnown.body.code, 'NOT_ALLOWED');
const stale = await ask({ ifUpdatedAt: '2020-01-01T00:00:00.000Z', church: { name: 'Hijacked' } });
assert.equal(stale.status, 409);
assert.equal(stale.body.code, 'PROFILE_CHANGED');
assert.equal((await church(h.ctx)).name, 'Hope Family Church');
});
test('takes an edit made on the current version', async () => {
const current = await church(h.ctx);
const res = await ask({ ifUpdatedAt: current.updatedAt, church: { serviceTimes: [{ day: 'sunday', time: '09:00', label: null, campus: null, note: null }] } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal((await church(h.ctx)).serviceTimes.length, 1);
});
test('an invalid value is refused with what\'s wrong', async () => {
const res = await ask({ church: { contact: { email: null, phone: '016 123', whatsapp: null, address: null } } });
assert.equal(res.status, 400);
assert.equal(res.body.code, 'INVALID_REQUEST');
});
});
describe('saving the profile keeps the brand style', () => {
test('an admin form that sends branding without the style doesn\'t drop it', async () => {
await updateProfile(h.ctx, { branding: { style: { fontPairing: 'classic', corners: 'sharp' } } });
await updateProfile(h.ctx, { branding: { logoUrl: null, iconUrl: null, colours: { primary: '#204060', accent: null } } });
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'classic', corners: 'sharp' });
assert.equal(c.branding.colours.primary, '#204060');
});
test('mergeProfile replaces other fields whole and merges branding', () => {
const merged = mergeProfile({ name: 'A', social: [1], branding: { logoUrl: 'x', colours: { primary: '#000000' } } }, { social: [], branding: { colours: { primary: '#ffffff' } } });
assert.deepEqual(merged, { name: 'A', social: [], branding: { logoUrl: 'x', colours: { primary: '#ffffff' } } });
});
test('the sign-in pages get the style', async () => {
const res = await fetch(`${h.publicUrl}/api/v2/branding`);
const b = (await res.json()) as { style: unknown };
assert.deepEqual(b.style, { fontPairing: 'classic', corners: 'sharp' });
});
});
@@ -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', () => {
@@ -199,6 +199,29 @@ describe('people.* from a product', () => {
assert.equal(again.body.created, true);
});
test('1.5.0 people.check: profiles of the product\'s people, deleted accounts, and unknown for the rest; never stored', async () => {
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
const known = await ensure('Check Known', 'check.known@hope.test');
const gone = await ensure('Check Gone', 'check.gone@hope.test');
await h.db.account.update({ where: { id: gone }, data: { status: 'deleted' } });
const off = await ensure('Check Off', 'check.off@hope.test');
await h.db.account.update({ where: { id: off }, data: { status: 'deactivated' } });
const stranger = (await h.makeAccount({ email: 'check.stranger@hope.test' })).id as string;
const nobody = crypto.randomUUID();
const requestId = crypto.randomUUID();
const res = await ask({ type: 'people.check', subs: [known, gone, off, stranger, nobody] }, { requestId });
assert.equal(res.status, 200, JSON.stringify(res.body));
const bySub = Object.fromEntries((res.body.people as { sub: string; status: string; profile: { name: string } | null }[]).map((p) => [p.sub, p]));
assert.equal(bySub[known]!.status, 'active');
assert.equal(bySub[known]!.profile!.name, 'Check Known');
assert.equal(bySub[gone]!.status, 'deleted');
assert.equal(bySub[gone]!.profile, null);
assert.equal(bySub[off]!.status, 'deactivated');
assert.deepEqual([bySub[stranger]!.status, bySub[stranger]!.profile], ['unknown', null], 'not known through this product: no profile');
assert.equal(bySub[nobody]!.status, 'unknown');
assert.equal(await h.db.productRequest.findUnique({ where: { requestId } }), null, 'the reply holds profiles: not kept');
});
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
const requestId = crypto.randomUUID();
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
@@ -0,0 +1,50 @@
// 1.6.0: a "New sign-in" email (and WhatsApp) after each sign-in, as Cross Events sends.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { startHarness, type Harness } from './support/harness.js';
import { describeDevice, sendSignInNotice } from '../src/accounts/signInNotice.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
describe('sign-in notices', () => {
test('an email with when, where, the device and the site; WhatsApp too for a verified number', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.person@hope.test' });
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: '127.0.0.1', userAgent: CHROME_WIN, clientId: 'accounts-self' }), 'sent');
const mail = m.emails.filter((e) => e.to === 'notice.person@hope.test').at(-1)!;
assert.match(mail.subject, /^New sign-in to your .+ account$/);
assert.match(mail.text, /Device: Chrome on Windows/);
assert.match(mail.text, /Signed in to: Your account page/);
assert.match(mail.html ?? '', /Not you\?/);
await h.db.account.update({ where: { id: a.id as string }, data: { phone: '+27821234567', phoneVerified: true } });
m.whatsappOn = true;
const before = m.whatsapps.length;
await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null });
assert.equal(m.whatsapps.length, before + 1);
assert.match(m.whatsapps.at(-1)!.text, /New sign-in/);
m.whatsappOn = false;
});
test('admins can switch them off; a failing email never throws', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.off@hope.test' });
await h.ctx.settings.set('signin_notices', 'false');
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'off');
await h.ctx.settings.set('signin_notices', null);
m.emailOn = false;
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'failed');
m.emailOn = true;
});
test('device names', () => {
assert.equal(describeDevice(CHROME_WIN), 'Chrome on Windows');
assert.equal(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone or iPad');
assert.equal(describeDevice(null), 'Unknown device');
});
});
+43
View File
@@ -0,0 +1,43 @@
import AxeBuilder from "@axe-core/playwright";
import { expect, test } from "@playwright/test";
// 1.7.0 (WEBSITE-1.0-PLAN §3, §9): the church's brand style and shared footer on Accounts' public
// pages. The e2e church (e2e/server.ts) has the "warm" pairing, round corners and service times.
const PRODUCT = "http://localhost:5211";
test("the sign-in page uses the church's fonts and corners, and shows its footer", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm");
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
const heading = page.getByRole("heading", { name: "Sign in to Hope Family Church" });
expect(await heading.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Fraunces");
expect(await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Nunito Sans");
// The font files themselves load from this site (self-hosted), not from anyone else.
await page.evaluate(() => document.fonts.ready);
expect(await page.evaluate(() => document.fonts.check('600 20px "CC Fraunces"'))).toBe(true);
expect(await page.getByRole("button", { name: "Sign in" }).evaluate((el) => getComputedStyle(el).borderRadius)).toBe("9999px");
const footer = page.locator("footer");
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
await expect(footer).toContainText("Sundays 09:00");
await expect(footer.getByRole("link", { name: "office@hope.test" })).toHaveAttribute("href", "mailto:office@hope.test");
await expect(footer.getByRole("link", { name: "Website" })).toHaveAttribute("href", PRODUCT);
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/privacy");
});
test("fonts never come from another site", async ({ page }) => {
const foreign: string[] = [];
page.on("request", (r) => { if (/\.(woff2?|ttf|otf)(\?|$)/.test(r.url()) && !r.url().startsWith("http://localhost:3210/")) foreign.push(r.url()); });
await page.goto(`${PRODUCT}/start?returnTo=/`);
await page.evaluate(() => document.fonts.ready);
expect(foreign).toEqual([]);
});
test("the sign-in page with the footer passes axe (WCAG 2.2 AA)", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.locator("footer")).toBeVisible();
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
});
+7 -1
View File
@@ -29,7 +29,13 @@ const messenger = new MemoryMessenger();
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
await ctx.settings.setMany({
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
// 1.7.0: a brand style, service times and contact details, so the pages show the church's fonts and footer.
church_profile: JSON.stringify({
name: 'Hope Family Church', shortName: 'Hope',
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' }, style: { fontPairing: 'warm', corners: 'round' } },
serviceTimes: [{ day: 'sunday', time: '09:00', label: 'Morning service', campus: null, note: null }],
contact: { email: 'office@hope.test', phone: '+27161234567', whatsapp: null, address: null },
}),
});
const linkSecret = newLinkSecret();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
+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.4.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>}
@@ -2,7 +2,8 @@
import Link from "next/link";
import { useState } from "react";
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
import { Card, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -20,12 +21,12 @@ export function ConfirmEmail({ token }: { token: string }) {
return () => { alive = false; };
}, [token]);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading>Your email address</Heading>
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
<Link href="/account" className="text-brand underline">Back to your account</Link>
</Card>
</Shell>
</PublicShell>
);
}
+184 -36
View File
@@ -2,14 +2,18 @@
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";
import { useExternalEffect } from "@/lib/hooks";
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
import { BrandStyle } from "./BrandStyle";
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
@@ -25,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;
@@ -34,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 (
@@ -49,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} />}
{section === "church" && <Church 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", "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} />}
@@ -69,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);
@@ -93,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>
@@ -125,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>
);
@@ -140,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) => (
@@ -188,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);
@@ -229,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">
@@ -252,13 +398,14 @@ function Linked({ flash }: { flash: Flash }) {
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
signup_enabled: ["Members can create their own account", "bool"],
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
signin_notices: ["Tell people by email (and WhatsApp) each time they sign in", "bool"],
session_days: ['Days "Keep me signed in" lasts', "number"],
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
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;
@@ -266,9 +413,10 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
return () => { alive = false; };
}, []);
if (!values) return <p className="text-gray-600">Loading…</p>;
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
return (
<Card>
<Heading icon={icon} sub={sub}>{title}</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
@@ -279,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]!;
@@ -316,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.{" "}
@@ -337,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>
@@ -355,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>
@@ -386,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>}
@@ -0,0 +1,98 @@
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { CORNERS, FONT_PAIRING_IDS, FONT_PAIRINGS, type Corners, type FontPairing } from "@crosscode/contracts";
import { Button } from "@crosscode/ui";
import { Card, Heading } from "@/components/Panel";
import { call } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Style = { fontPairing: FontPairing | null; corners: Corners | null };
type ChurchStyle = { branding: { style?: Style } };
const CORNER_LABELS: Record<Corners, { name: string; radius: string }> = {
sharp: { name: "Sharp", radius: "0" },
soft: { name: "Soft", radius: "0.5rem" },
round: { name: "Round", radius: "9999px" },
};
/**
* The church's brand style (1.7.0, WEBSITE-1.0-PLAN §3): a font pairing and corners, shared by
* Accounts' pages, the Website and Cross Events. Each option is shown in its own fonts (fonts.css
* is loaded on every page; a pairing's files download only when shown).
*/
export function BrandStyle({ flash }: { flash: (tone: "success" | "error", text: string) => void }) {
const router = useRouter();
const [saved, setSaved] = useState<Style | null>(null);
const [style, setStyle] = useState<Style>({ fontPairing: null, corners: null });
const [busy, setBusy] = useState(false);
useExternalEffect(() => {
let alive = true;
call<ChurchStyle>("GET", "/admin/church").then((r) => {
if (!alive || !r.ok) return;
const s = { fontPairing: r.data.branding.style?.fontPairing ?? null, corners: r.data.branding.style?.corners ?? null };
setSaved(s);
setStyle(s);
});
return () => { alive = false; };
}, []);
if (!saved) return null;
const changed = saved.fontPairing !== style.fontPairing || saved.corners !== style.corners;
const option = (selected: boolean) => `block cursor-pointer rounded-xl border p-4 transition focus-within:ring-2 focus-within:ring-brand/50 ${selected ? "border-brand bg-brand/5 ring-1 ring-brand" : "border-gray-200 hover:border-gray-300"}`;
return (
<Card className="mt-6">
<Heading sub="How the church's sites look: these sign-in pages, the website and Cross Events' public pages. Colours and logo are above.">Brand style</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
const r = await call<ChurchStyle>("PUT", "/admin/church", { branding: { style } });
setBusy(false);
if (r.ok) {
setSaved(style);
flash("success", "Saved. The church's sites use the new style.");
router.refresh();
} else flash("error", r.error.message);
}}>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Fonts</legend>
<p className="mb-3 text-sm text-gray-600">A font for headings and one for text. The website&apos;s template recommends three, but any works.</p>
<div className="grid gap-3 sm:grid-cols-2">
<label className={option(style.fontPairing === null)}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === null} onChange={() => setStyle({ ...style, fontPairing: null })} />
<span className="block text-lg font-semibold [font-family:ui-sans-serif,system-ui,sans-serif]">Device fonts</span>
<span className="mt-1 block text-sm text-gray-600 [font-family:ui-sans-serif,system-ui,sans-serif]">Each phone and computer&apos;s own. The website uses its template&apos;s fonts.</span>
</label>
{FONT_PAIRING_IDS.map((id) => {
const p = FONT_PAIRINGS[id];
return (
<label key={id} className={option(style.fontPairing === id)} data-cc-fonts={id}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === id} onChange={() => setStyle({ ...style, fontPairing: id })} />
<span className="block text-lg font-semibold [font-family:var(--cc-font-heading)] [font-variation-settings:var(--cc-heading-variation,normal)]">{p.name}: Welcome home</span>
<span className="mt-1 block text-sm text-gray-700 [font-family:var(--cc-font-body)]">{p.feel}. <em>Sundays at 09:00.</em></span>
<span className="mt-2 block text-xs text-gray-500 [font-family:ui-sans-serif,system-ui,sans-serif]">{p.heading.family}{p.body.family !== p.heading.family && ` and ${p.body.family}`}</span>
</label>
);
})}
</div>
</fieldset>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Corners</legend>
<p className="mb-3 text-sm text-gray-600">Of buttons, cards, photos and fields.</p>
<div className="grid grid-cols-3 gap-3">
{CORNERS.map((id) => (
<label key={id} className={option((style.corners ?? "soft") === id)}>
<input type="radio" name="corners" className="sr-only" checked={(style.corners ?? "soft") === id} onChange={() => setStyle({ ...style, corners: id })} />
<span className="mb-2 block h-8 w-full bg-brand" style={{ borderRadius: CORNER_LABELS[id].radius }} aria-hidden />
<span className="block text-sm font-medium">{CORNER_LABELS[id].name}</span>
</label>
))}
</div>
</fieldset>
<Button type="submit" busy={busy} disabled={!changed}>Save</Button>
</form>
</Card>
);
}
@@ -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" />;
}
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call } from "@/lib/api";
@@ -12,7 +13,7 @@ export function Forgot({ uid }: { uid: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
{sent ? (
@@ -32,6 +33,6 @@ export function Forgot({ uid }: { uid: string | null }) {
)}
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
</Card>
</Shell>
</PublicShell>
);
}
@@ -10,4 +10,11 @@
body {
@apply bg-gray-50 text-gray-900 antialiased;
/* 1.7.0: the church's font pairing when it has one (@crosscode/ui fonts.css), else the system font. */
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
}
h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
+7 -4
View File
@@ -1,8 +1,10 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { BrandingProvider } from "@/components/BrandingProvider";
import { loadBranding, rgbVars } from "@/lib/branding";
import { loadBranding, loadChurch, rgbVars } from "@/lib/branding";
export async function generateMetadata(): Promise<Metadata> {
const b = await loadBranding();
@@ -12,15 +14,16 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get("x-nonce") ?? undefined;
const b = await loadBranding();
const [b, church] = await Promise.all([loadBranding(), loadChurch()]);
const vars = rgbVars(b.colours.primary);
// 1.7.0: the church's font pairing and corners (fonts.css), shared with its other sites.
return (
<html lang="en-ZA">
<html lang="en-ZA" {...brandAttributes(b.style)}>
<head>
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
</head>
<body>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded, church }}>
{children}
</BrandingProvider>
</body>
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
@@ -11,7 +12,7 @@ export function Reset({ token }: { token: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
{error && <Notice tone="error">{error}</Notice>}
@@ -29,6 +30,6 @@ export function Reset({ token }: { token: string | null }) {
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
</form>
</Card>
</Shell>
</PublicShell>
);
}
@@ -1,18 +1,19 @@
"use client";
import { LogOut } from "lucide-react";
import { Card, Heading, Shell } from "@crosscode/ui";
import { Card, Heading } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { selfSignIn } from "@/lib/api";
export default function SignedOutPage() {
const branding = useBranding();
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You&apos;re signed out</Heading>
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
</Card>
</Shell>
</PublicShell>
);
}
@@ -3,7 +3,8 @@
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
import React, { useState } from "react";
import QRCode from "qrcode";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Checkbox, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { NoticeText } from "@/components/NoticeText";
import { call, type ApiError } from "@/lib/api";
@@ -82,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) {
return r;
};
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
const frame = (children: React.ReactNode) => <PublicShell><Card>{children}</Card></PublicShell>;
if (codes) {
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
@@ -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>
);
}
@@ -1,8 +1,10 @@
"use client";
import React, { createContext, useContext } from "react";
import type { FooterChurch } from "@crosscode/ui";
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
/** `church` (1.7.0): the profile for the shared footer, null when it couldn't be loaded. */
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean; church?: FooterChurch | null };
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
@@ -0,0 +1,16 @@
"use client";
import React from "react";
import { ChurchFooter, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
/**
* The frame of the public pages (sign in, forgot, reset, signed out, confirm email) with the
* church's shared footer (1.7.0, WEBSITE-1.0-PLAN §9): its service times, contact and links to its
* other sites, as on the Website and Cross Events.
*/
export function PublicShell({ children }: { children: React.ReactNode }) {
const branding = useBranding();
const footer = branding.church ? <ChurchFooter church={branding.church} current="accounts" privacyUrl="/privacy" /> : undefined;
return <Shell branding={branding} footer={footer}>{children}</Shell>;
}
@@ -1,9 +1,13 @@
import type { FooterChurch } from "@crosscode/ui";
/** The church's branding from the backend, for the server-rendered frame of every page. */
export type BrandingData = {
name: string;
shortName: string | null;
logoUrl: string | null;
colours: { primary: string; accent: string | null };
/** 1.7.0: the font pairing and corners (null: not picked). */
style?: { fontPairing: string | null; corners: string | null };
signupEnabled: boolean;
setupNeeded: boolean;
};
@@ -20,6 +24,17 @@ export async function loadBranding(): Promise<BrandingData> {
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
}
/** The church profile (`crosscode.church/1`) for the shared footer (1.7.0), or null while it can't be had. */
export async function loadChurch(): Promise<FooterChurch | null> {
try {
const res = await fetch(`${api}/api/church/v1`, { next: { revalidate: 60 } });
if (res.ok) return (await res.json()) as FooterChurch;
} catch {
// As loadBranding: the page works without it.
}
return null;
}
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
export function rgbVars(hex: string): { brand: string; dark: string } {
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
+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;
+3 -2
View File
@@ -13,8 +13,9 @@ curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/ma
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
```
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
Add `--central` on the central (FastPanel) server: there the agent only runs `check-ports`,
`probe-ports`, `status`, `update-agent`, and `frp-read` / `frp-write` (frps's config, from the
server's page on the Hub; agent 1.4.0+). The script installs Node 24 if needed, the agent in
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
`crosscode-agent.service`.
+75
View File
@@ -0,0 +1,75 @@
# What's new in the server agent
What each version of the Cross Code server agent changes, for whoever runs the Hub. The Hub shows
these notes on its Releases page and when you pick a version under Update agent.
<!--
How this file is used: the Cross Code Hub reads it from main every 15 minutes (release source
"Server agent", tags agent@1.2.3) and shows a section only once its version is tagged, so write it
before tagging; fixes to old sections show straight away. Each version is a "## 1.2.3" heading; add
"— urgent" (or "security") to the heading for a security or serious bug fix. Under it, lines
starting with "- " show as a list and other lines as paragraphs.
Write for the person updating servers: what the agent can now do from the Hub, and which Hub or
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
those go, and the church keeps the others. Naming every product it still has removes the whole
church, so the last product to go takes the church with it. Before, uninstalling a church's Cross
Events also removed its Accounts.
- The Hub (2.12.0 and later) uninstalls one product only on servers with this agent; older agents
can only remove the whole church.
## 1.4.0
- **frp's config from the Hub.** The agent finds frps's config (central server) or frpc's (church
server) wherever it is: the path set on the Hub, the `-c` in the systemd unit, or the usual places.
It reads INI and TOML.
- **Changing it from the Hub:** the agent checks the new file with `frp* verify`, keeps a backup,
restarts frp if asked, and puts the old file back if frp doesn't start. Secret values never leave
the server.
- **Ports checked before an install:** the Hub asks this server and the central server which ports
are free, so a new install gets ports free on both.
- Needed for frp config on a server's page and port checks (Hub 2.11.0).
## 1.3.1
- **Fix:** 1.3.0 reported itself as 1.2.0, so the Hub refused its .env jobs. It now reports its
real version. Install this instead of 1.3.0.
## 1.3.0
- **A site's .env from the Hub.** The agent reads an install's .env (secret values hidden) and
changes it: one file at a time, rebuilding the site when its frontend settings changed,
restarting it, and putting the old file back if the site doesn't answer.
- Needed for the Settings (.env) tab on an install's page (Hub 2.8.0).
## 1.2.0
- **Demo data from the Hub.** The agent loads a demo profile onto a site marked as a demo: a backup
first, then the demo data, keeping one admin account.
- Needed for demo sites (Hub 2.4.0).
## 1.1.1
- **Fix:** the server's stats now keep going while a long job runs. Before, a 30-minute install
stopped them and the Hub alerted that the server was down.
- **Fix:** 1.1.0 reported itself as 1.0.1; it now reports its real version.
## 1.1.0
- **Accounts installs.** The agent installs Accounts, and adds a product next to a church's others
on the same server (with the ports and release the Hub chose).
## 1.0.1
- **Fix:** on the central server, Check status failed (it has no `crosscode` script). It now answers
with its own stats, including whether frps is running.
## 1.0.0
- **The first server agent.** It polls the Hub every 30 seconds for signed jobs, runs the
`crosscode` script for them (install, update, status, export, uninstall), sends the results, and
sends the server's stats every minute. It listens on no port: every request goes out to the Hub.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.3.1",
"version": "1.5.0",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
+17 -48
View File
@@ -1,51 +1,15 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import { paths } from "./paths";
import type { FrpSettings } from "./frp";
import { portAllowed } from "./frp";
export { parseFrpsIni, portAllowed } from "./frp";
/**
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
* The central server (AGENT-1.0-PLAN §6): the `check-ports` job after an install. Are the new
* tunnel's ports allowed by frps, open, and bound to 127.0.0.1 only? frps's config is found and
* read by ./frp.ts (INI or TOML, wherever it is).
*/
export interface FrpsSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
}
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
export function parseFrpsIni(text: string): FrpsSettings {
let inCommon = false;
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
if (!m) continue;
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
}
return out;
}
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
try {
return parseFrpsIni(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
export function portAllowed(port: number, allowPorts: string | null): boolean {
if (!allowPorts) return true;
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
const [a, b] = range.split("-").map((n) => Number(n.trim()));
if (!Number.isFinite(a)) return false;
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
});
}
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
export function parseSs(text: string): Map<number, string[]> {
const out = new Map<number, string[]>();
@@ -72,11 +36,16 @@ export interface PortCheck {
ok: boolean;
}
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
export function checkPorts(
ports: number[],
frps: Pick<FrpSettings, "proxyBindAddr" | "allowPorts"> | null,
listening: Map<number, string[]>,
configPath: string | null = null,
): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } {
const warnings: string[] = [];
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
if (!frps) warnings.push(configPath ? `frps's config isn't at ${configPath} (Hub → the central server → frp config).` : "frps's config wasn't found (Hub → the central server → frp config: set where it is).");
const bind = frps?.proxyBindAddr ?? null;
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 (frps.toml: proxyBindAddr = "127.0.0.1") in ${configPath ?? "frps's config"}.`);
const results = ports.map((port) => {
const addrs = listening.get(port) ?? [];
const allowed = portAllowed(port, frps?.allowPorts ?? null);
@@ -86,9 +55,9 @@ export function checkPorts(ports: number[], frps: FrpsSettings | null, listening
for (const r of results) {
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1 (${(listening.get(r.port) ?? []).join(", ")}).`);
}
return { ports: results, proxyBindAddr: bind, warnings };
return { ports: results, proxyBindAddr: bind, configPath, warnings };
}
export function listeningNow(): Promise<Map<number, string[]>> {
+8 -4
View File
@@ -3,7 +3,7 @@ import type { agent } from "@crosscode/contracts";
/**
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
* as an array passed straight to the process (never through a shell). Jobs the agent handles
* itself (update-agent, check-ports) have none.
* itself (update-agent, check-ports, frp-read, frp-write, probe-ports) have none.
*
* `--config <file>` is added by the runner when the job brings config; `--json` always.
*/
@@ -62,15 +62,19 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, "--out", opts.exportFile];
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
case "uninstall":
return ["uninstall", job.args.church, "--confirm", job.args.church];
// 1.5.0: only the products named go (the church keeps its others); none named: the church.
return ["uninstall", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "purge":
return ["purge", job.args.church, "--confirm", job.args.church];
return ["purge", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "status":
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
case "update-agent":
case "check-ports":
case "frp-read":
case "frp-write":
case "probe-ports":
return null;
}
}
+454
View File
@@ -0,0 +1,454 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { paths } from "./paths";
/**
* frp's config on this server (agent 1.4.0): frps's on the central server, frpc's on a church
* server. The agent finds the file itself (the path set from the Hub, else the systemd unit's
* `-c`, else a usual place), reads frp's two formats (INI and TOML), hides secret values before
* anything leaves the server, and writes a new file from the Hub the careful way: secrets put
* back, `verify`, a backup, a restart, and the old file back when the service doesn't come up.
*/
export type FrpService = "frps" | "frpc";
export type FrpSource = (typeof agent.FRP_CONFIG_SOURCES)[number];
export const serviceFor = (mode: agent.AgentMode): FrpService => (mode === "central" ? "frps" : "frpc");
// ─── Where the file is ────────────────────────────────────────────────────────
/** frps.toml, frpc.ini, frps-main.toml … */
const FRP_FILE = /^frp[A-Za-z0-9._-]*\.(ini|toml)$/;
const rememberedFile = () => path.join(paths.stateDir, "frp.json");
/** The path set from the Hub (an `frp-read` with a path), if any. */
export function rememberedPath(): string | null {
try {
const p = JSON.parse(fs.readFileSync(rememberedFile(), "utf8")).path;
return typeof p === "string" && path.isAbsolute(p) && FRP_FILE.test(path.basename(p)) ? p : null;
} catch {
return null;
}
}
export function rememberPath(p: string): void {
fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
fs.writeFileSync(rememberedFile(), `${JSON.stringify({ path: p, at: new Date().toISOString() })}\n`, { mode: 0o600 });
}
/** `-c <file>`, `-c=<file>`, `--config <file>` or `--config=<file>` in a command line. */
export function configFromCommand(argv: string): string | null {
const parts = argv.trim().split(/\s+/);
for (let i = 0; i < parts.length; i++) {
const a = parts[i]!;
const eq = /^(?:-c|--config)=(.+)$/.exec(a);
if (eq) return eq[1]!;
if ((a === "-c" || a === "--config") && parts[i + 1]) return parts[i + 1]!;
}
return null;
}
/** The config and the binary from `systemctl show <unit> -p ExecStart --value` ("{ path=… ; argv[]=… ; … }"). */
export function parseExecStart(text: string): { config: string | null; bin: string | null } {
const argv = /argv\[\]=([^;]*)/.exec(text)?.[1]?.trim() ?? text.trim();
const bin = argv.split(/\s+/)[0] || null;
return { config: configFromCommand(argv), bin: bin && bin.startsWith("/") ? bin : null };
}
function execText(cmd: string, args: string[], timeout = 10_000): Promise<{ ok: boolean; out: string; err: string; missing: boolean }> {
return new Promise((resolve) => {
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({
ok: !err, out: String(stdout ?? ""), err: String(stderr ?? "") || (err ? err.message : ""), missing: (err as NodeJS.ErrnoException | null)?.code === "ENOENT",
}));
});
}
async function fromSystemd(service: FrpService): Promise<{ config: string | null; bin: string | null }> {
const r = await execText("systemctl", ["show", service, "-p", "ExecStart", "--value"]);
return r.ok ? parseExecStart(r.out) : { config: null, bin: null };
}
/** Where frp is usually kept, in the order the agent looks. */
export function usualPlaces(service: FrpService): string[] {
const dirs = ["/etc/frp", `/etc/${service}`, "/usr/local/etc/frp", "/usr/local/frp", "/opt/frp", `/opt/${service}`, "/root/frp"];
return dirs.flatMap((d) => [`${d}/${service}.toml`, `${d}/${service}.ini`]);
}
export interface FoundConfig {
path: string | null;
source: FrpSource | null;
/** frps / frpc as the systemd unit runs it (for `verify`), else the name on PATH. */
bin: string;
looked: string[];
}
const exists = (f: string) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
let cache: { at: number; mode: agent.AgentMode; found: FoundConfig } | null = null;
/** The config this server's frp uses. The Hub's path wins (even when the file isn't there: the Hub then says so). */
export async function findConfig(mode: agent.AgentMode, opts: { fresh?: boolean } = {}): Promise<FoundConfig> {
if (!opts.fresh && cache && cache.mode === mode && Date.now() - cache.at < 5 * 60_000) return cache.found;
const service = serviceFor(mode);
const unit = await fromSystemd(service);
const bin = unit.bin ?? service;
const looked: string[] = [];
let found: FoundConfig | null = null;
const hub = rememberedPath();
// The old setting (agent 1.0–1.3) still works, for a server that set it in the unit.
const env = mode === "central" ? process.env.CROSSCODE_FRPS_INI : process.env.CROSSCODE_FRPC_INI;
if (hub) found = { path: hub, source: "hub", bin, looked };
else if (env) found = { path: env, source: "hub", bin, looked };
else {
const candidates: Array<[string, FrpSource]> = [];
if (unit.config) candidates.push([unit.config, "systemd"]);
for (const p of usualPlaces(service)) candidates.push([p, "usual-place"]);
for (const [p, source] of candidates) {
looked.push(p);
if (exists(p)) { found = { path: p, source, bin, looked: [] }; break; }
}
}
const result = found ?? { path: null, source: null, bin, looked: looked.slice(0, 20) };
cache = { at: Date.now(), mode, found: result };
return result;
}
export function forgetFound(): void {
cache = null;
}
// ─── Reading INI and TOML ─────────────────────────────────────────────────────
export type FrpFormat = "ini" | "toml";
export const formatOf = (file: string, text = ""): FrpFormat => (file.endsWith(".toml") ? "toml" : file.endsWith(".ini") ? "ini" : /^\s*\[common\]/m.test(text) ? "ini" : "toml");
interface Line {
/** `[common]`, `[[proxies]]`: the header the line is under ("" before any), with how many came before it. */
section: string;
sectionIndex: number;
key: string;
/** The value as written, after `=` (quotes kept, comments after it dropped for TOML). */
raw: string;
/** The value without quotes. */
value: string;
/** Where `raw` starts and ends in the line. */
start: number;
end: number;
}
function unquote(v: string): string {
const t = v.trim();
if ((t.startsWith('"') && t.endsWith('"') && t.length >= 2) || (t.startsWith("'") && t.endsWith("'") && t.length >= 2)) return t.slice(1, -1);
return t;
}
/** Each `key = value` line, with the section it's in. */
export function lines(text: string, format: FrpFormat): Array<Line | null> {
let section = "";
const seen = new Map<string, number>();
let sectionIndex = 0;
return text.split("\n").map((rawLine) => {
const line = rawLine.replace(/\r$/, "");
const t = line.trim();
if (!t || t.startsWith("#") || t.startsWith(";")) return null;
const header = /^(\[\[?[^\]]+\]\]?)\s*(#.*)?$/.exec(t);
if (header) {
section = header[1]!.replace(/\s+/g, "");
sectionIndex = seen.get(section) ?? 0;
seen.set(section, sectionIndex + 1);
return null;
}
const m = /^(\s*)([A-Za-z0-9_.-]+|"[^"]+")(\s*=\s*)(.*)$/.exec(line);
if (!m) return null;
let raw = m[4]!;
if (format === "toml") {
// A comment after the value (outside quotes).
let q: string | null = null;
for (let i = 0; i < raw.length; i++) {
const c = raw[i]!;
if (q) { if (c === q && raw[i - 1] !== "\\") q = null; continue; }
if (c === '"' || c === "'") q = c;
else if (c === "#") { raw = raw.slice(0, i); break; }
}
}
raw = raw.replace(/\s+$/, "");
const start = m[1]!.length + m[2]!.length + m[3]!.length;
return { section, sectionIndex, key: m[2]!.replace(/"/g, ""), raw, value: unquote(raw), start, end: start + raw.length };
});
}
export interface FrpSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
/** Ports frpc's proxies use (remote and local), or frps's own ports (bind, dashboard …). */
usedPorts: number[];
}
/** TOML's allowPorts = [{ start = 2000, end = 3000 }, { single = 3001 }] → "2000-3000,3001". */
export function tomlAllowPorts(text: string): string | null {
const m = /^\s*allowPorts\s*=\s*\[([\s\S]*?)\]\s*$/m.exec(text);
if (!m) return null;
const out: string[] = [];
for (const obj of m[1]!.matchAll(/\{([^}]*)\}/g)) {
const single = /single\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
const start = /start\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
const end = /end\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
if (single) out.push(single);
else if (start && end) out.push(`${start}-${end}`);
else if (start) out.push(start);
}
return out.length ? out.join(",") : null;
}
const PORT_KEYS = /^(remote_?port|remotePort|local_?port|localPort|bind_?port|bindPort|kcp_?bind_?port|kcpBindPort|quic_?bind_?port|quicBindPort|vhost_?http_?port|vhostHTTPPort|vhost_?https_?port|vhostHTTPSPort|dashboard_?port|admin_?port|webServer\.port|port|tcpmux_?httpconnect_?port|tcpmuxHTTPConnectPort)$/;
export function parseSettings(text: string, format: FrpFormat): FrpSettings {
const all = lines(text, format).filter((l): l is Line => !!l);
const used = new Set<number>();
for (const l of all) {
if (!PORT_KEYS.test(l.key)) continue;
// INI: `remote_port = 6000`; frpc's `local_port` of a proxy is a port on the server too.
for (const n of l.value.split(/[,\s]+/)) if (/^\d+$/.test(n)) used.add(Number(n));
}
if (format === "ini") {
const common = all.filter((l) => l.section === "[common]");
const get = (k: string) => common.find((l) => l.key === k)?.value || null;
return { proxyBindAddr: get("proxy_bind_addr"), allowPorts: get("allow_ports"), usedPorts: [...used].sort((a, b) => a - b) };
}
const top = all.filter((l) => l.section === "");
return {
proxyBindAddr: top.find((l) => l.key === "proxyBindAddr")?.value || null,
allowPorts: tomlAllowPorts(text),
usedPorts: [...used].sort((a, b) => a - b),
};
}
/** Keeps the old helper's shape (agent ≤ 1.3 tests and stats). */
export function parseFrpsIni(text: string): { proxyBindAddr: string | null; allowPorts: string | null } {
const s = parseSettings(text, "ini");
return { proxyBindAddr: s.proxyBindAddr, allowPorts: s.allowPorts };
}
// ─── Secrets ──────────────────────────────────────────────────────────────────
/** token, auth.token, dashboard_pwd, webServer.password, oidc client secret, privilege_token … */
const SECRET_KEY = /(token|pwd|passw(or)?d|secret|private_?key|privateKey|credential)/i;
export const isSecretKey = (key: string): boolean => SECRET_KEY.test(key);
/** A secret key, or an inline table with one in it (auth = { token = "…" }). */
const INLINE_SECRET = /[{,]\s*[A-Za-z0-9_.]*(token|pwd|passw(or)?d|secret|private_?key|credential)[A-Za-z0-9_]*\s*=/i;
const isSecretLine = (l: Line): boolean => isSecretKey(l.key) || INLINE_SECRET.test(l.raw);
const idOf = (l: Line) => `${l.section}#${l.sectionIndex}/${l.key}`;
const nameOf = (l: Line) => (l.section && !l.section.startsWith("[[") && l.section !== "[common]" ? `${l.section.replace(/[[\]]/g, "")}.${l.key}` : l.key);
function hiddenRaw(raw: string): string {
const t = raw.trim();
if (t.startsWith('"')) return `"${agent.FRP_HIDDEN}"`;
if (t.startsWith("'")) return `'${agent.FRP_HIDDEN}'`;
return agent.FRP_HIDDEN;
}
/** The file with secret values replaced, and their names. */
export function hideSecrets(text: string, format: FrpFormat): { content: string; hidden: string[] } {
const hidden: string[] = [];
const src = text.split("\n");
lines(text, format).forEach((l, i) => {
if (!l || !isSecretLine(l) || !l.value) return;
const line = src[i]!;
src[i] = line.slice(0, l.start) + hiddenRaw(l.raw) + line.slice(l.end);
hidden.push(nameOf(l));
});
return { content: src.join("\n"), hidden: [...new Set(hidden)].slice(0, 50) };
}
/**
* A file from the Hub with the server's secret values put back. Refused when it changes a secret,
* or has a hidden value the server's file has no value for.
*/
export function restoreSecrets(incoming: string, current: string, format: FrpFormat): { ok: true; content: string } | { ok: false; message: string } {
const now = new Map<string, Line>();
for (const l of lines(current, format)) if (l && isSecretLine(l)) now.set(idOf(l), l);
const src = incoming.split("\n");
const parsed = lines(incoming, format);
for (let i = 0; i < parsed.length; i++) {
const l = parsed[i];
if (!l || !isSecretLine(l)) continue;
const old = now.get(idOf(l));
if (l.value === agent.FRP_HIDDEN) {
if (!old) return { ok: false, message: `${nameOf(l)} shows ${agent.FRP_HIDDEN}, but the file on the server has no value for it there. Secrets are set on the server.` };
src[i] = src[i]!.slice(0, l.start) + old.raw + src[i]!.slice(l.end);
} else if (l.value && (!old || old.value !== l.value)) {
return { ok: false, message: `${nameOf(l)} is a secret: it can't be set or changed from the Hub. Change it on the server.` };
}
}
return { ok: true, content: src.join("\n") };
}
// ─── Read, write ──────────────────────────────────────────────────────────────
/** systemd's view of a unit: true / false, or null when there's no systemctl. */
export async function serviceActive(unit: string): Promise<boolean | null> {
const r = await execText("systemctl", ["is-active", unit]);
if (r.missing) return null;
return r.out.trim() === "active";
}
export interface FrpDeps {
/** For tests: systemctl and `frp* verify`. */
exec?: (cmd: string, args: string[]) => Promise<{ ok: boolean; out: string; err: string; missing: boolean }>;
wait?: (ms: number) => Promise<void>;
}
export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise<agent.FrpReadResult> {
const service = serviceFor(mode);
if (opts.path) {
if (exists(opts.path)) rememberPath(opts.path);
forgetFound();
}
const found = opts.path ? { ...(await findConfig(mode, { fresh: true })), ...(exists(opts.path) ? {} : { path: opts.path, source: "hub" as const }) } : await findConfig(mode, { fresh: true });
const exec = deps.exec ?? execText;
const running = await (async () => { const r = await exec("systemctl", ["is-active", service]); return r.missing ? null : r.out.trim() === "active"; })();
const base = { service, path: found.path, source: found.source, serviceRunning: running, readAt: new Date().toISOString() };
let text: string | null = null;
if (found.path) {
try {
const st = fs.statSync(found.path);
if (st.size > agent.FRP_CONFIG_MAX) throw new Error(`${found.path} is ${st.size} bytes; the Hub shows files up to ${agent.FRP_CONFIG_MAX}.`);
text = fs.readFileSync(found.path, "utf8");
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
}
if (text === null) {
return { ...base, found: false, format: null, content: null, hidden: [], proxyBindAddr: null, allowPorts: null, looked: found.path ? [found.path] : found.looked };
}
const format = formatOf(found.path!, text);
const settings = parseSettings(text, format);
const { content, hidden } = hideSecrets(text, format);
return {
...base, found: true, format, content, hidden,
proxyBindAddr: service === "frps" ? settings.proxyBindAddr : null,
allowPorts: service === "frps" ? settings.allowPorts : null,
};
}
export interface WriteOutcome {
status: agent.JobStatus;
message?: string;
steps: agent.ReportStep[];
result: Record<string, unknown>;
}
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
export async function writeConfig(mode: agent.AgentMode, args: { path: string; content: string; restart: boolean }, deps: FrpDeps = {}): Promise<WriteOutcome> {
const exec = deps.exec ?? execText;
const wait = deps.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
const service = serviceFor(mode);
const steps: agent.ReportStep[] = [];
const step = (name: string, outcome: agent.ReportStep["outcome"], detail?: string) => {
const at = new Date().toISOString();
steps.push({ name, startedAt: at, finishedAt: at, outcome, ...(detail ? { detail: detail.slice(0, 2000) } : {}) });
};
const refuse = (message: string): WriteOutcome => ({ status: "refused", message, steps, result: {} });
const found = await findConfig(mode, { fresh: true });
if (found.path !== args.path) return refuse(`This server's ${service} config is ${found.path ?? "not found"}, not ${args.path}. Read it again on the Hub first.`);
if (!path.basename(args.path).startsWith(service)) return refuse(`${args.path} isn't ${service}'s config (the name must start with ${service}).`);
let current: string;
try { current = fs.readFileSync(args.path, "utf8"); } catch { return refuse(`There's no file at ${args.path} to replace.`); }
const format = formatOf(args.path, current);
const restored = restoreSecrets(args.content.replace(/\r\n/g, "\n"), current, format);
if (!restored.ok) return refuse(restored.message);
const next = restored.content.endsWith("\n") ? restored.content : `${restored.content}\n`;
if (next === current) {
step("Compare", "skipped", "The file is already like this; nothing changed.");
return { status: "succeeded", message: "Nothing changed: the file is already like this.", steps, result: await readConfig(mode, {}, deps) as unknown as Record<string, unknown> };
}
const dir = path.dirname(args.path);
const tmp = path.join(dir, `.${path.basename(args.path)}.crosscode-${process.pid}${path.extname(args.path)}`);
const mode0 = fs.statSync(args.path).mode & 0o777;
fs.writeFileSync(tmp, next, { mode: mode0 });
try {
const v = await exec(found.bin, ["verify", "-c", tmp]);
if (v.missing) { step(`${service} verify`, "failed", `${found.bin} wasn't found.`); return { status: "failed", message: `${found.bin} wasn't found, so the new config couldn't be checked; nothing changed.`, steps, result: {} }; }
if (!v.ok) { step(`${service} verify`, "failed", `${v.out}\n${v.err}`.trim()); return { status: "failed", message: `${service} verify refused the new config, so nothing changed: ${(v.err || v.out).trim().slice(0, 500)}`, steps, result: {} }; }
step(`${service} verify`, "ok");
} catch (e) {
fs.rmSync(tmp, { force: true });
throw e;
}
const backups = path.join(dir, "backups");
fs.mkdirSync(backups, { recursive: true, mode: 0o700 });
const backup = path.join(backups, `${path.basename(args.path)}.${stamp()}`);
fs.copyFileSync(args.path, backup);
fs.chmodSync(backup, mode0);
fs.renameSync(tmp, args.path);
step("Replace the config", "ok", `Backup: ${backup}`);
if (!args.restart) {
step(`Restart ${service}`, "skipped", "Not asked: the new config is used when frp next starts.");
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
}
const restart = await exec("systemctl", ["restart", service]);
await wait(3000);
const up = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
if (restart.ok && up) {
step(`Restart ${service}`, "ok");
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
}
step(`Restart ${service}`, "failed", restart.err || `${service} isn't running after the restart.`);
fs.copyFileSync(backup, args.path);
await exec("systemctl", ["restart", service]);
await wait(3000);
const back = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
step("Put the old config back", back ? "rolled-back" : "failed", back ? `${service} runs with the old config again.` : `${service} isn't running with the old config either: look at it on the server (journalctl -u ${service}).`);
return {
status: back ? "rolled-back" : "failed",
message: back ? `${service} didn't start with the new config, so the old one was put back.` : `${service} didn't start with the new config, and isn't running after putting the old one back either.`,
steps,
result: { ...(await readConfig(mode, {}, deps)), backup },
};
}
// ─── Free ports (probe-ports) ─────────────────────────────────────────────────
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
export function portAllowed(port: number, allowPorts: string | null): boolean {
if (!allowPorts) return true;
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
const [a, b] = range.split("-").map((n) => Number(n.trim()));
if (!Number.isFinite(a)) return false;
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
});
}
export function probePorts(ports: number[], mode: agent.AgentMode, settings: FrpSettings | null, listening: Map<number, string[]>, configPath: string | null): agent.ProbePortsResult {
const used = new Set(settings?.usedPorts ?? []);
return {
configPath,
ports: ports.map((port) => {
const addrs = listening.get(port);
if (addrs?.length) return { port, free: false, reason: `In use: something listens on ${[...new Set(addrs)].join(", ")}.` };
if (mode === "central" && settings && !portAllowed(port, settings.allowPorts)) return { port, free: false, reason: "Not in frps's allow_ports." };
if (used.has(port)) return { port, free: false, reason: `Used in ${mode === "central" ? "frps" : "frpc"}'s config.` };
return { port, free: true, reason: null };
}),
};
}
/** The settings of the config this server uses, or null when there's none. */
export async function currentSettings(mode: agent.AgentMode): Promise<{ path: string | null; settings: FrpSettings | null }> {
const found = await findConfig(mode);
if (!found.path) return { path: null, settings: null };
try {
const text = fs.readFileSync(found.path, "utf8");
return { path: found.path, settings: parseSettings(text, formatOf(found.path, text)) };
} catch {
return { path: found.path, settings: null };
}
}
+23 -3
View File
@@ -2,7 +2,8 @@ import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { encryptExport } from "@crosscode/contracts/signing";
import { checkPorts, listeningNow, readFrps } from "./central";
import { checkPorts, listeningNow } from "./central";
import { currentSettings, findConfig, probePorts, readConfig, writeConfig } from "./frp";
import { crosscodeArgs } from "./command";
import type { AgentConfig, Keys } from "./config";
import { type HubClient, HubRequestError } from "./hub";
@@ -153,10 +154,25 @@ export class Agent {
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
}
case "check-ports": {
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
const { path: configPath, settings } = await currentSettings("central");
const res = checkPorts(job.args.ports, settings, await listeningNow(), configPath);
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-read": {
const result = await readConfig(this.deps.config.mode, { path: job.args.path });
const message = result.found ? undefined : `No ${result.service} config found${result.path ? ` at ${result.path}` : ""}.`;
return { status: result.found ? "succeeded" : "failed", steps: [], result: result as unknown as Record<string, unknown>, message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "frp-write": {
const w = await writeConfig(this.deps.config.mode, job.args);
return { status: w.status, steps: w.steps, result: w.result, message: w.message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "probe-ports": {
const { path: configPath, settings } = await currentSettings(this.deps.config.mode);
const result = probePorts(job.args.ports, this.deps.config.mode, settings, await listeningNow(), configPath);
return { status: "succeeded", steps: [], result: result as unknown as Record<string, unknown>, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "export":
return await this.runExport(job, limit);
case "status":
@@ -181,7 +197,11 @@ export class Agent {
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
if (this.deps.run) return this.deps.run(args, job);
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
return (async () => {
// crosscode edits frpc's config on installs: tell it where the file is (agent 1.4.0).
const frpc = this.deps.config.mode === "church" ? (await findConfig("church").catch(() => null))?.path : null;
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit, env: frpc ? { FRPC_INI: frpc } : {} });
})();
}
/**
-2
View File
@@ -15,8 +15,6 @@ export const paths = {
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
/** frps.ini on the central server. */
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
/** The churches on a church server. */
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
};
+3 -1
View File
@@ -27,6 +27,8 @@ export interface RunOptions {
sealedConfig?: agent.Sealed | null;
x25519Pem: string;
timeLimitMinutes: number;
/** Extra environment for crosscode (FRPC_INI). */
env?: Record<string, string>;
/** For tests. */
bin?: string;
}
@@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
const child = spawn(opts.bin ?? paths.crosscode, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
env: { ...process.env, ...opts.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
});
let timedOut = false;
const timer = setTimeout(() => {
+5 -4
View File
@@ -3,7 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { agent } from "@crosscode/contracts";
import { readFrps } from "./central";
import { currentSettings, serviceActive } from "./frp";
import { paths } from "./paths";
/**
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.3.1";
export const AGENT_VERSION = "1.5.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
@@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentSt
frpcRunning,
processes,
};
const frp = await currentSettings(mode).catch(() => ({ path: null, settings: null }));
stats.frpConfigPath = frp.path;
if (mode === "central") {
const frps = readFrps();
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
stats.central = { proxyBindAddr: frp.settings?.proxyBindAddr ?? null, allowPorts: frp.settings?.allowPorts ?? null, frpsRunning: await serviceActive("frps") };
}
return stats;
}
+4
View File
@@ -36,6 +36,10 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
// 1.5.0: one product of the church.
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope", products: ["events"] } }))).toEqual(["uninstall", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope", products: ["events"] } }))).toEqual(["purge", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] } }), { exportFile: "/x/e.zip" })).toEqual(["export", "hope", "accounts", "--out", "/x/e.zip"]);
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
});
+167
View File
@@ -0,0 +1,167 @@
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import {
configFromCommand, findConfig, forgetFound, hideSecrets, parseExecStart, parseSettings, probePorts, readConfig, restoreSecrets, writeConfig,
} from "../src/frp";
import { tempState } from "./helpers";
const H = agent.FRP_HIDDEN;
const TOML = `bindPort = 7000
proxyBindAddr = "127.0.0.1"
auth.token = "s3cret-token" # the shared token
allowPorts = [
{ start = 20000, end = 29999 },
{ single = 3001 },
]
[webServer]
port = 7500
password = 'dash-pass'
`;
const FRPC_INI = `[common]
server_addr = 203.0.113.10
server_port = 7000
token = abc123
[hope-events-web]
type = tcp
local_ip = 127.0.0.1
local_port = 20010
remote_port = 20010
`;
const noSystemd = async () => ({ ok: false, out: "", err: "", missing: true });
describe("finding frp's config", () => {
it("reads -c from the systemd unit", () => {
expect(configFromCommand("/usr/local/bin/frps -c /usr/local/frp/frps.toml")).toBe("/usr/local/frp/frps.toml");
expect(configFromCommand("/usr/bin/frps --config=/etc/frps/frps.ini")).toBe("/etc/frps/frps.ini");
expect(configFromCommand("/usr/bin/frps")).toBeNull();
expect(parseExecStart("{ path=/usr/local/bin/frps ; argv[]=/usr/local/bin/frps -c /opt/frp/frps.toml ; ignore_errors=no ; start_time=[n/a] }"))
.toEqual({ config: "/opt/frp/frps.toml", bin: "/usr/local/bin/frps" });
});
it("the path from the Hub wins, and is remembered", async () => {
const dir = tempState();
const file = path.join(dir, "frps.toml");
fs.writeFileSync(file, TOML);
forgetFound();
const exec = async () => ({ ok: true, out: "active\n", err: "", missing: false });
const r = await readConfig("central", { path: file }, { exec });
expect(r).toMatchObject({ found: true, source: "hub", path: file, format: "toml", proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001", serviceRunning: true });
forgetFound();
expect((await findConfig("central", { fresh: true })).path).toBe(file);
});
it("a path that isn't there is reported, not remembered", async () => {
const dir = tempState();
forgetFound();
const r = await readConfig("central", { path: path.join(dir, "nope", "frps.ini") }, { exec: noSystemd });
expect(r).toMatchObject({ found: false, content: null });
expect(fs.existsSync(path.join(dir, "frp.json"))).toBe(false);
});
});
describe("frp settings, INI and TOML", () => {
it("TOML", () => {
expect(parseSettings(TOML, "toml")).toMatchObject({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001" });
expect(parseSettings(TOML, "toml").usedPorts).toEqual(expect.arrayContaining([7000, 7500]));
});
it("INI: frpc's tunnels use their ports", () => {
expect(parseSettings(FRPC_INI, "ini").usedPorts).toEqual([20010]);
});
});
describe("secrets never leave the server", () => {
it("are hidden in TOML and INI, keeping the quotes", () => {
const t = hideSecrets(TOML, "toml");
expect(t.content).toContain(`auth.token = "${H}" # the shared token`);
expect(t.content).toContain(`password = '${H}'`);
expect(t.content).not.toMatch(/s3cret|dash-pass/);
expect(t.hidden).toEqual(["auth.token", "webServer.password"]);
const i = hideSecrets(FRPC_INI, "ini");
expect(i.content).toContain(`token = ${H}`);
expect(i.content).not.toContain("abc123");
});
it("in inline tables too", () => {
expect(hideSecrets(`auth = { method = "token", token = "zzz" }\n`, "toml").content).not.toContain("zzz");
});
it("are put back on write, and can't be changed from the Hub", () => {
const shown = hideSecrets(TOML, "toml").content.replace("bindPort = 7000", "bindPort = 7001");
const back = restoreSecrets(shown, TOML, "toml");
expect(back.ok && back.content).toBe(TOML.replace("bindPort = 7000", "bindPort = 7001"));
expect(restoreSecrets(shown.replace(`"${H}"`, '"new"'), TOML, "toml")).toMatchObject({ ok: false, message: expect.stringMatching(/auth.token is a secret/) });
expect(restoreSecrets(`${shown}\n[extra]\ntoken = "${H}"\n`, TOML, "toml")).toMatchObject({ ok: false });
});
});
describe("writing the config", () => {
const setup = () => {
const dir = tempState();
const file = path.join(dir, "frps.toml");
fs.writeFileSync(file, TOML);
fs.writeFileSync(path.join(dir, "frp.json"), JSON.stringify({ path: file }));
forgetFound();
return { dir, file };
};
const shown = () => hideSecrets(TOML, "toml").content;
it("verify, backup, replace, restart", async () => {
const { dir, file } = setup();
const calls: string[] = [];
const exec = async (cmd: string, args: string[]) => { calls.push(`${cmd} ${args.join(" ")}`); return { ok: true, out: "active", err: "", missing: false }; };
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("succeeded");
expect(fs.readFileSync(file, "utf8")).toContain("bindPort = 7001");
expect(fs.readFileSync(file, "utf8")).toContain("s3cret-token");
expect(fs.readdirSync(path.join(dir, "backups"))).toHaveLength(1);
expect(calls.some((c) => / verify -c /.test(c))).toBe(true);
expect(calls).toContain("systemctl restart frps");
expect(JSON.stringify(r.result)).not.toContain("s3cret");
});
it("verify refuses: nothing changes", async () => {
const { file } = setup();
const exec = async (cmd: string) => ({ ok: cmd === "systemctl", out: "", err: "bad key", missing: false });
const r = await writeConfig("central", { path: file, content: "nonsense = [", restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("failed");
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
});
it("frps doesn't come back: the old file is put back", async () => {
const { file } = setup();
let restarts = 0;
const exec = async (_cmd: string, args: string[]) => {
if (args[0] === "restart") restarts++;
if (args[0] === "is-active") return { ok: true, out: restarts >= 2 ? "active" : "failed", err: "", missing: false };
return { ok: true, out: "", err: "", missing: false };
};
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
expect(r.status).toBe("rolled-back");
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
});
it("only the file the agent uses", async () => {
const { dir } = setup();
const r = await writeConfig("central", { path: path.join(dir, "frpc.toml"), content: "x = 1", restart: false }, { exec: noSystemd });
expect(r.status).toBe("refused");
});
});
describe("free ports before an install", () => {
it("central: not listening and inside allow_ports", () => {
const listening = new Map([[20001, ["0.0.0.0"]]]);
const r = probePorts([20000, 20001, 30000], "central", parseSettings(TOML, "toml"), listening, "/etc/frp/frps.toml");
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20000, true], [20001, false], [30000, false]]);
});
it("church: not listening and not in frpc's tunnels", () => {
const r = probePorts([20010, 20011], "church", parseSettings(FRPC_INI, "ini"), new Map(), "/etc/frp/frpc.ini");
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20010, false], [20011, true]]);
});
it("with no config found, listening is all it can check", () => {
expect(probePorts([20010], "central", null, new Map(), null).ports[0]!.free).toBe(true);
});
});
+77
View File
@@ -5,6 +5,83 @@ 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). **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
- **The church's fonts and corners on the public pages.** The backend reads the church profile from
Accounts (`GET /api/church/v1`, kept for 10 minutes; `src/accounts/church.ts`) and the public
pages get it from the new `GET /api/v2/church` (public). `<html>` gets `brandAttributes(style)`
from `@crosscode/ui` and the root layout imports `@crosscode/ui/fonts.css` (self-hosted, so no
font is loaded from another site). Body text and h1–h3 use `--cc-font-body` and
`--cc-font-heading` when the church picked a pairing, and `--radius` follows the corner style
(`soft` is 0.5rem, the same as before). The dashboard and setup screens (`data-cc-staff`) keep
the system fonts and 0.5rem.
- **`church.changed` from Accounts** at `POST /api/church/v1/changed` (signed with the Accounts
link, `LINK_HEADERS`): the profile is fetched again on the next page. Before 3.7.0 this answered
404 and Accounts kept retrying for a week.
- **The shared church footer** (`ChurchFooter`, `@crosscode/ui` 0.3.0) on the public pages when
Accounts is connected: name and logo, service times, address, contact, social links and links
to the church's other sites and the privacy notice, with Terms of Use and cookie settings below.
Without Accounts, and on the dashboard (`<Footer plain />`), the footer is as before.
- **Links to the church's other sites** in the header of the public pages (its Website, later its
App), from the profile's `links`.
### Changed
- `@crosscode/ui` 0.3.0: `ChurchFooter` takes `bottom` (a product's own links after the copyright).
- Frontend: `transpilePackages: ["@crosscode/ui"]`; Tailwind scans `packages/ui/src` and has
`brand` (brand-700) for the shared footer.
## [3.6.1] - 2026-11-20
### Fixed
- **Uploading a logo or favicon under Settings → Branding failed on some servers** with "The logo was
uploaded, but the site can't show it yet". The upload worked, but on a server whose proxy has a
rule for file extensions (static-file caching) every `/api/…` path ending in `.png`, `.ico`,
`.pdf`, `.json` and so on went to the site (Next.js), which answered 404. So the check after the
upload failed, as did pictures, certificate PDFs and `/api/v2/openapi.json`. Two changes:
- The site passes `/api/*` and `/uploads/*` that reach it on to the backend
(`next.config.ts` rewrites, `beforeFiles`). New frontend setting `BACKEND_INTERNAL_URL`
(`http://127.0.0.1:<apiPort>`, added to `.env.production` on deploy). Unset, nothing is
passed on, as before. The end-to-end tests' `E2E_API_PROXY` uses the same rewrites.
- The nginx site the installers write (and DEPLOYMENT.md) sends `/api/` and `/uploads/` to the
backend with `location ^~`, so no regex location can take them. Existing servers keep their
nginx file: change it by hand (DEPLOYMENT.md §4).
## [3.6.0] - 2026-11-20
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
### Added
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
## [3.5.0] - 2026-11-20
### Fixed
+26 -15
View File
@@ -127,13 +127,17 @@ server {
access_log /var/log/nginx/hope-events.access.log hope_proxy;
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
@@ -147,7 +151,10 @@ server {
```
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
unchanged (frps picks the site by its host name). Send every path through as it is: no
`location ~* \.(png|css|js…)$` caching rules for this site on the VPS, which would send
`/api/uploads/…/logo.png` to the site instead of the backend. (Since 3.6.1 the site passes such
requests on to the backend itself, but they're slower that way.) For nginx on the VPS, roughly:
```nginx
server {
@@ -188,13 +195,17 @@ server {
client_max_body_size 25m;
access_log /var/log/nginx/hope-events.access.log hope_proxy;
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
+26
View File
@@ -12,6 +12,32 @@ 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.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 →
Brand style (as your sign-in pages, and later your church website, do), and a new footer shows your service times,
address, contact details, social links and links to your other sites. The dashboard looks the same
as before.
## 3.6.1
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
the site can't show it yet", depending on how the server is set up. Uploaded pictures, certificate
downloads and the like now show on those servers too.
## 3.6.0
- **People's details are checked every night.** Cross Events compares everyone's name, email,
phone and news choices with their church account and fixes any that are out of date, and handles
accounts that were deleted, in case a change never reached this site. You can see it, run it or
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
## 3.5.0
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.5.0",
"version": "3.7.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -0,0 +1,67 @@
/**
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
* social, the church's other sites). Accounts owns it and serves it publicly at
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
*
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
* copy is kept and it's tried again after a minute; a site without Accounts has none, and its
* pages look as they always have.
*/
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import { accountsLink } from './client';
const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000;
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
let cached: Cached | null = null;
let pending: Promise<Church | null> | 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;
}
/** The church's profile, or null when Accounts isn't connected or hasn't answered yet. Never throws. */
export async function churchProfile(): Promise<Church | null> {
let link;
try {
link = await accountsLink();
} catch {
return cached?.church ?? null;
}
if (!link) return null;
const url = link.url;
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
if (!pending) {
const last = cached?.url === url ? cached.church : null;
pending = fetchProfile(url)
.then((church) => {
cached = { url, church, at: Date.now(), ok: true };
return church;
}, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message);
cached = { url, church: last, at: Date.now(), ok: false };
return last;
})
.finally(() => { pending = null; });
}
return pending;
}
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
export function churchChanged(): void {
if (cached) cached = { ...cached, at: 0 };
}
/** Tests: start with nothing. */
export function resetChurchProfile(): void {
cached = null;
pending = null;
}
@@ -0,0 +1,102 @@
/**
* The nightly people check (3.6.0, contracts 1.14.0 `people.check`, Accounts 1.5.0): Accounts tells
* Events about every change (`user.updated`, `user.deleted`), retried for about a week; this catches
* whatever never arrived (a link that was down, as after a demo load before 3.5.0). For everyone here
* with an account it asks Accounts, a page at a time, and:
*
* - updates the local copy when the profile differs (as `user.updated` does);
* - handles a deleted account as `user.deleted` does (anonymised, or deferred while the person has a
* registration for an event that hasn't ended);
* - only counts people Accounts doesn't know through this site (`unknown`). When most of a page is
* unknown, Events is probably linked to the wrong Accounts: the check stops and fails, so it
* shows on Background jobs and the Hub, and nothing is changed for those people.
*/
import { PEOPLE_CHECK_MAX, peopleCheckReplySchema, type PeopleCheckReply, type Profile } from '@crosscode/contracts';
import { accounts, accountsLink } from './client';
import { handleAccountsCall } from './calls';
import { viaAccounts } from './mode';
import { recordSignInError } from './status';
import { updateLocalCopy } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
type Local = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
export type PeopleCheckResult = { checked: number; updated: number; deleted: number; deferred: number; deactivated: number; unknown: number } | { skipped: string };
/** Asks Accounts about these subs (tests replace it). */
export type Ask = (subs: string[]) => Promise<PeopleCheckReply>;
const defaultAsk: Ask = async (subs) => {
const auth = await accounts();
const raw = await auth.request({ type: 'people.check', actor: null, subs }, { timeoutMs: 120000 });
return peopleCheckReplySchema.parse(raw);
};
/** Whether the local copy already says what the profile says (only what Events keeps). */
export function sameAsLocal(u: Local, p: Profile): boolean {
return u.name === p.name
&& u.email.toLowerCase() === p.email.toLowerCase()
&& (u.phoneNumber ?? null) === (p.phone_number ?? null)
&& u.newsEmail === p.news_consent.email
&& u.newsWhatsApp === p.news_consent.whatsapp;
}
/** More than this share of a page unknown (with at least MIN_FOR_ALARM people) stops the check. */
const UNKNOWN_ALARM = 0.5;
const MIN_FOR_ALARM = 10;
export async function runPeopleCheck(opts: { ask?: Ask; pageSize?: number } = {}): Promise<PeopleCheckResult> {
if (!(await viaAccounts())) return { skipped: 'This site uses its own sign-in.' };
if (!(await accountsLink())) return { skipped: 'Accounts isn\'t linked.' };
const ask = opts.ask ?? defaultAsk;
const size = Math.min(opts.pageSize ?? PEOPLE_CHECK_MAX, PEOPLE_CHECK_MAX);
const out = { checked: 0, updated: 0, deleted: 0, deferred: 0, deactivated: 0, unknown: 0 };
let cursor: string | undefined;
for (;;) {
const page: Local[] = await prisma.user.findMany({
where: { accountId: { not: null } },
select: { id: true, accountId: true, name: true, email: true, phoneNumber: true, newsEmail: true, newsWhatsApp: true },
orderBy: { id: 'asc' },
take: size,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
});
if (!page.length) break;
cursor = page[page.length - 1]!.id;
const bySub = new Map(page.map((u) => [u.accountId, u]));
let reply: PeopleCheckReply;
try {
reply = await ask(page.map((u) => u.accountId));
} catch (e) {
// Accounts before 1.5.0 doesn't know people.check: nothing to do until it's updated.
const err = e as { code?: string; message?: string };
if (err.code === 'INVALID_REQUEST' && /\btype\b/.test(err.message ?? '')) return { skipped: 'The church\'s Accounts is older than 1.5.0, which this check needs.' };
throw e;
}
const unknown = reply.people.filter((p) => p.status === 'unknown').length;
if (page.length >= MIN_FOR_ALARM && unknown / page.length > UNKNOWN_ALARM) {
const message = `Accounts doesn't know ${unknown} of ${page.length} people here: is this site linked to the church's own Accounts? Nothing was changed for them.`;
await recordSignInError('PEOPLE_UNKNOWN', message);
throw new Error(message);
}
for (const p of reply.people) {
const u = bySub.get(p.sub);
if (!u) continue; // not one we asked about
out.checked++;
if (p.status === 'unknown') { out.unknown++; continue; }
if (p.status === 'deleted') {
const r = await handleAccountsCall({ type: 'user.deleted', sub: p.sub } as never) as { status?: string };
if (r.status === 'deferred') out.deferred++; else out.deleted++;
continue;
}
if (p.status === 'deactivated') out.deactivated++;
if (p.profile && !sameAsLocal(u, p.profile)) {
await updateLocalCopy(u.id, p.profile);
out.updated++;
}
}
if (page.length < size) break;
}
return out;
}
+5
View File
@@ -98,6 +98,11 @@ const JOBS = [
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
},
{
// 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts).
name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED',
run: () => require('../accounts/peopleCheck').runPeopleCheck(),
},
{
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
+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);
+22 -1
View File
@@ -4,6 +4,7 @@
*
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
* POST /api/church/v1/changed church.changed from the church's Accounts (3.7.0)
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
*
@@ -11,11 +12,12 @@
*/
import express, { type Request, type Response, type Router } from 'express';
import rateLimit from 'express-rate-limit';
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import { hubInstallId, publishOn } from '../feed/context';
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
import { churchChanged } from '../accounts/church';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
@@ -74,6 +76,25 @@ export function crossProductRouter(): Router {
}
});
// 3.7.0: the church profile changed in Accounts (its brand style, footer details): fetch it again.
router.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
try {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link || link.product !== 'accounts') return fail(res, 404, 'NOT_LINKED', 'This site has no link with that Accounts.');
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
if (!check.ok) return fail(res, 401, check.code, "The signature doesn't match this link.");
let body: unknown;
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
if (!churchChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', "That isn't a church.changed message.");
churchChanged();
return res.status(202).json({ accepted: true });
} catch (e) {
return sendError(res, e);
}
});
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
try {
return res.json(await acceptConnect(req.body, getClientIp(req)));
+1
View File
@@ -26,6 +26,7 @@ import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
import './resources/signIn';
import './resources/church';
const pkg = require('../../package.json') as { version: string };
@@ -0,0 +1,23 @@
import { churchSchema } from '@crosscode/contracts';
import { defineRoute } from '../route';
import { single } from '../paging';
import { churchProfile } from '../../accounts/church';
/**
* The church profile for the public pages (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): its brand style
* (fonts, corners) and the shared footer's details, from the church's Accounts
* (src/accounts/church.ts). null when Accounts isn't connected.
*/
export const getChurch = defineRoute({
method: 'get',
path: '/church',
tag: 'Site',
summary: "The church's profile",
description: "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.",
access: 'public',
response: single(churchSchema.nullable()),
async handler({ res }) {
res.setHeader('Cache-Control', 'public, max-age=60');
return { data: await churchProfile() };
},
});
@@ -0,0 +1,83 @@
// 3.6.0: the nightly people check against Accounts (contracts 1.14.0 people.check).
type U = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
let mockUsers: U[] = [];
const mockUpdated: string[] = [];
const mockCalls: { type: string; sub: string }[] = [];
const mockErrors: string[] = [];
let mockMode = true;
let mockLinked = true;
let mockDeferred = new Set<string>();
jest.mock('../src/config/db', () => ({
user: {
findMany: async ({ take, cursor }: { take: number; cursor?: { id: string } }) => {
const sorted = [...mockUsers].sort((a, b) => a.id.localeCompare(b.id));
const start = cursor ? sorted.findIndex((u) => u.id === cursor.id) + 1 : 0;
return sorted.slice(start, start + take);
},
},
}));
jest.mock('../src/accounts/mode', () => ({ viaAccounts: async () => mockMode }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => (mockLinked ? { installId: 'acc-1' } : null), accounts: async () => { throw new Error('not in tests'); } }));
jest.mock('../src/accounts/signin', () => ({ updateLocalCopy: async (id: string) => { mockUpdated.push(id); } }));
jest.mock('../src/accounts/calls', () => ({
handleAccountsCall: async (c: { type: string; sub: string }) => { mockCalls.push(c); return { status: mockDeferred.has(c.sub) ? 'deferred' : 'deleted' }; },
}));
jest.mock('../src/accounts/status', () => ({ recordSignInError: async (_c: string, m: string) => { mockErrors.push(m); } }));
import type { PeopleCheckReply, Profile } from '@crosscode/contracts';
import { runPeopleCheck, sameAsLocal } from '../src/accounts/peopleCheck';
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
const user = (n: number, over: Partial<U> = {}): U => ({ id: `u${String(n).padStart(3, '0')}`, accountId: sub(n), name: `Person ${n}`, email: `p${n}@hope.test`, phoneNumber: null, newsEmail: false, newsWhatsApp: false, ...over });
const profile = (u: U, over: Partial<Profile> = {}): Profile => ({ name: u.name, given_name: null, family_name: null, email: u.email, email_verified: true, phone_number: u.phoneNumber, phone_number_verified: false, news_consent: { email: u.newsEmail, whatsapp: u.newsWhatsApp }, ...over });
beforeEach(() => {
mockUsers = []; mockUpdated.length = 0; mockCalls.length = 0; mockErrors.length = 0;
mockMode = true; mockLinked = true; mockDeferred = new Set();
});
test('updates only copies that differ, handles deleted accounts as user.deleted does, counts the rest', async () => {
mockUsers = [user(1), user(2), user(3), user(4), user(5)];
mockDeferred = new Set([sub(4)]);
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({
schema: 'crosscode.identity-request/1',
people: subs.map((s) => {
const u = mockUsers.find((x) => x.accountId === s)!;
if (s === sub(1)) return { sub: s, status: 'active' as const, profile: profile(u) };
if (s === sub(2)) return { sub: s, status: 'active' as const, profile: profile(u, { name: 'New Name', news_consent: { email: true, whatsapp: false } }) };
if (s === sub(3) || s === sub(4)) return { sub: s, status: 'deleted' as const, profile: null };
return { sub: s, status: 'unknown' as const, profile: null };
}),
});
expect(await runPeopleCheck({ ask, pageSize: 2 })).toEqual({ checked: 5, updated: 1, deleted: 1, deferred: 1, deactivated: 0, unknown: 1 });
expect(mockUpdated).toEqual(['u002']);
expect(mockCalls.map((c) => [c.type, c.sub])).toEqual([['user.deleted', sub(3)], ['user.deleted', sub(4)]]);
});
test('stops, changing nothing, when Accounts knows hardly anyone (linked to the wrong Accounts?)', async () => {
mockUsers = Array.from({ length: 12 }, (_, i) => user(i + 1));
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({ schema: 'crosscode.identity-request/1', people: subs.map((s) => ({ sub: s, status: 'unknown' as const, profile: null })) });
await expect(runPeopleCheck({ ask })).rejects.toThrow(/doesn't know 12 of 12/);
expect(mockCalls).toEqual([]);
expect(mockErrors).toHaveLength(1);
});
test('skipped on its own sign-in, or without a link', async () => {
mockMode = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
mockMode = true; mockLinked = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
});
test('sameAsLocal ignores email case and what Events doesn\'t keep', () => {
const u = user(1, { email: 'Jane@Hope.test' });
expect(sameAsLocal(u, profile(u, { email: 'jane@hope.test', email_verified: false, given_name: 'Jane' }))).toBe(true);
expect(sameAsLocal(u, profile(u, { phone_number: '+27821234567' }))).toBe(false);
});
test('an Accounts before 1.5.0 (people.check unknown there) skips the check instead of failing every night', async () => {
mockUsers = [user(1)];
const ask = async () => { throw Object.assign(new Error('Not a crosscode.identity-request/1 request: type Invalid input'), { code: 'INVALID_REQUEST' }); };
expect(await runPeopleCheck({ ask })).toEqual({ skipped: expect.stringContaining('1.5.0') });
});
@@ -0,0 +1,140 @@
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9): the church profile from Accounts for the public pages (its
// brand style and the shared footer), kept in memory and fetched again on church.changed.
import fs from 'fs';
import path from 'path';
import express from 'express';
import request from 'supertest';
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
const mockLinks: Link[] = [];
jest.mock('../src/config/db', () => ({
productLink: {
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
findUnique: async ({ where }: { where: { installId: string } }) => mockLinks.find((l) => l.installId === where.installId) ?? null,
},
}));
jest.mock('../src/jobs', () => ({ enqueueTask: async () => ({ queued: true }) }));
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
import { CHURCH_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { churchProfile, resetChurchProfile } from '../src/accounts/church';
import { crossProductRouter } from '../src/links/routes';
import { getChurch } from '../src/v2/resources/church';
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS
const { encrypt } = require('../src/utils/encryption') as { encrypt(v: string): string };
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const sample = (name: string) => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8'));
const ACCOUNTS_ID = '5c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f';
const SECRET = 'link-secret-for-the-test-0123456789';
let profile = sample('church.json');
let answers: (number | 'down')[] = [];
let fetches = 0;
const realFetch = global.fetch;
beforeAll(() => {
global.fetch = (async (url: string) => {
fetches++;
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
const next = answers.shift() ?? 200;
if (next === 'down') throw new Error('connect ECONNREFUSED');
return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } });
}) as typeof fetch;
});
afterAll(() => { global.fetch = realFetch; });
beforeEach(() => {
resetChurchProfile();
mockLinks.length = 0;
answers = [];
fetches = 0;
profile = sample('church.json');
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => { jest.restoreAllMocks(); });
const connectAccounts = () => mockLinks.push({ installId: ACCOUNTS_ID, product: 'accounts', url: 'https://accounts.hope.test/', secret: encrypt(SECRET), updatedAt: new Date() });
function app() {
const a = express();
a.use('/api', crossProductRouter());
return a;
}
function changed(body: object, { from = ACCOUNTS_ID, secret = SECRET } = {}) {
const raw = JSON.stringify(body);
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret, rawBody: raw });
return request(app()).post(CHURCH_PATHS.changed).set({ 'content-type': 'application/json', ...headers }).send(raw);
}
describe('the church profile', () => {
test('none without Accounts, and nothing is fetched', async () => {
expect(await churchProfile()).toBeNull();
expect(fetches).toBe(0);
});
test("fetched from the church's Accounts, with its brand style, and kept", async () => {
connectAccounts();
const c = await churchProfile();
expect(c?.branding.style).toEqual({ fontPairing: 'warm', corners: 'soft' });
expect(c?.name).toBe(profile.name);
await churchProfile();
expect(fetches).toBe(1);
});
test('a pairing this version doesn\'t know reads as none, so the page keeps its fonts', async () => {
connectAccounts();
profile.branding.style = { fontPairing: 'from-the-future', corners: 'round' };
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: null, corners: 'round' });
});
test('Accounts down: none at first, then the last copy is kept while it is down', async () => {
connectAccounts();
answers = ['down'];
expect(await churchProfile()).toBeNull();
resetChurchProfile();
expect((await churchProfile())?.name).toBe(profile.name);
});
test('a profile that isn\'t crosscode.church/1 isn\'t used', async () => {
connectAccounts();
profile = { hello: 'world' };
expect(await churchProfile()).toBeNull();
});
test('GET /api/v2/church answers it, cacheable for a minute', async () => {
connectAccounts();
const headers: Record<string, string> = {};
const res = { setHeader: (k: string, v: string) => { headers[k] = v; } };
const out = await getChurch.handler({ res } as never);
expect(getChurch.response.safeParse(out).success).toBe(true);
expect((out as { data: { name: string } }).data.name).toBe(profile.name);
expect(headers['Cache-Control']).toBe('public, max-age=60');
});
});
describe('church.changed from Accounts', () => {
test('fetches the profile again (the last copy until then)', async () => {
connectAccounts();
await churchProfile();
profile.branding.style = { fontPairing: 'classic', corners: 'sharp' };
expect((await churchProfile())?.branding.style?.fontPairing).toBe('warm');
const res = await changed(sample('church-changed.json'));
expect(res.status).toBe(202);
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: 'classic', corners: 'sharp' });
expect(fetches).toBe(2);
});
test('refuses a wrong signature, a sender that isn\'t Accounts and a body that isn\'t church.changed', async () => {
connectAccounts();
mockLinks.push({ installId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', product: 'website', url: 'https://www.hope.test', secret: encrypt(SECRET), updatedAt: new Date() });
expect((await changed(sample('church-changed.json'), { secret: 'not-the-secret-at-all-0123456789' })).status).toBe(401);
expect((await changed(sample('church-changed.json'), { from: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' })).status).toBe(404);
const bad = await changed({ type: 'something.else' });
expect(bad.status).toBe(400);
expect(bad.body.code).toBe('INVALID_REQUEST');
});
});
@@ -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 });
+117
View File
@@ -0,0 +1,117 @@
import path from "path";
import AxeBuilder from "@axe-core/playwright";
import { test, expect, loginAs, seed } from "./fixtures";
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9 and §13): with the church's Accounts connected, the public
// pages use the church's fonts and corners from its profile and the shared church footer, as the
// Website and Accounts' own pages do. The dashboard stays as it is. Accounts runs in memory
// (e2e/support/accounts-server.mts); afterwards the link is removed, so the other specs see the
// site as before.
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
const backend = path.join(__dirname, "..", "backend");
require(require.resolve("dotenv", { paths: [backend] })).config({ path: path.join(backend, ".env") });
const { Client } = require(require.resolve("pg", { paths: [backend] }));
const { e2eDatabaseUrl } = require("./support/db-url");
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
const { encrypt } = require(path.join(backend, "src", "utils", "encryption"));
/* eslint-enable @typescript-eslint/no-require-imports */
const ACCOUNTS_API = "http://127.0.0.1:5221";
const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b";
const TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
async function sql(text: string, values: unknown[] = []) {
const client = new Client({ connectionString: e2eDatabaseUrl() });
await client.connect();
try {
return (await client.query(text, values)).rows;
} finally {
await client.end();
}
}
test.describe.serial("the church's brand style and footer", () => {
test.beforeAll(async () => {
const profile = await fetch(`${ACCOUNTS_API}/test/profile`, {
method: "POST",
body: JSON.stringify({
name: "E2E Church",
branding: { style: { fontPairing: "warm", corners: "round" } },
serviceTimes: [{ day: "sunday", time: "09:00", label: "Morning service", campus: null, note: null }],
contact: { email: "office@e2e.test", phone: "+27161234567", whatsapp: null, address: { line1: "1 Church Street", line2: null, suburb: null, city: "Vereeniging", postalCode: "1939" } },
}),
});
expect(profile.ok, await profile.text()).toBe(true);
// Linked to Accounts, as Connect would (the backend reads the profile from this address).
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
await sql(
`INSERT INTO "ProductLink" ("installId", product, url, "publicKey", secret, "connectedAt", "createdAt", "updatedAt") VALUES ($1, 'accounts', $2, 'x', $3, now(), now(), now())`,
[ACCOUNTS_ID, ACCOUNTS_API, encrypt(signing.newLinkSecret())],
);
});
test.afterAll(async () => {
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
});
test("public pages: the church's fonts, round corners and the shared footer, all from this site", async ({ page }) => {
const elsewhere: string[] = [];
page.on("request", (r) => {
if (r.resourceType() === "font" && !r.url().startsWith("http://localhost:3100/")) elsewhere.push(r.url());
});
// The site keeps the profile for a minute; reload until it's there.
await expect(async () => {
await page.goto("/events");
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm", { timeout: 1000 });
}).toPass({ timeout: 90_000 });
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
await expect(page.getByText("E2E Free Evening")).toBeVisible();
const fonts = await page.evaluate(async () => {
await document.fonts.ready;
const h1 = document.querySelector("h1");
return {
body: getComputedStyle(document.body).fontFamily,
heading: h1 ? getComputedStyle(h1).fontFamily : "",
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
loaded: [...document.fonts].filter((f) => f.status === "loaded").map((f) => f.family.replace(/"/g, "")),
};
});
expect(fonts.body).toContain("CC Nunito Sans");
expect(fonts.heading).toContain("CC Fraunces");
expect(fonts.radius).toBe("0.75rem");
expect(fonts.loaded).toContain("CC Nunito Sans");
const footer = page.locator("footer");
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
await expect(footer).toContainText("Sundays 09:00");
await expect(footer).toContainText("1 Church Street");
await expect(footer.getByRole("link", { name: "+27161234567" })).toHaveAttribute("href", "tel:+27161234567");
await expect(footer.getByRole("link", { name: "Your account" })).toHaveAttribute("href", /127\.0\.0\.1/);
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/legal/privacy");
await expect(footer.getByRole("link", { name: "Terms of Use" })).toBeVisible();
await expect(footer.getByRole("button", { name: /cookie/i })).toBeVisible();
await page.goto(`/events/${seed().events.course}`);
await expect(page.getByRole("heading", { name: "E2E Alpha Course" })).toBeVisible();
await expect(page.locator("footer").getByRole("heading", { name: "Service times" })).toBeVisible();
await page.waitForLoadState("networkidle");
const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
expect(elsewhere).toEqual([]);
});
test("the dashboard keeps its own fonts, corners and footer", async ({ page }) => {
await loginAs(page, "admin");
await page.goto("/dashboard");
await expect(page.locator("[data-cc-staff]").first()).toBeVisible();
await expect(page.locator("main")).toBeVisible();
const look = await page.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
}));
expect(look.body).not.toContain("CC ");
expect(look.radius).toBe("0.5rem");
await expect(page.locator("footer")).toContainText("All rights reserved");
});
});
+16 -1
View File
@@ -5,11 +5,13 @@
* differs from the Events site's (localhost), so their cookies stay apart as on two domains.
*
* Test helpers: POST /test/link { installId, url, secret } links Events, as Connect would;
* GET /test/code?to=<email> answers the last code emailed to that address.
* GET /test/code?to=<email> answers the last code emailed to that address; POST /test/profile changes
* the church profile (3.7.0, church-brand.spec.ts), as an admin's save in Accounts would.
*/
import http from 'node:http';
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
import { createApp } from '../../../accounts/backend/src/app.ts';
import { updateProfile } from '../../../accounts/backend/src/church/profile.ts';
import { createCtx } from '../../../accounts/backend/src/context.ts';
import { loadConfig } from '../../../accounts/backend/src/lib/config.ts';
import { MemoryMessenger } from '../../../accounts/backend/src/lib/messages.ts';
@@ -33,6 +35,19 @@ http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' }).end(messenger.lastCode(to) ?? '');
return;
}
if (req.method === 'POST' && req.url === '/test/profile') {
let body = '';
req.on('data', (c) => { body += c; });
req.on('end', async () => {
try {
const church = await updateProfile(ctx, JSON.parse(body));
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(church));
} catch (e) {
res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ message: (e as Error).message }));
}
});
return;
}
if (req.method === 'POST' && req.url === '/test/link') {
let body = '';
req.on('data', (c) => { body += c; });
+6
View File
@@ -108,6 +108,12 @@
"layer": "install",
"from": "https://{domain}",
"required": true
},
{
"name": "BACKEND_INTERNAL_URL",
"layer": "install",
"from": "http://127.0.0.1:{apiPort}",
"description": "The backend on this server: requests for /api or /uploads that reach the site are passed to it (3.6.1)"
}
]
}
+25 -4
View File
@@ -1,10 +1,21 @@
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
// Requests for the backend (/api, /uploads) that reach the site anyway are passed to it (3.6.1).
// On a server nginx sends those paths to the backend, but a proxy in front can send some to the
// site instead: one with a rule for file extensions (static-file caching) sent every
// /api/uploads/…png here, so an uploaded logo never showed. BACKEND_INTERNAL_URL is the backend on
// this server (http://127.0.0.1:<port>), never the public address, which would come straight back
// here. The end-to-end tests set E2E_API_PROXY (3.0.0): the site and its API on one address, as
// nginx does, so Accounts' sign-in comes back to <site>/api/auth/callback.
const backend = (process.env.BACKEND_INTERNAL_URL || process.env.E2E_API_PROXY || "").replace(/\/+$/, "");
const nextConfig: NextConfig = {
// The end-to-end tests run their own dev server; a separate build folder keeps it
// from clashing with one already running.
distDir: process.env.NEXT_DIST_DIR || ".next",
// The shared fonts and footer (3.7.0) are TypeScript source.
transpilePackages: ["@crosscode/ui"],
images: {
// (images.domains is deprecated in Next 16.)
remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
@@ -12,10 +23,20 @@ const nextConfig: NextConfig = {
compiler: {
removeConsole: process.env.NODE_ENV === 'production',
},
// The end-to-end tests only (3.0.0): the site and its API on one address, as nginx does on a
// server, so Accounts' sign-in comes back to <site>/api/auth/callback. Unset everywhere else.
...(process.env.E2E_API_PROXY
? { async rewrites() { return [{ source: '/api/:path*', destination: `${process.env.E2E_API_PROXY}/api/:path*` }]; } }
...(backend
? {
// beforeFiles: ahead of every page, so a dynamic route like /[redirectUrl] never catches them.
async rewrites() {
return {
beforeFiles: [
{ source: '/api/:path*', destination: `${backend}/api/:path*` },
{ source: '/uploads/:path*', destination: `${backend}/uploads/:path*` },
],
afterFiles: [],
fallback: [],
};
},
}
: {}),
};
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.5.0",
"version": "3.7.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -12,6 +12,7 @@
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"@dnd-kit/core": "^6.3.1",
"@hookform/resolvers": "^5.2.1",
"@radix-ui/react-accordion": "^1.2.11",
@@ -75,7 +75,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
// Don't render protected content until auth state is known
if (loading || !user) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div data-cc-staff className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-sm text-gray-400">Loading…</div>
</div>
);
@@ -88,7 +88,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
// scroll) so the sidebar can be a plain sibling column that never
// scrolls — only the content column (main + footer) scrolls internally.
return (
<div className="h-screen flex flex-col overflow-hidden">
<div data-cc-staff className="h-screen flex flex-col overflow-hidden">
<Navbar />
<LicenceBanner />
<ProviderNotices />
@@ -99,7 +99,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
<Sidebar />
<div className="flex-1 min-w-0 flex flex-col overflow-y-auto">
<main className="flex-1 p-6 bg-gray-50">{children}</main>
<Footer />
<Footer plain />
</div>
</div>
</div>
@@ -107,14 +107,14 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
}
return (
<div className="min-h-screen flex flex-col">
<div data-cc-staff className="min-h-screen flex flex-col">
<Navbar />
<LicenceBanner />
<ProviderNotices />
<PrivacyPrompts />
<CommandPalette />
<main className="flex-1 p-6 bg-gray-50">{children}</main>
<Footer />
<Footer plain />
</div>
);
}
+26 -1
View File
@@ -47,7 +47,8 @@
--input: 214.3 31.8% 91.4%;
--ring: 243 75% 59%;
--radius: 0.5rem;
/* The church's corners (3.7.0, @crosscode/ui fonts.css): soft (0.5rem) unless it picked others. */
--radius: var(--cc-radius-sm, 0.5rem);
/* Fallback brand scale (matches the pre-branding-feature default indigo, brand-600 #4F46E5) */
--brand-50: #EEF2FF;
@@ -73,6 +74,30 @@ html {
scroll-behavior: smooth;
}
/*
* The church's fonts (3.7.0, docs/WEBSITE-1.0-PLAN.md §3 and §9): <html> gets
* data-cc-fonts from its brand style in Accounts, and @crosscode/ui/fonts.css sets these
* variables. Without a pairing they're unset and the page keeps Tailwind's system fonts.
* The dashboard and setup screens (data-cc-staff) stay as they are.
*/
@layer base {
body {
font-family: var(--cc-font-body, theme("fontFamily.sans"));
}
h1,
h2,
h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
html:has([data-cc-staff]) {
--cc-font-body: initial;
--cc-font-heading: initial;
--cc-heading-variation: initial;
--cc-radius-sm: initial;
}
}
/*
* Accessibility (WCAG 2.2 AA, 1.50.0): a clear focus ring for keyboard users on every
* focusable element (mouse clicks don't show it), in the brand colour with a white halo
+10 -2
View File
@@ -1,5 +1,7 @@
import type { Metadata } from "next";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { AuthProvider } from "@/contexts/AuthContext";
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext";
import { ToastProvider } from "@/components/shared/ToastProvider";
@@ -11,6 +13,8 @@ import { ImpersonationBanner } from "@/components/shared/ImpersonationBanner";
import { SkipLink } from "@/components/layout/SkipLink";
import { resolveToApiOrigin } from "@/lib/api";
import { getServerSettings } from "@/lib/serverSettings";
import { getServerChurch } from "@/lib/serverChurch";
import { ChurchProvider } from "@/contexts/ChurchContext";
import { buildThemeCssVars } from "@/lib/colorScale";
import { appUrl } from "@/lib/siteConfig";
@@ -49,7 +53,7 @@ export async function generateMetadata(): Promise<Metadata> {
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const settings = await getServerSettings();
const [settings, church] = await Promise.all([getServerSettings(), getServerChurch()]);
const cssVars = buildThemeCssVars({
primary: settings.primary_color || settings.accent_color,
secondary: settings.secondary_color,
@@ -57,12 +61,15 @@ export default async function RootLayout({ children }: { children: React.ReactNo
});
return (
<html lang="en">
// The church's fonts and corners from Accounts (3.7.0): used by the public pages; the
// dashboard and setup screens keep their own (globals.css, data-cc-staff).
<html lang="en" {...brandAttributes(church?.branding.style)}>
<body>
{cssVars && (
<style id="brand-theme" dangerouslySetInnerHTML={{ __html: `:root{${cssVars}}` }} />
)}
<SkipLink />
<ChurchProvider church={church}>
<SiteSettingsProvider initialSettings={settings}>
<AuthProvider>
<ToastProvider>
@@ -75,6 +82,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
</ToastProvider>
</AuthProvider>
</SiteSettingsProvider>
</ChurchProvider>
</body>
</html>
+1 -1
View File
@@ -247,7 +247,7 @@ export default function SetupPage() {
};
return (
<div className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
<div data-cc-staff className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
<div className={`bg-white rounded-2xl shadow-lg w-full p-8 transition-all ${step === 3 ? "max-w-4xl" : "max-w-lg"}`}>
{/* Heading */}
@@ -1,30 +1,53 @@
"use client";
import Link from "next/link";
import { ChurchFooter } from "@crosscode/ui";
import { appName } from "@/lib/siteConfig";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useChurch } from "@/contexts/ChurchContext";
import { CookieSettingsButton } from "@/components/shared/CookieSettingsButton";
export const Footer = () => {
/**
* The public pages' footer. With the church's Accounts connected (3.7.0) it's the shared church
* footer (as on the Website and Accounts' pages): name and logo, service times, address, contact,
* social links and the church's other sites, with this site's terms and cookie settings below.
* `plain`: the dashboard's own footer, as before.
*/
export const Footer = ({ plain = false }: { plain?: boolean }) => {
const { settings } = useSiteSettings();
const church = useChurch();
const displayName = settings.org_name || appName;
return (
<>
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
<div className="mt-2 space-x-4">
<Link href="/legal/terms" className="hover:underline text-gray-300">
Terms of Use
</Link>
<Link href="/legal/privacy" className="hover:underline text-gray-300">
Privacy Policy
</Link>
<CookieSettingsButton className="hover:underline text-gray-300" />
</div>
</footer>
{church && !plain ? (
<ChurchFooter
church={church}
current="events"
privacyUrl="/legal/privacy"
bottom={
<>
<Link href="/legal/terms" className="hover:underline">Terms of Use</Link>
<CookieSettingsButton className="hover:underline" />
</>
}
/>
) : (
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
<div className="mt-2 space-x-4">
<Link href="/legal/terms" className="hover:underline text-gray-300">
Terms of Use
</Link>
<Link href="/legal/privacy" className="hover:underline text-gray-300">
Privacy Policy
</Link>
<CookieSettingsButton className="hover:underline text-gray-300" />
</div>
</footer>
)}
{/* Spacer so content isn't hidden behind the fixed mobile bottom nav */}
<div className="h-16 md:hidden" aria-hidden="true" />
</>
);
};
};
@@ -9,6 +9,8 @@ import { BottomNav } from "./BottomNav";
import defaultLogo from "@/app/default_logo.png";
import { appName } from "@/lib/siteConfig";
import { resolveToApiOrigin } from "@/lib/api";
import { productLinks } from "@crosscode/ui";
import { useChurch } from "@/contexts/ChurchContext";
type NavLink = {
href: string;
@@ -20,6 +22,10 @@ export const Navbar = () => {
const { user, loading: authLoading, logout } = useAuth();
const { settings, loading: settingsLoading } = useSiteSettings();
const pathname = usePathname();
const church = useChurch();
// The church's other sites from its profile in Accounts (3.7.0): its Website, later its App.
// Not on the dashboard, which stays as it is.
const otherSites = church && !pathname?.startsWith("/dashboard") ? productLinks(church.links, "events") : [];
const displayName = settings.org_name || appName;
const logoSrc = settings.logo_url ? resolveToApiOrigin(settings.logo_url) : null;
@@ -94,6 +100,11 @@ export const Navbar = () => {
{link.label}
</Link>
))}
{otherSites.map(site => (
<a key={site.href} href={site.href} className="text-sm pb-0.5 border-b-2 border-transparent text-gray-700 transition-colors hover:text-brand-600">
{site.label}
</a>
))}
{/* Auth links are only known once the token has been validated —
rendering nothing here (instead of guessing "logged out") avoids
@@ -0,0 +1,13 @@
"use client";
import React, { createContext, useContext } from "react";
import type { Church } from "@crosscode/contracts";
/** The church profile from Accounts (3.7.0), fetched once by the root layout; null without Accounts. */
const ChurchContext = createContext<Church | null>(null);
export function ChurchProvider({ church, children }: { church: Church | null; children: React.ReactNode }) {
return <ChurchContext.Provider value={church}>{children}</ChurchContext.Provider>;
}
export const useChurch = () => useContext(ChurchContext);
@@ -74271,6 +74271,648 @@
}
}
}
},
"/church": {
"get": {
"tags": [
"Site"
],
"summary": "The church's profile",
"description": "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.\n\n**Who:** Anyone.",
"operationId": "getChurch",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"anyOf": [
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.church/1"
},
"customerId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"updatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"shortName": {
"anyOf": [
{
"type": "string",
"maxLength": 30
},
{
"type": "null"
}
]
},
"timezone": {
"type": "string",
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
},
"locale": {
"type": "string",
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
},
"branding": {
"type": "object",
"properties": {
"logoUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"iconUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"colours": {
"type": "object",
"properties": {
"primary": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
"accent": {
"anyOf": [
{
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
{
"type": "null"
}
]
}
},
"required": [
"primary",
"accent"
],
"additionalProperties": false
},
"style": {
"type": "object",
"properties": {
"fontPairing": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"classic",
"scholarly",
"editorial",
"impact",
"contemporary",
"friendly",
"warm",
"modern"
]
},
{
"type": "null"
}
]
},
"corners": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"sharp",
"soft",
"round"
]
},
{
"type": "null"
}
]
}
},
"required": [
"fontPairing",
"corners"
],
"additionalProperties": false
}
},
"required": [
"logoUrl",
"iconUrl",
"colours"
],
"additionalProperties": false
},
"campuses": {
"maxItems": 50,
"type": "array",
"items": {
"type": "object",
"properties": {
"slug": {
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"slug",
"name",
"address"
],
"additionalProperties": false
}
},
"serviceTimes": {
"maxItems": 100,
"type": "array",
"items": {
"type": "object",
"properties": {
"day": {
"type": "string",
"enum": [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
]
},
"time": {
"type": "string",
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
},
"label": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"campus": {
"anyOf": [
{
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
{
"type": "null"
}
]
},
"note": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
}
},
"required": [
"day",
"time",
"label",
"campus",
"note"
],
"additionalProperties": false
}
},
"contact": {
"type": "object",
"properties": {
"email": {
"anyOf": [
{
"type": "string",
"maxLength": 254,
"format": "email",
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
},
{
"type": "null"
}
]
},
"phone": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"whatsapp": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"email",
"phone",
"whatsapp",
"address"
],
"additionalProperties": false
},
"social": {
"maxItems": 20,
"type": "array",
"items": {
"type": "object",
"properties": {
"network": {
"type": "string",
"enum": [
"facebook",
"instagram",
"youtube",
"tiktok",
"x",
"spotify",
"whatsapp-channel",
"other"
]
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"network",
"url"
],
"additionalProperties": false
}
},
"links": {
"type": "object",
"properties": {
"website": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"events": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"app": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"accounts": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"website",
"events",
"app",
"accounts"
],
"additionalProperties": false
}
},
"required": [
"schema",
"customerId",
"updatedAt",
"name",
"shortName",
"timezone",
"locale",
"branding",
"campuses",
"serviceTimes",
"contact",
"social",
"links"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
}
}
}
}
},
"components": {
+125
View File
@@ -7760,6 +7760,28 @@ export interface paths {
patch?: never;
trace?: never;
};
"/church": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The church's profile
* @description The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.
*
* **Who:** Anyone.
*/
get: operations["getChurch"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -40739,4 +40761,107 @@ export interface operations {
};
};
};
getChurch: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
schema: "crosscode.church/1";
/** Format: uuid */
customerId: string;
/** Format: date-time */
updatedAt: string;
name: string;
shortName: string | null;
timezone: string;
locale: string;
branding: {
logoUrl: string | null;
iconUrl: string | null;
colours: {
primary: string;
accent: string | null;
};
style?: {
/** @default null */
fontPairing: ("classic" | "scholarly" | "editorial" | "impact" | "contemporary" | "friendly" | "warm" | "modern") | null;
/** @default null */
corners: ("sharp" | "soft" | "round") | null;
};
};
campuses: {
slug: string;
name: string;
address: {
line1: string;
line2: string | null;
suburb: string | null;
city: string;
province: string | null;
postalCode: string | null;
country: string;
geo: {
lat: number;
lng: number;
} | null;
} | null;
}[];
serviceTimes: {
/** @enum {string} */
day: "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
time: string;
label: string | null;
campus: string | null;
note: string | null;
}[];
contact: {
email: string | null;
phone: string | null;
whatsapp: string | null;
address: {
line1: string;
line2: string | null;
suburb: string | null;
city: string;
province: string | null;
postalCode: string | null;
country: string;
geo: {
lat: number;
lng: number;
} | null;
} | null;
};
social: {
/** @enum {string} */
network: "facebook" | "instagram" | "youtube" | "tiktok" | "x" | "spotify" | "whatsapp-channel" | "other";
/** Format: uri */
url: string;
}[];
links: {
website: string | null;
events: string | null;
app: string | null;
/** Format: uri */
accounts: string;
};
} | null;
};
};
};
};
};
}
@@ -0,0 +1,19 @@
import type { Church } from "@crosscode/contracts";
import { API_BASE } from "@/lib/api";
/**
* The church profile from the church's Accounts (3.7.0), through the backend's
* `GET /api/v2/church`: the brand style for `<html>` and the shared footer. null when Accounts
* isn't connected or the backend can't be reached, and the pages look as they always have.
* Fetched the same way as getServerSettings, so Next dedupes it within a request.
*/
export async function getServerChurch(): Promise<Church | null> {
if (!API_BASE) return null;
try {
const res = await fetch(`${API_BASE}/api/v2/church`, { next: { revalidate: 60 } });
if (!res.ok) return null;
return ((await res.json())?.data as Church | null) ?? null;
} catch {
return null;
}
}
+4
View File
@@ -2,6 +2,8 @@
module.exports = {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
// The shared footer (3.7.0)
"../../../packages/ui/src/**/*.{ts,tsx}",
],
theme: {
extend: {
@@ -47,6 +49,8 @@ module.exports = {
// colorScale.ts's buildBrandScale + globals.css for the static
// fallback defaults used when no setting is saved yet).
brand: {
// `brand` alone (the shared footer's links, @crosscode/ui)
DEFAULT: "var(--brand-700)",
50: "var(--brand-50)",
100: "var(--brand-100)",
200: "var(--brand-200)",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.5.0",
"version": "3.7.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+11 -8
View File
@@ -116,7 +116,7 @@ else
echo " backend/.env exists — kept"
fi
if [ ! -f "$DIR/frontend/.env.production" ]; then
echo "NEXT_PUBLIC_API_URL=$SITE_URL" > "$DIR/frontend/.env.production"
printf 'NEXT_PUBLIC_API_URL=%s\nBACKEND_INTERNAL_URL=http://127.0.0.1:%s\n' "$SITE_URL" "$API_PORT" > "$DIR/frontend/.env.production"
fi
if [ ! -f "$DIR/ecosystem.config.js" ]; then
sed -e "s/'hope-events-backend'/'$NAME-backend'/" -e "s/'hope-events-frontend'/'$NAME-frontend'/" -e "s/-p 3000/-p $WEB_PORT/" \
@@ -140,14 +140,17 @@ server {
server_name $DOMAIN;
client_max_body_size 25m;
# For the backend locations below ("location /" sets its own).
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
# The API, uploaded files, health and API docs go to the backend; everything else to the site.
location ~ ^/(api|uploads|health|docs)(/|\$) {
proxy_pass http://127.0.0.1:$API_PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# ^~ so a regex location added later (e.g. caching *.png) can't send /api/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ~ ^/(api|uploads|health|docs)(/|\$) { proxy_pass http://127.0.0.1:$API_PORT; }
location / {
proxy_pass http://127.0.0.1:$WEB_PORT;
proxy_http_version 1.1;
+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
+195
View File
@@ -0,0 +1,195 @@
# Changelog — Church Website
## [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 4 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).
+50
View File
@@ -0,0 +1,50 @@
# 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.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/
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@crosscode/website-backend",
"version": "1.1.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",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"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
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
*
* npm run demo -- --template heritage|bold|community|clean [--force]
*
* It replaces the site's content, so a site that has been published needs --force.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { 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 { 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 template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
if (!template.success) {
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
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, template.data);
console.log(`Demo church loaded on ${template.data} 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 } });
}
+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();
}
+217
View File
@@ -0,0 +1,217 @@
/**
* 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';
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 }; }));
return r;
}

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